repo_id stringclasses 875
values | size int64 974 38.9k | file_path stringlengths 10 308 | content stringlengths 974 38.9k |
|---|---|---|---|
apache/gravitino | 36,370 | core/src/test/java/org/apache/gravitino/storage/relational/service/TestModelVersionMetaService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.gravitino.storage.relational.service;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.exceptions.IllegalNamespaceException;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.NonEmptyEntityException;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.ModelEntity;
import org.apache.gravitino.meta.ModelVersionEntity;
import org.apache.gravitino.model.ModelVersion;
import org.apache.gravitino.storage.RandomIdGenerator;
import org.apache.gravitino.storage.relational.TestJDBCBackend;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
public class TestModelVersionMetaService extends TestJDBCBackend {
private static final String METALAKE_NAME = "metalake_for_model_version_meta_test";
private static final String CATALOG_NAME = "catalog_for_model_version_meta_test";
private static final String SCHEMA_NAME = "schema_for_model_version_meta_test";
private static final Namespace MODEL_NS = Namespace.of(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME);
private final AuditInfo auditInfo =
AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build();
private final Map<String, String> properties = ImmutableMap.of("k1", "v1");
private final List<String> aliases = Lists.newArrayList("alias1", "alias2");
@Test
public void testInsertAndSelectModelVersion() throws IOException {
createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);
// Create a model entity
ModelEntity modelEntity =
createModelEntity(
RandomIdGenerator.INSTANCE.nextId(),
MODEL_NS,
"model1",
"model1 comment",
0,
properties,
auditInfo);
Assertions.assertDoesNotThrow(
() -> ModelMetaService.getInstance().insertModel(modelEntity, false));
// Create a model version entity
ModelVersionEntity modelVersionEntity =
createModelVersionEntity(
modelEntity.nameIdentifier(),
0,
ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "model_path"),
aliases,
"test comment",
properties,
auditInfo);
Assertions.assertDoesNotThrow(
() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity));
// Test if the model version can be retrieved by the identifier
Assertions.assertEquals(
modelVersionEntity,
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(getModelVersionIdent(modelEntity.nameIdentifier(), 0)));
Assertions.assertEquals(
modelVersionEntity,
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(
getModelVersionIdent(modelEntity.nameIdentifier(), "alias1")));
Assertions.assertEquals(
modelVersionEntity,
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(
getModelVersionIdent(modelEntity.nameIdentifier(), "alias2")));
// Test insert again to get a new version number
ModelVersionEntity modelVersionEntity2 =
createModelVersionEntity(
modelEntity.nameIdentifier(),
1,
ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "model_path"),
null,
null,
null,
auditInfo);
Assertions.assertDoesNotThrow(
() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity2));
// Test if the new model version can be retrieved by the identifier
Assertions.assertEquals(
modelVersionEntity2,
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(getModelVersionIdent(modelEntity.nameIdentifier(), 1)));
// Test if the old model version can still be retrieved by the identifier
Assertions.assertEquals(
modelVersionEntity,
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(getModelVersionIdent(modelEntity.nameIdentifier(), 0)));
// Test if the old model version can still be retrieved by the alias
Assertions.assertEquals(
modelVersionEntity,
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(
getModelVersionIdent(modelEntity.nameIdentifier(), "alias1")));
// Test fetch a non-exist model version
Assertions.assertThrows(
NoSuchEntityException.class,
() ->
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(
getModelVersionIdent(modelEntity.nameIdentifier(), 2)));
// Test fetch a non-exist model alias
Assertions.assertThrows(
NoSuchEntityException.class,
() ->
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(
getModelVersionIdent(modelEntity.nameIdentifier(), "alias3")));
// Test fetch from a non-exist model
Assertions.assertThrows(
NoSuchEntityException.class,
() ->
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(
getModelVersionIdent(NameIdentifier.of(MODEL_NS, "model2"), 0)));
// Model latest version should be updated
ModelEntity registeredModelEntity =
ModelMetaService.getInstance().getModelByIdentifier(modelEntity.nameIdentifier());
Assertions.assertEquals(2, registeredModelEntity.latestVersion());
// Test fetch from an invalid model version
Assertions.assertThrows(
IllegalNamespaceException.class,
() ->
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(NameIdentifier.of(MODEL_NS, "model1")));
// Throw NoSuchEntityException if the model does not exist
ModelVersionEntity modelVersionEntity3 =
createModelVersionEntity(
NameIdentifier.of(MODEL_NS, "model2"),
1,
ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "model_path"),
aliases,
"test comment",
properties,
auditInfo);
Assertions.assertThrows(
NoSuchEntityException.class,
() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity3));
}
@Test
public void testInsertAndListModelVersions() throws IOException {
createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);
// Create a model entity
ModelEntity modelEntity =
createModelEntity(
RandomIdGenerator.INSTANCE.nextId(),
MODEL_NS,
"model1",
"model1 comment",
0,
properties,
auditInfo);
Assertions.assertDoesNotThrow(
() -> ModelMetaService.getInstance().insertModel(modelEntity, false));
// Create a model version entity
ModelVersionEntity modelVersionEntity =
createModelVersionEntity(
modelEntity.nameIdentifier(),
0,
ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "model_path"),
aliases,
"test comment",
properties,
auditInfo);
Assertions.assertDoesNotThrow(
() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity));
List<ModelVersionEntity> modelVersions =
ModelVersionMetaService.getInstance()
.listModelVersionsByNamespace(getModelVersionNs(modelEntity.nameIdentifier()));
Assertions.assertEquals(1, modelVersions.size());
Assertions.assertEquals(modelVersionEntity, modelVersions.get(0));
// Test insert again to get a new version number
ModelVersionEntity modelVersionEntity2 =
createModelVersionEntity(
modelEntity.nameIdentifier(),
1,
ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "model_path"),
null,
null,
null,
auditInfo);
Assertions.assertDoesNotThrow(
() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity2));
List<ModelVersionEntity> modelVersions2 =
ModelVersionMetaService.getInstance()
.listModelVersionsByNamespace(getModelVersionNs(modelEntity.nameIdentifier()));
Map<Integer, ModelVersionEntity> modelVersionMap =
modelVersions2.stream().collect(Collectors.toMap(ModelVersionEntity::version, v -> v));
Assertions.assertEquals(2, modelVersions2.size());
Assertions.assertEquals(modelVersionEntity, modelVersionMap.get(0));
Assertions.assertEquals(modelVersionEntity2, modelVersionMap.get(1));
// List model versions from a non-exist model
Assertions.assertThrows(
NoSuchEntityException.class,
() ->
ModelVersionMetaService.getInstance()
.listModelVersionsByNamespace(
getModelVersionNs(NameIdentifier.of(MODEL_NS, "model2"))));
}
@Test
public void testInsertAndDeleteModelVersion() throws IOException {
createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);
// Create a model entity
ModelEntity modelEntity =
createModelEntity(
RandomIdGenerator.INSTANCE.nextId(),
MODEL_NS,
"model1",
"model1 comment",
0,
properties,
auditInfo);
Assertions.assertDoesNotThrow(
() -> ModelMetaService.getInstance().insertModel(modelEntity, false));
// Create a model version entity
ModelVersionEntity modelVersionEntity =
createModelVersionEntity(
modelEntity.nameIdentifier(),
0,
ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "model_path"),
aliases,
"test comment",
properties,
auditInfo);
Assertions.assertDoesNotThrow(
() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity));
// Test using a non-exist model version to delete
Assertions.assertFalse(
ModelVersionMetaService.getInstance()
.deleteModelVersion(getModelVersionIdent(modelEntity.nameIdentifier(), 100)));
// Test delete the model version
Assertions.assertTrue(
ModelVersionMetaService.getInstance()
.deleteModelVersion(getModelVersionIdent(modelEntity.nameIdentifier(), 0)));
// Test fetch a non-exist model version
Assertions.assertThrows(
NoSuchEntityException.class,
() ->
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(
getModelVersionIdent(modelEntity.nameIdentifier(), 0)));
// Test delete a non-exist model version
Assertions.assertFalse(
ModelVersionMetaService.getInstance()
.deleteModelVersion(getModelVersionIdent(modelEntity.nameIdentifier(), 0)));
// Test delete a non-exist model version
Assertions.assertFalse(
ModelVersionMetaService.getInstance()
.deleteModelVersion(getModelVersionIdent(modelEntity.nameIdentifier(), 1)));
// Test delete from a non-exist model
Assertions.assertFalse(
ModelVersionMetaService.getInstance()
.deleteModelVersion(getModelVersionIdent(NameIdentifier.of(MODEL_NS, "model2"), 0)));
// Test delete by alias
ModelVersionEntity modelVersionEntity2 =
createModelVersionEntity(
modelEntity.nameIdentifier(),
1,
ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "model_path"),
aliases,
"test comment",
properties,
auditInfo);
Assertions.assertDoesNotThrow(
() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity2));
ModelVersionEntity registeredModelVersionEntity =
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(
getModelVersionIdent(modelEntity.nameIdentifier(), "alias1"));
Assertions.assertEquals(1, registeredModelVersionEntity.version());
ModelEntity registeredModelEntity =
ModelMetaService.getInstance().getModelByIdentifier(modelEntity.nameIdentifier());
Assertions.assertEquals(2, registeredModelEntity.latestVersion());
// Test delete by a non-exist alias
Assertions.assertFalse(
ModelVersionMetaService.getInstance()
.deleteModelVersion(getModelVersionIdent(modelEntity.nameIdentifier(), "alias3")));
// Test delete by an exist alias
Assertions.assertTrue(
ModelVersionMetaService.getInstance()
.deleteModelVersion(getModelVersionIdent(modelEntity.nameIdentifier(), "alias1")));
// Test delete again by the same alias
Assertions.assertFalse(
ModelVersionMetaService.getInstance()
.deleteModelVersion(getModelVersionIdent(modelEntity.nameIdentifier(), "alias1")));
// Test fetch a non-exist model version
Assertions.assertThrows(
NoSuchEntityException.class,
() ->
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(
getModelVersionIdent(modelEntity.nameIdentifier(), "alias1")));
Assertions.assertThrows(
NoSuchEntityException.class,
() ->
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(
getModelVersionIdent(modelEntity.nameIdentifier(), "alias2")));
}
@Test
public void testModelVersionWithMultipleUris() throws IOException {
createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);
// Create a model entity
ModelEntity modelEntity =
createModelEntity(
RandomIdGenerator.INSTANCE.nextId(),
MODEL_NS,
"model1",
"model1 comment",
0,
properties,
auditInfo);
Assertions.assertDoesNotThrow(
() -> ModelMetaService.getInstance().insertModel(modelEntity, false));
// Create a model version entity with multiple URIs
ModelVersionEntity modelVersionEntity =
createModelVersionEntity(
modelEntity.nameIdentifier(),
0,
ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "uri1", "uri-name-2", "uri2"),
aliases,
"test comment",
properties,
auditInfo);
Assertions.assertDoesNotThrow(
() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity));
// Test if the model version can be retrieved by the identifier
Assertions.assertEquals(
modelVersionEntity,
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(getModelVersionIdent(modelEntity.nameIdentifier(), 0)));
Assertions.assertEquals(
modelVersionEntity,
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(
getModelVersionIdent(modelEntity.nameIdentifier(), "alias1")));
Assertions.assertEquals(
modelVersionEntity,
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(
getModelVersionIdent(modelEntity.nameIdentifier(), "alias2")));
// Test list model versions
List<ModelVersionEntity> modelVersions =
ModelVersionMetaService.getInstance()
.listModelVersionsByNamespace(getModelVersionNs(modelEntity.nameIdentifier()));
Assertions.assertEquals(1, modelVersions.size());
Assertions.assertEquals(modelVersionEntity, modelVersions.get(0));
// Test update model version
ModelVersionEntity updatedModelVersionEntity =
createModelVersionEntity(
modelVersionEntity.modelIdentifier(),
modelVersionEntity.version(),
ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "uri1-updated", "uri-name-2", "uri2"),
ImmutableList.of("alias2", "alias3"),
"updated comment",
ImmutableMap.of("k1", "v1", "k2", "v2"),
modelVersionEntity.auditInfo());
Function<ModelVersionEntity, ModelVersionEntity> updatePropertiesUpdater =
oldModelVersionEntity -> updatedModelVersionEntity;
ModelVersionEntity alteredModelVersionEntity =
ModelVersionMetaService.getInstance()
.updateModelVersion(modelVersionEntity.nameIdentifier(), updatePropertiesUpdater);
Assertions.assertEquals(updatedModelVersionEntity, alteredModelVersionEntity);
// Test if the model version is updated
Assertions.assertEquals(
updatedModelVersionEntity,
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(getModelVersionIdent(modelEntity.nameIdentifier(), 0)));
// Test delete the model version
Assertions.assertTrue(
ModelVersionMetaService.getInstance()
.deleteModelVersion(getModelVersionIdent(modelEntity.nameIdentifier(), 0)));
// Test fetch a non-exist model version
Assertions.assertThrows(
NoSuchEntityException.class,
() ->
ModelVersionMetaService.getInstance()
.getModelVersionByIdentifier(
getModelVersionIdent(modelEntity.nameIdentifier(), 0)));
}
@ParameterizedTest
@ValueSource(strings = {"model", "schema", "catalog", "metalake"})
public void testDeleteModelVersionsInDeletion(String input) throws IOException {
createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);
// Create a model entity
ModelEntity modelEntity =
createModelEntity(
RandomIdGenerator.INSTANCE.nextId(),
MODEL_NS,
"model1",
"model1 comment",
0,
properties,
auditInfo);
Assertions.assertDoesNotThrow(
() -> ModelMetaService.getInstance().insertModel(modelEntity, false));
// Create a model version entity
ModelVersionEntity modelVersionEntity =
createModelVersionEntity(
modelEntity.nameIdentifier(),
0,
ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "model_path"),
aliases,
"test comment",
properties,
auditInfo);
Assertions.assertDoesNotThrow(
() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity));
ModelVersionEntity modelVersionEntity1 =
createModelVersionEntity(
modelEntity.nameIdentifier(),
1,
ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "model_path"),
null,
null,
null,
auditInfo);
Assertions.assertDoesNotThrow(
() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity1));
if (input.equals("model")) {
// Test delete the model
Assertions.assertTrue(
ModelMetaService.getInstance().deleteModel(modelEntity.nameIdentifier()));
} else if (input.equals("schema")) {
NameIdentifier schemaIdent = NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME);
Assertions.assertThrows(
NonEmptyEntityException.class,
() -> SchemaMetaService.getInstance().deleteSchema(schemaIdent, false));
// Test delete the schema with cascade
Assertions.assertTrue(SchemaMetaService.getInstance().deleteSchema(schemaIdent, true));
} else if (input.equals("catalog")) {
NameIdentifier catalogIdent = NameIdentifier.of(METALAKE_NAME, CATALOG_NAME);
Assertions.assertThrows(
NonEmptyEntityException.class,
() -> CatalogMetaService.getInstance().deleteCatalog(catalogIdent, false));
// Test delete the catalog with cascade
Assertions.assertTrue(CatalogMetaService.getInstance().deleteCatalog(catalogIdent, true));
} else if (input.equals("metalake")) {
NameIdentifier metalakeIdent = NameIdentifier.of(METALAKE_NAME);
Assertions.assertThrows(
NonEmptyEntityException.class,
() -> MetalakeMetaService.getInstance().deleteMetalake(metalakeIdent, false));
// Test delete the metalake with cascade
Assertions.assertTrue(MetalakeMetaService.getInstance().deleteMetalake(metalakeIdent, true));
}
// Test fetch a non-exist model
Assertions.assertThrows(
NoSuchEntityException.class,
() -> ModelMetaService.getInstance().getModelByIdentifier(modelEntity.nameIdentifier()));
// Test list the model versions
Assertions.assertThrows(
NoSuchEntityException.class,
() ->
ModelVersionMetaService.getInstance()
.listModelVersionsByNamespace(getModelVersionNs(modelEntity.nameIdentifier())));
// Test fetch a non-exist model version
verifyModelVersionExists(getModelVersionIdent(modelEntity.nameIdentifier(), 0));
verifyModelVersionExists(getModelVersionIdent(modelEntity.nameIdentifier(), 1));
verifyModelVersionExists(getModelVersionIdent(modelEntity.nameIdentifier(), "alias1"));
verifyModelVersionExists(getModelVersionIdent(modelEntity.nameIdentifier(), "alias2"));
}
@Test
void testUpdateVersionComment() throws IOException {
createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);
Map<String, String> properties = ImmutableMap.of("k1", "v1");
String modelName = randomModelName();
String modelComment = "model1 comment";
String modelVersionUri = "S3://test/path/to/model/version";
List<String> modelVersionAliases = ImmutableList.of("alias1", "alias2");
String modelVersionComment = "test comment";
String updatedComment = "new comment";
int version = 0;
ModelEntity modelEntity =
createModelEntity(
RandomIdGenerator.INSTANCE.nextId(),
MODEL_NS,
modelName,
modelComment,
0,
properties,
auditInfo);
ModelVersionEntity modelVersionEntity =
createModelVersionEntity(
modelEntity.nameIdentifier(),
version,
ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, modelVersionUri),
modelVersionAliases,
modelVersionComment,
properties,
auditInfo);
ModelVersionEntity updatedModelVersionEntity =
createModelVersionEntity(
modelVersionEntity.modelIdentifier(),
modelVersionEntity.version(),
modelVersionEntity.uris(),
modelVersionEntity.aliases(),
updatedComment,
modelVersionEntity.properties(),
modelVersionEntity.auditInfo());
Assertions.assertDoesNotThrow(
() -> ModelMetaService.getInstance().insertModel(modelEntity, false));
Assertions.assertDoesNotThrow(
() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity));
Function<ModelVersionEntity, ModelVersionEntity> updateCommentUpdater =
oldModelVersionEntity -> updatedModelVersionEntity;
ModelVersionEntity alteredModelVersionEntity =
ModelVersionMetaService.getInstance()
.updateModelVersion(modelVersionEntity.nameIdentifier(), updateCommentUpdater);
Assertions.assertEquals(updatedModelVersionEntity, alteredModelVersionEntity);
// Test update a non-exist model
Assertions.assertThrows(
NoSuchEntityException.class,
() ->
ModelVersionMetaService.getInstance()
.updateModelVersion(
NameIdentifierUtil.ofModelVersion(
METALAKE_NAME,
CATALOG_NAME,
SCHEMA_NAME,
"non_exist_model",
"non_exist_version"),
updateCommentUpdater));
// Test update a non-exist model version
Assertions.assertThrows(
NoSuchEntityException.class,
() ->
ModelVersionMetaService.getInstance()
.updateModelVersion(
NameIdentifierUtil.ofModelVersion(
METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, modelName, "non_exist_version"),
updateCommentUpdater));
}
@Test
void testAlterModelVersionProperties() throws IOException {
createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);
Map<String, String> properties = ImmutableMap.of("k1", "v1", "k2", "v2");
String modelName = randomModelName();
String modelComment = "model1 comment";
String modelVersionUri = "S3://test/path/to/model/version";
List<String> modelVersionAliases = ImmutableList.of("alias1", "alias2");
String modelVersionComment = "test comment";
Map<String, String> updatedProperties =
ImmutableMap.of("k1", "new value", "k2", "v2", "k3", "v3");
int version = 0;
ModelEntity modelEntity =
createModelEntity(
RandomIdGenerator.INSTANCE.nextId(),
MODEL_NS,
modelName,
modelComment,
0,
properties,
auditInfo);
ModelVersionEntity modelVersionEntity =
createModelVersionEntity(
modelEntity.nameIdentifier(),
version,
ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, modelVersionUri),
modelVersionAliases,
modelVersionComment,
properties,
auditInfo);
ModelVersionEntity updatedModelVersionEntity =
createModelVersionEntity(
modelVersionEntity.modelIdentifier(),
modelVersionEntity.version(),
modelVersionEntity.uris(),
modelVersionEntity.aliases(),
modelVersionEntity.comment(),
updatedProperties,
modelVersionEntity.auditInfo());
Assertions.assertDoesNotThrow(
() -> ModelMetaService.getInstance().insertModel(modelEntity, false));
Assertions.assertDoesNotThrow(
() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity));
Function<ModelVersionEntity, ModelVersionEntity> updatePropertiesUpdater =
oldModelVersionEntity -> updatedModelVersionEntity;
ModelVersionEntity alteredModelVersionEntity =
ModelVersionMetaService.getInstance()
.updateModelVersion(modelVersionEntity.nameIdentifier(), updatePropertiesUpdater);
Assertions.assertEquals(updatedModelVersionEntity, alteredModelVersionEntity);
// Test update a non-exist model
Assertions.assertThrows(
NoSuchEntityException.class,
() ->
ModelVersionMetaService.getInstance()
.updateModelVersion(
NameIdentifierUtil.ofModelVersion(
METALAKE_NAME,
CATALOG_NAME,
SCHEMA_NAME,
"non_exist_model",
"non_exist_version"),
updatePropertiesUpdater));
// Test update a non-exist model version
Assertions.assertThrows(
NoSuchEntityException.class,
() ->
ModelVersionMetaService.getInstance()
.updateModelVersion(
NameIdentifierUtil.ofModelVersion(
METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, modelName, "non_exist_version"),
updatePropertiesUpdater));
}
@Test
void testUpdateModelVersionUri() throws IOException {
createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);
Map<String, String> properties = ImmutableMap.of("k1", "v1", "k2", "v2");
String modelName = randomModelName();
String modelComment = "model1 comment";
Map<String, String> modelVersionUris = ImmutableMap.of("n1", "u1");
List<String> modelVersionAliases = ImmutableList.of("alias1", "alias2");
String modelVersionComment = "test comment";
int version = 0;
ModelEntity modelEntity =
createModelEntity(
RandomIdGenerator.INSTANCE.nextId(),
MODEL_NS,
modelName,
modelComment,
0,
properties,
auditInfo);
ModelVersionEntity modelVersionEntity =
createModelVersionEntity(
modelEntity.nameIdentifier(),
version,
modelVersionUris,
modelVersionAliases,
modelVersionComment,
properties,
auditInfo);
Map<String, String> newModelVersionUris = ImmutableMap.of("n1", "u1-1", "n2", "u2");
ModelVersionEntity updatedModelVersionEntity =
createModelVersionEntity(
modelVersionEntity.modelIdentifier(),
modelVersionEntity.version(),
newModelVersionUris,
modelVersionEntity.aliases(),
modelVersionEntity.comment(),
modelVersionEntity.properties(),
modelVersionEntity.auditInfo());
Assertions.assertDoesNotThrow(
() -> ModelMetaService.getInstance().insertModel(modelEntity, false));
Assertions.assertDoesNotThrow(
() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity));
Function<ModelVersionEntity, ModelVersionEntity> updatePropertiesUpdater =
oldModelVersionEntity -> updatedModelVersionEntity;
ModelVersionEntity alteredModelVersionEntity =
ModelVersionMetaService.getInstance()
.updateModelVersion(modelVersionEntity.nameIdentifier(), updatePropertiesUpdater);
Assertions.assertEquals(updatedModelVersionEntity, alteredModelVersionEntity);
// Test update a non-exist model
Assertions.assertThrows(
NoSuchEntityException.class,
() ->
ModelVersionMetaService.getInstance()
.updateModelVersion(
NameIdentifierUtil.ofModelVersion(
METALAKE_NAME,
CATALOG_NAME,
SCHEMA_NAME,
"non_exist_model",
"non_exist_version"),
updatePropertiesUpdater));
// Test update a non-exist model version
Assertions.assertThrows(
NoSuchEntityException.class,
() ->
ModelVersionMetaService.getInstance()
.updateModelVersion(
NameIdentifierUtil.ofModelVersion(
METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, modelName, "non_exist_version"),
updatePropertiesUpdater));
}
@Test
void testUpdateModelVersionAliases() throws IOException {
createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);
Map<String, String> properties = ImmutableMap.of("k1", "v1", "k2", "v2");
String modelName = randomModelName();
String modelComment = "model1 comment";
String modelVersionUri = "S3://test/path/to/model/version";
List<String> modelVersionAliases = ImmutableList.of("alias1", "alias2");
List<String> updatedVersionAliases = ImmutableList.of("alias2", "alias3");
String modelVersionComment = "test comment";
int version = 0;
ModelEntity modelEntity =
createModelEntity(
RandomIdGenerator.INSTANCE.nextId(),
MODEL_NS,
modelName,
modelComment,
0,
properties,
auditInfo);
ModelVersionEntity modelVersionEntity =
createModelVersionEntity(
modelEntity.nameIdentifier(),
version,
ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, modelVersionUri),
modelVersionAliases,
modelVersionComment,
properties,
auditInfo);
ModelVersionEntity updatedModelVersionEntity =
createModelVersionEntity(
modelVersionEntity.modelIdentifier(),
modelVersionEntity.version(),
modelVersionEntity.uris(),
updatedVersionAliases,
modelVersionEntity.comment(),
modelVersionEntity.properties(),
modelVersionEntity.auditInfo());
Assertions.assertDoesNotThrow(
() -> ModelMetaService.getInstance().insertModel(modelEntity, false));
Assertions.assertDoesNotThrow(
() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity));
Function<ModelVersionEntity, ModelVersionEntity> updatePropertiesUpdater =
oldModelVersionEntity -> updatedModelVersionEntity;
ModelVersionEntity alteredModelVersionEntity =
ModelVersionMetaService.getInstance()
.updateModelVersion(modelVersionEntity.nameIdentifier(), updatePropertiesUpdater);
Assertions.assertEquals(updatedModelVersionEntity, alteredModelVersionEntity);
// Test update a non-exist model
Assertions.assertThrows(
NoSuchEntityException.class,
() ->
ModelVersionMetaService.getInstance()
.updateModelVersion(
NameIdentifierUtil.ofModelVersion(
METALAKE_NAME,
CATALOG_NAME,
SCHEMA_NAME,
"non_exist_model",
"non_exist_version"),
updatePropertiesUpdater));
// Test update a non-exist model version
Assertions.assertThrows(
NoSuchEntityException.class,
() ->
ModelVersionMetaService.getInstance()
.updateModelVersion(
NameIdentifierUtil.ofModelVersion(
METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, modelName, "non_exist_version"),
updatePropertiesUpdater));
}
private NameIdentifier getModelVersionIdent(NameIdentifier modelIdent, int version) {
List<String> parts = Lists.newArrayList(modelIdent.namespace().levels());
parts.add(modelIdent.name());
parts.add(String.valueOf(version));
return NameIdentifier.of(parts.toArray(new String[0]));
}
private NameIdentifier getModelVersionIdent(NameIdentifier modelIdent, String alias) {
List<String> parts = Lists.newArrayList(modelIdent.namespace().levels());
parts.add(modelIdent.name());
parts.add(alias);
return NameIdentifier.of(parts.toArray(new String[0]));
}
private Namespace getModelVersionNs(NameIdentifier modelIdent) {
List<String> parts = Lists.newArrayList(modelIdent.namespace().levels());
parts.add(modelIdent.name());
return Namespace.of(parts.toArray(new String[0]));
}
private void verifyModelVersionExists(NameIdentifier ident) {
Assertions.assertThrows(
NoSuchEntityException.class,
() -> ModelVersionMetaService.getInstance().getModelVersionByIdentifier(ident));
Assertions.assertFalse(ModelVersionMetaService.getInstance().deleteModelVersion(ident));
}
private String randomModelName() {
return "model_" + UUID.randomUUID().toString().replace("-", "");
}
}
|
googleapis/google-cloud-java | 36,363 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/ListModelsResponse.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/model_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1;
/**
*
*
* <pre>
* Response message for
* [ModelService.ListModels][google.cloud.aiplatform.v1beta1.ModelService.ListModels]
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.ListModelsResponse}
*/
public final class ListModelsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.ListModelsResponse)
ListModelsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListModelsResponse.newBuilder() to construct.
private ListModelsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListModelsResponse() {
models_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListModelsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.ModelServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListModelsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.ModelServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListModelsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.ListModelsResponse.class,
com.google.cloud.aiplatform.v1beta1.ListModelsResponse.Builder.class);
}
public static final int MODELS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.aiplatform.v1beta1.Model> models_;
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.aiplatform.v1beta1.Model> getModelsList() {
return models_;
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.ModelOrBuilder>
getModelsOrBuilderList() {
return models_;
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
@java.lang.Override
public int getModelsCount() {
return models_.size();
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.Model getModels(int index) {
return models_.get(index);
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ModelOrBuilder getModelsOrBuilder(int index) {
return models_.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
* [ListModelsRequest.page_token][google.cloud.aiplatform.v1beta1.ListModelsRequest.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
* [ListModelsRequest.page_token][google.cloud.aiplatform.v1beta1.ListModelsRequest.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 < models_.size(); i++) {
output.writeMessage(1, models_.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 < models_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, models_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.aiplatform.v1beta1.ListModelsResponse)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.ListModelsResponse other =
(com.google.cloud.aiplatform.v1beta1.ListModelsResponse) obj;
if (!getModelsList().equals(other.getModelsList())) 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 (getModelsCount() > 0) {
hash = (37 * hash) + MODELS_FIELD_NUMBER;
hash = (53 * hash) + getModelsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1beta1.ListModelsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListModelsResponse 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.ListModelsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListModelsResponse 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.ListModelsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListModelsResponse 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.ListModelsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.ListModelsResponse 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.ListModelsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.ListModelsResponse 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.ListModelsResponse 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.ListModelsResponse 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.ListModelsResponse 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
* [ModelService.ListModels][google.cloud.aiplatform.v1beta1.ModelService.ListModels]
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.ListModelsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.ListModelsResponse)
com.google.cloud.aiplatform.v1beta1.ListModelsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.ModelServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListModelsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.ModelServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListModelsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.ListModelsResponse.class,
com.google.cloud.aiplatform.v1beta1.ListModelsResponse.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.ListModelsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (modelsBuilder_ == null) {
models_ = java.util.Collections.emptyList();
} else {
models_ = null;
modelsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1beta1.ModelServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListModelsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListModelsResponse getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.ListModelsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListModelsResponse build() {
com.google.cloud.aiplatform.v1beta1.ListModelsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListModelsResponse buildPartial() {
com.google.cloud.aiplatform.v1beta1.ListModelsResponse result =
new com.google.cloud.aiplatform.v1beta1.ListModelsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.aiplatform.v1beta1.ListModelsResponse result) {
if (modelsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
models_ = java.util.Collections.unmodifiableList(models_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.models_ = models_;
} else {
result.models_ = modelsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.aiplatform.v1beta1.ListModelsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.aiplatform.v1beta1.ListModelsResponse) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.ListModelsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.ListModelsResponse other) {
if (other == com.google.cloud.aiplatform.v1beta1.ListModelsResponse.getDefaultInstance())
return this;
if (modelsBuilder_ == null) {
if (!other.models_.isEmpty()) {
if (models_.isEmpty()) {
models_ = other.models_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureModelsIsMutable();
models_.addAll(other.models_);
}
onChanged();
}
} else {
if (!other.models_.isEmpty()) {
if (modelsBuilder_.isEmpty()) {
modelsBuilder_.dispose();
modelsBuilder_ = null;
models_ = other.models_;
bitField0_ = (bitField0_ & ~0x00000001);
modelsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getModelsFieldBuilder()
: null;
} else {
modelsBuilder_.addAllMessages(other.models_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.aiplatform.v1beta1.Model m =
input.readMessage(
com.google.cloud.aiplatform.v1beta1.Model.parser(), extensionRegistry);
if (modelsBuilder_ == null) {
ensureModelsIsMutable();
models_.add(m);
} else {
modelsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.aiplatform.v1beta1.Model> models_ =
java.util.Collections.emptyList();
private void ensureModelsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
models_ = new java.util.ArrayList<com.google.cloud.aiplatform.v1beta1.Model>(models_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Model,
com.google.cloud.aiplatform.v1beta1.Model.Builder,
com.google.cloud.aiplatform.v1beta1.ModelOrBuilder>
modelsBuilder_;
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.Model> getModelsList() {
if (modelsBuilder_ == null) {
return java.util.Collections.unmodifiableList(models_);
} else {
return modelsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public int getModelsCount() {
if (modelsBuilder_ == null) {
return models_.size();
} else {
return modelsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Model getModels(int index) {
if (modelsBuilder_ == null) {
return models_.get(index);
} else {
return modelsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public Builder setModels(int index, com.google.cloud.aiplatform.v1beta1.Model value) {
if (modelsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureModelsIsMutable();
models_.set(index, value);
onChanged();
} else {
modelsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public Builder setModels(
int index, com.google.cloud.aiplatform.v1beta1.Model.Builder builderForValue) {
if (modelsBuilder_ == null) {
ensureModelsIsMutable();
models_.set(index, builderForValue.build());
onChanged();
} else {
modelsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public Builder addModels(com.google.cloud.aiplatform.v1beta1.Model value) {
if (modelsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureModelsIsMutable();
models_.add(value);
onChanged();
} else {
modelsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public Builder addModels(int index, com.google.cloud.aiplatform.v1beta1.Model value) {
if (modelsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureModelsIsMutable();
models_.add(index, value);
onChanged();
} else {
modelsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public Builder addModels(com.google.cloud.aiplatform.v1beta1.Model.Builder builderForValue) {
if (modelsBuilder_ == null) {
ensureModelsIsMutable();
models_.add(builderForValue.build());
onChanged();
} else {
modelsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public Builder addModels(
int index, com.google.cloud.aiplatform.v1beta1.Model.Builder builderForValue) {
if (modelsBuilder_ == null) {
ensureModelsIsMutable();
models_.add(index, builderForValue.build());
onChanged();
} else {
modelsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public Builder addAllModels(
java.lang.Iterable<? extends com.google.cloud.aiplatform.v1beta1.Model> values) {
if (modelsBuilder_ == null) {
ensureModelsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, models_);
onChanged();
} else {
modelsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public Builder clearModels() {
if (modelsBuilder_ == null) {
models_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
modelsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public Builder removeModels(int index) {
if (modelsBuilder_ == null) {
ensureModelsIsMutable();
models_.remove(index);
onChanged();
} else {
modelsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Model.Builder getModelsBuilder(int index) {
return getModelsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.ModelOrBuilder getModelsOrBuilder(int index) {
if (modelsBuilder_ == null) {
return models_.get(index);
} else {
return modelsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.ModelOrBuilder>
getModelsOrBuilderList() {
if (modelsBuilder_ != null) {
return modelsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(models_);
}
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Model.Builder addModelsBuilder() {
return getModelsFieldBuilder()
.addBuilder(com.google.cloud.aiplatform.v1beta1.Model.getDefaultInstance());
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Model.Builder addModelsBuilder(int index) {
return getModelsFieldBuilder()
.addBuilder(index, com.google.cloud.aiplatform.v1beta1.Model.getDefaultInstance());
}
/**
*
*
* <pre>
* List of Models in the requested page.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Model models = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.Model.Builder>
getModelsBuilderList() {
return getModelsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Model,
com.google.cloud.aiplatform.v1beta1.Model.Builder,
com.google.cloud.aiplatform.v1beta1.ModelOrBuilder>
getModelsFieldBuilder() {
if (modelsBuilder_ == null) {
modelsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Model,
com.google.cloud.aiplatform.v1beta1.Model.Builder,
com.google.cloud.aiplatform.v1beta1.ModelOrBuilder>(
models_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
models_ = null;
}
return modelsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token to retrieve next page of results.
* Pass to
* [ListModelsRequest.page_token][google.cloud.aiplatform.v1beta1.ListModelsRequest.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
* [ListModelsRequest.page_token][google.cloud.aiplatform.v1beta1.ListModelsRequest.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
* [ListModelsRequest.page_token][google.cloud.aiplatform.v1beta1.ListModelsRequest.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
* [ListModelsRequest.page_token][google.cloud.aiplatform.v1beta1.ListModelsRequest.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
* [ListModelsRequest.page_token][google.cloud.aiplatform.v1beta1.ListModelsRequest.page_token]
* to obtain that page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.ListModelsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.ListModelsResponse)
private static final com.google.cloud.aiplatform.v1beta1.ListModelsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.ListModelsResponse();
}
public static com.google.cloud.aiplatform.v1beta1.ListModelsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListModelsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListModelsResponse>() {
@java.lang.Override
public ListModelsResponse 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<ListModelsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListModelsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListModelsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/tomee | 36,113 | container/openejb-jee/src/main/java/org/apache/openejb/jee/oejb2/EntityBeanType.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.openejb.jee.oejb2;
import org.apache.openejb.jee.oejb3.PropertiesAdapter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import jakarta.xml.bind.JAXBElement;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlElementRef;
import jakarta.xml.bind.annotation.XmlID;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.adapters.CollapsedStringAdapter;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for entity-beanType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="entity-beanType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ejb-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="jndi-name" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* <element name="local-jndi-name" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* <group ref="{http://tomee.apache.org/xml/ns/openejb-jar-2.2}tssGroup" minOccurs="0"/>
* <sequence minOccurs="0">
* <element name="table-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="static-sql" type="{http://geronimo.apache.org/xml/ns/deployment-1.2}emptyType" minOccurs="0"/>
* <element name="cmp-field-mapping" maxOccurs="unbounded">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cmp-field-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="cmp-field-class" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="table-column" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="sql-type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="type-converter" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="primkey-field" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element ref="{http://tomee.apache.org/xml/ns/pkgen-2.1}key-generator" minOccurs="0"/>
* <element name="prefetch-group" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="group" type="{http://tomee.apache.org/xml/ns/openejb-jar-2.2}groupType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="entity-group-mapping" type="{http://tomee.apache.org/xml/ns/openejb-jar-2.2}entity-group-mappingType" minOccurs="0"/>
* <element name="cmp-field-group-mapping" type="{http://tomee.apache.org/xml/ns/openejb-jar-2.2}cmp-field-group-mappingType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="cmr-field-group-mapping" type="{http://tomee.apache.org/xml/ns/openejb-jar-2.2}cmr-field-group-mappingType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="select-for-update" type="{http://geronimo.apache.org/xml/ns/deployment-1.2}emptyType" minOccurs="0"/>
* </sequence>
* <element name="cache" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="isolation-level">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="read-uncommitted"/>
* <enumeration value="read-committed"/>
* <enumeration value="repeatable-read"/>
* </restriction>
* </simpleType>
* </element>
* <element name="size" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <group ref="{http://geronimo.apache.org/xml/ns/naming-1.2}jndiEnvironmentRefsGroup"/>
* <element name="query" type="{http://tomee.apache.org/xml/ns/openejb-jar-2.2}queryType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "entity-beanType", propOrder = {
"ejbName",
"jndiName",
"localJndiName",
"jndi",
"properties",
"tssLink",
"tss",
"tableName",
"staticSql",
"cmpFieldMapping",
"primkeyField",
"keyGenerator",
"prefetchGroup",
"selectForUpdate",
"cache",
"abstractNamingEntry",
"persistenceContextRef",
"persistenceUnitRef",
"ejbRef",
"ejbLocalRef",
"serviceRef",
"resourceRef",
"resourceEnvRef",
"query"
})
public class EntityBeanType implements EnterpriseBean, RpcBean {
@XmlElement(name = "ejb-name", required = true)
protected String ejbName;
@XmlElement(name = "jndi-name")
protected List<String> jndiName;
@XmlElement(name = "local-jndi-name")
protected List<String> localJndiName;
@XmlElement(name = "jndi")
protected List<Jndi> jndi;
@XmlElement(name = "tss-link")
protected String tssLink;
@XmlElement()
protected PatternType tss;
@XmlElement(name = "table-name")
protected String tableName;
@XmlElement(name = "static-sql")
protected EmptyType staticSql;
@XmlElement(name = "cmp-field-mapping")
protected List<EntityBeanType.CmpFieldMapping> cmpFieldMapping;
@XmlElement(name = "primkey-field")
protected String primkeyField;
@XmlElement(name = "key-generator", namespace = "http://tomee.apache.org/xml/ns/pkgen-2.1")
protected KeyGeneratorType keyGenerator;
@XmlElement(name = "prefetch-group")
protected EntityBeanType.PrefetchGroup prefetchGroup;
@XmlElement(name = "select-for-update")
protected EmptyType selectForUpdate;
@XmlElement()
protected EntityBeanType.Cache cache;
@XmlElementRef(name = "abstract-naming-entry", namespace = "http://geronimo.apache.org/xml/ns/naming-1.2", type = JAXBElement.class)
protected List<JAXBElement<? extends AbstractNamingEntryType>> abstractNamingEntry;
@XmlElement(name = "persistence-context-ref", namespace = "http://geronimo.apache.org/xml/ns/naming-1.2")
protected List<PersistenceContextRefType> persistenceContextRef;
@XmlElement(name = "persistence-unit-ref", namespace = "http://geronimo.apache.org/xml/ns/naming-1.2")
protected List<PersistenceUnitRefType> persistenceUnitRef;
@XmlElement(name = "ejb-ref", namespace = "http://geronimo.apache.org/xml/ns/naming-1.2")
protected List<EjbRefType> ejbRef;
@XmlElement(name = "ejb-local-ref", namespace = "http://geronimo.apache.org/xml/ns/naming-1.2")
protected List<EjbLocalRefType> ejbLocalRef;
@XmlElement(name = "service-ref", namespace = "http://geronimo.apache.org/xml/ns/naming-1.2")
protected List<ServiceRefType> serviceRef;
@XmlElement(name = "resource-ref", namespace = "http://geronimo.apache.org/xml/ns/naming-1.2")
protected List<ResourceRefType> resourceRef;
@XmlElement(name = "resource-env-ref", namespace = "http://geronimo.apache.org/xml/ns/naming-1.2")
protected List<ResourceEnvRefType> resourceEnvRef;
@XmlElement()
protected List<QueryType> query;
@XmlElement(name = "properties")
@XmlJavaTypeAdapter(PropertiesAdapter.class)
protected Properties properties;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
protected String id;
/**
* Gets the value of the ejbName property.
*
* @return possible object is
* {@link String }
*/
public String getEjbName() {
return ejbName;
}
/**
* Sets the value of the ejbName property.
*
* @param value allowed object is
* {@link String }
*/
public void setEjbName(final String value) {
this.ejbName = value;
}
/**
* Gets the value of the jndiName property.
*
*
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the jndiName property.
*
*
* For example, to add a new item, do as follows:
* <pre>
* getJndiName().add(newItem);
* </pre>
*
*
*
* Objects of the following type(s) are allowed in the list
* {@link String }
*/
public List<String> getJndiName() {
if (jndiName == null) {
jndiName = new ArrayList<String>();
}
return this.jndiName;
}
/**
* Gets the value of the localJndiName property.
*
*
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the localJndiName property.
*
*
* For example, to add a new item, do as follows:
* <pre>
* getLocalJndiName().add(newItem);
* </pre>
*
*
*
* Objects of the following type(s) are allowed in the list
* {@link String }
*/
public List<String> getLocalJndiName() {
if (localJndiName == null) {
localJndiName = new ArrayList<String>();
}
return this.localJndiName;
}
public List<Jndi> getJndi() {
if (jndi == null) {
jndi = new ArrayList<Jndi>();
}
return this.jndi;
}
/**
* Gets the value of the tssLink property.
*
* @return possible object is
* {@link String }
*/
public String getTssLink() {
return tssLink;
}
/**
* Sets the value of the tssLink property.
*
* @param value allowed object is
* {@link String }
*/
public void setTssLink(final String value) {
this.tssLink = value;
}
/**
* Gets the value of the tss property.
*
* @return possible object is
* {@link PatternType }
*/
public PatternType getTss() {
return tss;
}
/**
* Sets the value of the tss property.
*
* @param value allowed object is
* {@link PatternType }
*/
public void setTss(final PatternType value) {
this.tss = value;
}
/**
* Gets the value of the tableName property.
*
* @return possible object is
* {@link String }
*/
public String getTableName() {
return tableName;
}
/**
* Sets the value of the tableName property.
*
* @param value allowed object is
* {@link String }
*/
public void setTableName(final String value) {
this.tableName = value;
}
/**
* Gets the value of the staticSql property.
*
* @return possible object is
* {@link boolean }
*/
public boolean isStaticSql() {
return staticSql != null;
}
/**
* Sets the value of the staticSql property.
*
* @param value allowed object is
* {@link boolean }
*/
public void setStaticSql(final boolean value) {
this.staticSql = value ? new EmptyType() : null;
}
/**
* Gets the value of the cmpFieldMapping property.
*
*
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the cmpFieldMapping property.
*
*
* For example, to add a new item, do as follows:
* <pre>
* getCmpFieldMapping().add(newItem);
* </pre>
*
*
*
* Objects of the following type(s) are allowed in the list
* {@link EntityBeanType.CmpFieldMapping }
*/
public List<EntityBeanType.CmpFieldMapping> getCmpFieldMapping() {
if (cmpFieldMapping == null) {
cmpFieldMapping = new ArrayList<EntityBeanType.CmpFieldMapping>();
}
return this.cmpFieldMapping;
}
/**
* Gets the value of the primkeyField property.
*
* @return possible object is
* {@link String }
*/
public String getPrimkeyField() {
return primkeyField;
}
/**
* Sets the value of the primkeyField property.
*
* @param value allowed object is
* {@link String }
*/
public void setPrimkeyField(final String value) {
this.primkeyField = value;
}
/**
* Gets the value of the keyGenerator property.
*
* @return possible object is
* {@link KeyGeneratorType }
*/
public KeyGeneratorType getKeyGenerator() {
return keyGenerator;
}
/**
* Sets the value of the keyGenerator property.
*
* @param value allowed object is
* {@link KeyGeneratorType }
*/
public void setKeyGenerator(final KeyGeneratorType value) {
this.keyGenerator = value;
}
/**
* Gets the value of the prefetchGroup property.
*
* @return possible object is
* {@link EntityBeanType.PrefetchGroup }
*/
public EntityBeanType.PrefetchGroup getPrefetchGroup() {
return prefetchGroup;
}
/**
* Sets the value of the prefetchGroup property.
*
* @param value allowed object is
* {@link EntityBeanType.PrefetchGroup }
*/
public void setPrefetchGroup(final EntityBeanType.PrefetchGroup value) {
this.prefetchGroup = value;
}
/**
* Gets the value of the selectForUpdate property.
*
* @return possible object is
* {@link boolean }
*/
public boolean isSelectForUpdate() {
return selectForUpdate != null;
}
/**
* Sets the value of the selectForUpdate property.
*
* @param value allowed object is
* {@link boolean }
*/
public void setSelectForUpdate(final boolean value) {
this.selectForUpdate = value ? new EmptyType() : null;
}
/**
* Gets the value of the cache property.
*
* @return possible object is
* {@link EntityBeanType.Cache }
*/
public EntityBeanType.Cache getCache() {
return cache;
}
/**
* Sets the value of the cache property.
*
* @param value allowed object is
* {@link EntityBeanType.Cache }
*/
public void setCache(final EntityBeanType.Cache value) {
this.cache = value;
}
/**
* Gets the value of the abstractNamingEntry property.
*
*
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the abstractNamingEntry property.
*
*
* For example, to add a new item, do as follows:
* <pre>
* getAbstractNamingEntry().add(newItem);
* </pre>
*
*
*
* Objects of the following type(s) are allowed in the list
* {@link JAXBElement }{@code <}{@link AbstractNamingEntryType }{@code >}
* {@link JAXBElement }{@code <}{@link PersistenceContextRefType }{@code >}
* {@link JAXBElement }{@code <}{@link PersistenceUnitRefType }{@code >}
* {@link JAXBElement }{@code <}{@link GbeanRefType }{@code >}
*/
public List<JAXBElement<? extends AbstractNamingEntryType>> getAbstractNamingEntry() {
if (abstractNamingEntry == null) {
abstractNamingEntry = new ArrayList<JAXBElement<? extends AbstractNamingEntryType>>();
}
return this.abstractNamingEntry;
}
public List<PersistenceContextRefType> getPersistenceContextRef() {
if (persistenceContextRef == null) {
persistenceContextRef = new ArrayList<PersistenceContextRefType>();
}
return persistenceContextRef;
}
public List<PersistenceUnitRefType> getPersistenceUnitRef() {
if (persistenceUnitRef == null) {
persistenceUnitRef = new ArrayList<PersistenceUnitRefType>();
}
return persistenceUnitRef;
}
/**
* Gets the value of the ejbRef property.
*
*
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the ejbRef property.
*
*
* For example, to add a new item, do as follows:
* <pre>
* getEjbRef().add(newItem);
* </pre>
*
*
*
* Objects of the following type(s) are allowed in the list
* {@link EjbRefType }
*/
public List<EjbRefType> getEjbRef() {
if (ejbRef == null) {
ejbRef = new ArrayList<EjbRefType>();
}
return this.ejbRef;
}
/**
* Gets the value of the ejbLocalRef property.
*
*
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the ejbLocalRef property.
*
*
* For example, to add a new item, do as follows:
* <pre>
* getEjbLocalRef().add(newItem);
* </pre>
*
*
*
* Objects of the following type(s) are allowed in the list
* {@link EjbLocalRefType }
*/
public List<EjbLocalRefType> getEjbLocalRef() {
if (ejbLocalRef == null) {
ejbLocalRef = new ArrayList<EjbLocalRefType>();
}
return this.ejbLocalRef;
}
/**
* Gets the value of the serviceRef property.
*
*
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the serviceRef property.
*
*
* For example, to add a new item, do as follows:
* <pre>
* getServiceRef().add(newItem);
* </pre>
*
*
*
* Objects of the following type(s) are allowed in the list
* {@link ServiceRefType }
*/
public List<ServiceRefType> getServiceRef() {
if (serviceRef == null) {
serviceRef = new ArrayList<ServiceRefType>();
}
return this.serviceRef;
}
/**
* Gets the value of the resourceRef property.
*
*
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the resourceRef property.
*
*
* For example, to add a new item, do as follows:
* <pre>
* getResourceRef().add(newItem);
* </pre>
*
*
*
* Objects of the following type(s) are allowed in the list
* {@link ResourceRefType }
*/
public List<ResourceRefType> getResourceRef() {
if (resourceRef == null) {
resourceRef = new ArrayList<ResourceRefType>();
}
return this.resourceRef;
}
/**
* Gets the value of the resourceEnvRef property.
*
*
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the resourceEnvRef property.
*
*
* For example, to add a new item, do as follows:
* <pre>
* getResourceEnvRef().add(newItem);
* </pre>
*
*
*
* Objects of the following type(s) are allowed in the list
* {@link ResourceEnvRefType }
*/
public List<ResourceEnvRefType> getResourceEnvRef() {
if (resourceEnvRef == null) {
resourceEnvRef = new ArrayList<ResourceEnvRefType>();
}
return this.resourceEnvRef;
}
/**
* Gets the value of the query property.
*
*
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the query property.
*
*
* For example, to add a new item, do as follows:
* <pre>
* getQuery().add(newItem);
* </pre>
*
*
*
* Objects of the following type(s) are allowed in the list
* {@link QueryType }
*/
public List<QueryType> getQuery() {
if (query == null) {
query = new ArrayList<QueryType>();
}
return this.query;
}
/**
* Gets the value of the id property.
*
* @return possible object is
* {@link String }
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value allowed object is
* {@link String }
*/
public void setId(final String value) {
this.id = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="isolation-level">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="read-uncommitted"/>
* <enumeration value="read-committed"/>
* <enumeration value="repeatable-read"/>
* </restriction>
* </simpleType>
* </element>
* <element name="size" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"isolationLevel",
"size"
})
public static class Cache {
@XmlElement(name = "isolation-level", required = true)
protected String isolationLevel;
@XmlElement()
protected int size;
/**
* Gets the value of the isolationLevel property.
*
* @return possible object is
* {@link String }
*/
public String getIsolationLevel() {
return isolationLevel;
}
/**
* Sets the value of the isolationLevel property.
*
* @param value allowed object is
* {@link String }
*/
public void setIsolationLevel(final String value) {
this.isolationLevel = value;
}
/**
* Gets the value of the size property.
*/
public int getSize() {
return size;
}
/**
* Sets the value of the size property.
*/
public void setSize(final int value) {
this.size = value;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cmp-field-name" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="cmp-field-class" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="table-column" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="sql-type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="type-converter" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"cmpFieldName",
"cmpFieldClass",
"tableColumn",
"sqlType",
"typeConverter"
})
public static class CmpFieldMapping {
@XmlElement(name = "cmp-field-name", required = true)
protected String cmpFieldName;
@XmlElement(name = "cmp-field-class")
protected String cmpFieldClass;
@XmlElement(name = "table-column", required = true)
protected String tableColumn;
@XmlElement(name = "sql-type")
protected String sqlType;
@XmlElement(name = "type-converter")
protected String typeConverter;
/**
* Gets the value of the cmpFieldName property.
*
* @return possible object is
* {@link String }
*/
public String getCmpFieldName() {
return cmpFieldName;
}
/**
* Sets the value of the cmpFieldName property.
*
* @param value allowed object is
* {@link String }
*/
public void setCmpFieldName(final String value) {
this.cmpFieldName = value;
}
/**
* Gets the value of the cmpFieldClass property.
*
* @return possible object is
* {@link String }
*/
public String getCmpFieldClass() {
return cmpFieldClass;
}
/**
* Sets the value of the cmpFieldClass property.
*
* @param value allowed object is
* {@link String }
*/
public void setCmpFieldClass(final String value) {
this.cmpFieldClass = value;
}
/**
* Gets the value of the tableColumn property.
*
* @return possible object is
* {@link String }
*/
public String getTableColumn() {
return tableColumn;
}
/**
* Sets the value of the tableColumn property.
*
* @param value allowed object is
* {@link String }
*/
public void setTableColumn(final String value) {
this.tableColumn = value;
}
/**
* Gets the value of the sqlType property.
*
* @return possible object is
* {@link String }
*/
public String getSqlType() {
return sqlType;
}
/**
* Sets the value of the sqlType property.
*
* @param value allowed object is
* {@link String }
*/
public void setSqlType(final String value) {
this.sqlType = value;
}
/**
* Gets the value of the typeConverter property.
*
* @return possible object is
* {@link String }
*/
public String getTypeConverter() {
return typeConverter;
}
/**
* Sets the value of the typeConverter property.
*
* @param value allowed object is
* {@link String }
*/
public void setTypeConverter(final String value) {
this.typeConverter = value;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="group" type="{http://tomee.apache.org/xml/ns/openejb-jar-2.2}groupType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="entity-group-mapping" type="{http://tomee.apache.org/xml/ns/openejb-jar-2.2}entity-group-mappingType" minOccurs="0"/>
* <element name="cmp-field-group-mapping" type="{http://tomee.apache.org/xml/ns/openejb-jar-2.2}cmp-field-group-mappingType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="cmr-field-group-mapping" type="{http://tomee.apache.org/xml/ns/openejb-jar-2.2}cmr-field-group-mappingType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"group",
"entityGroupMapping",
"cmpFieldGroupMapping",
"cmrFieldGroupMapping"
})
public static class PrefetchGroup {
@XmlElement()
protected List<GroupType> group;
@XmlElement(name = "entity-group-mapping")
protected EntityGroupMappingType entityGroupMapping;
@XmlElement(name = "cmp-field-group-mapping")
protected List<CmpFieldGroupMappingType> cmpFieldGroupMapping;
@XmlElement(name = "cmr-field-group-mapping")
protected List<CmrFieldGroupMappingType> cmrFieldGroupMapping;
/**
* Gets the value of the group property.
*
*
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the group property.
*
*
* For example, to add a new item, do as follows:
* <pre>
* getGroup().add(newItem);
* </pre>
*
*
*
* Objects of the following type(s) are allowed in the list
* {@link GroupType }
*/
public List<GroupType> getGroup() {
if (group == null) {
group = new ArrayList<GroupType>();
}
return this.group;
}
/**
* Gets the value of the entityGroupMapping property.
*
* @return possible object is
* {@link EntityGroupMappingType }
*/
public EntityGroupMappingType getEntityGroupMapping() {
return entityGroupMapping;
}
/**
* Sets the value of the entityGroupMapping property.
*
* @param value allowed object is
* {@link EntityGroupMappingType }
*/
public void setEntityGroupMapping(final EntityGroupMappingType value) {
this.entityGroupMapping = value;
}
/**
* Gets the value of the cmpFieldGroupMapping property.
*
*
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the cmpFieldGroupMapping property.
*
*
* For example, to add a new item, do as follows:
* <pre>
* getCmpFieldGroupMapping().add(newItem);
* </pre>
*
*
*
* Objects of the following type(s) are allowed in the list
* {@link CmpFieldGroupMappingType }
*/
public List<CmpFieldGroupMappingType> getCmpFieldGroupMapping() {
if (cmpFieldGroupMapping == null) {
cmpFieldGroupMapping = new ArrayList<CmpFieldGroupMappingType>();
}
return this.cmpFieldGroupMapping;
}
/**
* Gets the value of the cmrFieldGroupMapping property.
*
*
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the cmrFieldGroupMapping property.
*
*
* For example, to add a new item, do as follows:
* <pre>
* getCmrFieldGroupMapping().add(newItem);
* </pre>
*
*
*
* Objects of the following type(s) are allowed in the list
* {@link CmrFieldGroupMappingType }
*/
public List<CmrFieldGroupMappingType> getCmrFieldGroupMapping() {
if (cmrFieldGroupMapping == null) {
cmrFieldGroupMapping = new ArrayList<CmrFieldGroupMappingType>();
}
return this.cmrFieldGroupMapping;
}
}
public Properties getProperties() {
if (properties == null) {
properties = new Properties();
}
return properties;
}
}
|
googleapis/google-cloud-java | 36,352 | java-oracledatabase/proto-google-cloud-oracledatabase-v1/src/main/java/com/google/cloud/oracledatabase/v1/ScheduledOperationDetails.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/oracledatabase/v1/autonomous_database.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.oracledatabase.v1;
/**
*
*
* <pre>
* Details of scheduled operation.
* https://docs.oracle.com/en-us/iaas/api/#/en/database/20160918/datatypes/ScheduledOperationDetails
* </pre>
*
* Protobuf type {@code google.cloud.oracledatabase.v1.ScheduledOperationDetails}
*/
public final class ScheduledOperationDetails extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.oracledatabase.v1.ScheduledOperationDetails)
ScheduledOperationDetailsOrBuilder {
private static final long serialVersionUID = 0L;
// Use ScheduledOperationDetails.newBuilder() to construct.
private ScheduledOperationDetails(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ScheduledOperationDetails() {
dayOfWeek_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ScheduledOperationDetails();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.oracledatabase.v1.AutonomousDatabaseProto
.internal_static_google_cloud_oracledatabase_v1_ScheduledOperationDetails_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.oracledatabase.v1.AutonomousDatabaseProto
.internal_static_google_cloud_oracledatabase_v1_ScheduledOperationDetails_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.oracledatabase.v1.ScheduledOperationDetails.class,
com.google.cloud.oracledatabase.v1.ScheduledOperationDetails.Builder.class);
}
private int bitField0_;
public static final int DAY_OF_WEEK_FIELD_NUMBER = 1;
private int dayOfWeek_ = 0;
/**
*
*
* <pre>
* Output only. Day of week.
* </pre>
*
* <code>.google.type.DayOfWeek day_of_week = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return The enum numeric value on the wire for dayOfWeek.
*/
@java.lang.Override
public int getDayOfWeekValue() {
return dayOfWeek_;
}
/**
*
*
* <pre>
* Output only. Day of week.
* </pre>
*
* <code>.google.type.DayOfWeek day_of_week = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return The dayOfWeek.
*/
@java.lang.Override
public com.google.type.DayOfWeek getDayOfWeek() {
com.google.type.DayOfWeek result = com.google.type.DayOfWeek.forNumber(dayOfWeek_);
return result == null ? com.google.type.DayOfWeek.UNRECOGNIZED : result;
}
public static final int START_TIME_FIELD_NUMBER = 4;
private com.google.type.TimeOfDay startTime_;
/**
*
*
* <pre>
* Output only. Auto start time.
* </pre>
*
* <code>.google.type.TimeOfDay start_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return Whether the startTime field is set.
*/
@java.lang.Override
public boolean hasStartTime() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Output only. Auto start time.
* </pre>
*
* <code>.google.type.TimeOfDay start_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return The startTime.
*/
@java.lang.Override
public com.google.type.TimeOfDay getStartTime() {
return startTime_ == null ? com.google.type.TimeOfDay.getDefaultInstance() : startTime_;
}
/**
*
*
* <pre>
* Output only. Auto start time.
* </pre>
*
* <code>.google.type.TimeOfDay start_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
@java.lang.Override
public com.google.type.TimeOfDayOrBuilder getStartTimeOrBuilder() {
return startTime_ == null ? com.google.type.TimeOfDay.getDefaultInstance() : startTime_;
}
public static final int STOP_TIME_FIELD_NUMBER = 5;
private com.google.type.TimeOfDay stopTime_;
/**
*
*
* <pre>
* Output only. Auto stop time.
* </pre>
*
* <code>.google.type.TimeOfDay stop_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return Whether the stopTime field is set.
*/
@java.lang.Override
public boolean hasStopTime() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Output only. Auto stop time.
* </pre>
*
* <code>.google.type.TimeOfDay stop_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The stopTime.
*/
@java.lang.Override
public com.google.type.TimeOfDay getStopTime() {
return stopTime_ == null ? com.google.type.TimeOfDay.getDefaultInstance() : stopTime_;
}
/**
*
*
* <pre>
* Output only. Auto stop time.
* </pre>
*
* <code>.google.type.TimeOfDay stop_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*/
@java.lang.Override
public com.google.type.TimeOfDayOrBuilder getStopTimeOrBuilder() {
return stopTime_ == null ? com.google.type.TimeOfDay.getDefaultInstance() : stopTime_;
}
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 (dayOfWeek_ != com.google.type.DayOfWeek.DAY_OF_WEEK_UNSPECIFIED.getNumber()) {
output.writeEnum(1, dayOfWeek_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(4, getStartTime());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(5, getStopTime());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (dayOfWeek_ != com.google.type.DayOfWeek.DAY_OF_WEEK_UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, dayOfWeek_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, getStartTime());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(5, getStopTime());
}
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.ScheduledOperationDetails)) {
return super.equals(obj);
}
com.google.cloud.oracledatabase.v1.ScheduledOperationDetails other =
(com.google.cloud.oracledatabase.v1.ScheduledOperationDetails) obj;
if (dayOfWeek_ != other.dayOfWeek_) return false;
if (hasStartTime() != other.hasStartTime()) return false;
if (hasStartTime()) {
if (!getStartTime().equals(other.getStartTime())) return false;
}
if (hasStopTime() != other.hasStopTime()) return false;
if (hasStopTime()) {
if (!getStopTime().equals(other.getStopTime())) 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) + DAY_OF_WEEK_FIELD_NUMBER;
hash = (53 * hash) + dayOfWeek_;
if (hasStartTime()) {
hash = (37 * hash) + START_TIME_FIELD_NUMBER;
hash = (53 * hash) + getStartTime().hashCode();
}
if (hasStopTime()) {
hash = (37 * hash) + STOP_TIME_FIELD_NUMBER;
hash = (53 * hash) + getStopTime().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.oracledatabase.v1.ScheduledOperationDetails parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.oracledatabase.v1.ScheduledOperationDetails 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.ScheduledOperationDetails parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.oracledatabase.v1.ScheduledOperationDetails 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.ScheduledOperationDetails parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.oracledatabase.v1.ScheduledOperationDetails 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.ScheduledOperationDetails parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.oracledatabase.v1.ScheduledOperationDetails 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.ScheduledOperationDetails parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.oracledatabase.v1.ScheduledOperationDetails 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.ScheduledOperationDetails 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.ScheduledOperationDetails 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.ScheduledOperationDetails prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Details of scheduled operation.
* https://docs.oracle.com/en-us/iaas/api/#/en/database/20160918/datatypes/ScheduledOperationDetails
* </pre>
*
* Protobuf type {@code google.cloud.oracledatabase.v1.ScheduledOperationDetails}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.oracledatabase.v1.ScheduledOperationDetails)
com.google.cloud.oracledatabase.v1.ScheduledOperationDetailsOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.oracledatabase.v1.AutonomousDatabaseProto
.internal_static_google_cloud_oracledatabase_v1_ScheduledOperationDetails_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.oracledatabase.v1.AutonomousDatabaseProto
.internal_static_google_cloud_oracledatabase_v1_ScheduledOperationDetails_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.oracledatabase.v1.ScheduledOperationDetails.class,
com.google.cloud.oracledatabase.v1.ScheduledOperationDetails.Builder.class);
}
// Construct using com.google.cloud.oracledatabase.v1.ScheduledOperationDetails.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();
getStopTimeFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
dayOfWeek_ = 0;
startTime_ = null;
if (startTimeBuilder_ != null) {
startTimeBuilder_.dispose();
startTimeBuilder_ = null;
}
stopTime_ = null;
if (stopTimeBuilder_ != null) {
stopTimeBuilder_.dispose();
stopTimeBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.oracledatabase.v1.AutonomousDatabaseProto
.internal_static_google_cloud_oracledatabase_v1_ScheduledOperationDetails_descriptor;
}
@java.lang.Override
public com.google.cloud.oracledatabase.v1.ScheduledOperationDetails
getDefaultInstanceForType() {
return com.google.cloud.oracledatabase.v1.ScheduledOperationDetails.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.oracledatabase.v1.ScheduledOperationDetails build() {
com.google.cloud.oracledatabase.v1.ScheduledOperationDetails result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.oracledatabase.v1.ScheduledOperationDetails buildPartial() {
com.google.cloud.oracledatabase.v1.ScheduledOperationDetails result =
new com.google.cloud.oracledatabase.v1.ScheduledOperationDetails(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.oracledatabase.v1.ScheduledOperationDetails result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.dayOfWeek_ = dayOfWeek_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.startTime_ = startTimeBuilder_ == null ? startTime_ : startTimeBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.stopTime_ = stopTimeBuilder_ == null ? stopTime_ : stopTimeBuilder_.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.oracledatabase.v1.ScheduledOperationDetails) {
return mergeFrom((com.google.cloud.oracledatabase.v1.ScheduledOperationDetails) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.oracledatabase.v1.ScheduledOperationDetails other) {
if (other
== com.google.cloud.oracledatabase.v1.ScheduledOperationDetails.getDefaultInstance())
return this;
if (other.dayOfWeek_ != 0) {
setDayOfWeekValue(other.getDayOfWeekValue());
}
if (other.hasStartTime()) {
mergeStartTime(other.getStartTime());
}
if (other.hasStopTime()) {
mergeStopTime(other.getStopTime());
}
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:
{
dayOfWeek_ = input.readEnum();
bitField0_ |= 0x00000001;
break;
} // case 8
case 34:
{
input.readMessage(getStartTimeFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 34
case 42:
{
input.readMessage(getStopTimeFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000004;
break;
} // case 42
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private int dayOfWeek_ = 0;
/**
*
*
* <pre>
* Output only. Day of week.
* </pre>
*
* <code>.google.type.DayOfWeek day_of_week = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return The enum numeric value on the wire for dayOfWeek.
*/
@java.lang.Override
public int getDayOfWeekValue() {
return dayOfWeek_;
}
/**
*
*
* <pre>
* Output only. Day of week.
* </pre>
*
* <code>.google.type.DayOfWeek day_of_week = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @param value The enum numeric value on the wire for dayOfWeek to set.
* @return This builder for chaining.
*/
public Builder setDayOfWeekValue(int value) {
dayOfWeek_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Day of week.
* </pre>
*
* <code>.google.type.DayOfWeek day_of_week = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return The dayOfWeek.
*/
@java.lang.Override
public com.google.type.DayOfWeek getDayOfWeek() {
com.google.type.DayOfWeek result = com.google.type.DayOfWeek.forNumber(dayOfWeek_);
return result == null ? com.google.type.DayOfWeek.UNRECOGNIZED : result;
}
/**
*
*
* <pre>
* Output only. Day of week.
* </pre>
*
* <code>.google.type.DayOfWeek day_of_week = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @param value The dayOfWeek to set.
* @return This builder for chaining.
*/
public Builder setDayOfWeek(com.google.type.DayOfWeek value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
dayOfWeek_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Day of week.
* </pre>
*
* <code>.google.type.DayOfWeek day_of_week = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return This builder for chaining.
*/
public Builder clearDayOfWeek() {
bitField0_ = (bitField0_ & ~0x00000001);
dayOfWeek_ = 0;
onChanged();
return this;
}
private com.google.type.TimeOfDay startTime_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.type.TimeOfDay,
com.google.type.TimeOfDay.Builder,
com.google.type.TimeOfDayOrBuilder>
startTimeBuilder_;
/**
*
*
* <pre>
* Output only. Auto start time.
* </pre>
*
* <code>.google.type.TimeOfDay start_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return Whether the startTime field is set.
*/
public boolean hasStartTime() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Output only. Auto start time.
* </pre>
*
* <code>.google.type.TimeOfDay start_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return The startTime.
*/
public com.google.type.TimeOfDay getStartTime() {
if (startTimeBuilder_ == null) {
return startTime_ == null ? com.google.type.TimeOfDay.getDefaultInstance() : startTime_;
} else {
return startTimeBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Output only. Auto start time.
* </pre>
*
* <code>.google.type.TimeOfDay start_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder setStartTime(com.google.type.TimeOfDay value) {
if (startTimeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
startTime_ = value;
} else {
startTimeBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Auto start time.
* </pre>
*
* <code>.google.type.TimeOfDay start_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder setStartTime(com.google.type.TimeOfDay.Builder builderForValue) {
if (startTimeBuilder_ == null) {
startTime_ = builderForValue.build();
} else {
startTimeBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Auto start time.
* </pre>
*
* <code>.google.type.TimeOfDay start_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder mergeStartTime(com.google.type.TimeOfDay value) {
if (startTimeBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& startTime_ != null
&& startTime_ != com.google.type.TimeOfDay.getDefaultInstance()) {
getStartTimeBuilder().mergeFrom(value);
} else {
startTime_ = value;
}
} else {
startTimeBuilder_.mergeFrom(value);
}
if (startTime_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Output only. Auto start time.
* </pre>
*
* <code>.google.type.TimeOfDay start_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder clearStartTime() {
bitField0_ = (bitField0_ & ~0x00000002);
startTime_ = null;
if (startTimeBuilder_ != null) {
startTimeBuilder_.dispose();
startTimeBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Auto start time.
* </pre>
*
* <code>.google.type.TimeOfDay start_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public com.google.type.TimeOfDay.Builder getStartTimeBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getStartTimeFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Output only. Auto start time.
* </pre>
*
* <code>.google.type.TimeOfDay start_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public com.google.type.TimeOfDayOrBuilder getStartTimeOrBuilder() {
if (startTimeBuilder_ != null) {
return startTimeBuilder_.getMessageOrBuilder();
} else {
return startTime_ == null ? com.google.type.TimeOfDay.getDefaultInstance() : startTime_;
}
}
/**
*
*
* <pre>
* Output only. Auto start time.
* </pre>
*
* <code>.google.type.TimeOfDay start_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.type.TimeOfDay,
com.google.type.TimeOfDay.Builder,
com.google.type.TimeOfDayOrBuilder>
getStartTimeFieldBuilder() {
if (startTimeBuilder_ == null) {
startTimeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.type.TimeOfDay,
com.google.type.TimeOfDay.Builder,
com.google.type.TimeOfDayOrBuilder>(
getStartTime(), getParentForChildren(), isClean());
startTime_ = null;
}
return startTimeBuilder_;
}
private com.google.type.TimeOfDay stopTime_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.type.TimeOfDay,
com.google.type.TimeOfDay.Builder,
com.google.type.TimeOfDayOrBuilder>
stopTimeBuilder_;
/**
*
*
* <pre>
* Output only. Auto stop time.
* </pre>
*
* <code>.google.type.TimeOfDay stop_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return Whether the stopTime field is set.
*/
public boolean hasStopTime() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* Output only. Auto stop time.
* </pre>
*
* <code>.google.type.TimeOfDay stop_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return The stopTime.
*/
public com.google.type.TimeOfDay getStopTime() {
if (stopTimeBuilder_ == null) {
return stopTime_ == null ? com.google.type.TimeOfDay.getDefaultInstance() : stopTime_;
} else {
return stopTimeBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Output only. Auto stop time.
* </pre>
*
* <code>.google.type.TimeOfDay stop_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder setStopTime(com.google.type.TimeOfDay value) {
if (stopTimeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
stopTime_ = value;
} else {
stopTimeBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Auto stop time.
* </pre>
*
* <code>.google.type.TimeOfDay stop_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder setStopTime(com.google.type.TimeOfDay.Builder builderForValue) {
if (stopTimeBuilder_ == null) {
stopTime_ = builderForValue.build();
} else {
stopTimeBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Auto stop time.
* </pre>
*
* <code>.google.type.TimeOfDay stop_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder mergeStopTime(com.google.type.TimeOfDay value) {
if (stopTimeBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& stopTime_ != null
&& stopTime_ != com.google.type.TimeOfDay.getDefaultInstance()) {
getStopTimeBuilder().mergeFrom(value);
} else {
stopTime_ = value;
}
} else {
stopTimeBuilder_.mergeFrom(value);
}
if (stopTime_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Output only. Auto stop time.
* </pre>
*
* <code>.google.type.TimeOfDay stop_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder clearStopTime() {
bitField0_ = (bitField0_ & ~0x00000004);
stopTime_ = null;
if (stopTimeBuilder_ != null) {
stopTimeBuilder_.dispose();
stopTimeBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Auto stop time.
* </pre>
*
* <code>.google.type.TimeOfDay stop_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public com.google.type.TimeOfDay.Builder getStopTimeBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getStopTimeFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Output only. Auto stop time.
* </pre>
*
* <code>.google.type.TimeOfDay stop_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public com.google.type.TimeOfDayOrBuilder getStopTimeOrBuilder() {
if (stopTimeBuilder_ != null) {
return stopTimeBuilder_.getMessageOrBuilder();
} else {
return stopTime_ == null ? com.google.type.TimeOfDay.getDefaultInstance() : stopTime_;
}
}
/**
*
*
* <pre>
* Output only. Auto stop time.
* </pre>
*
* <code>.google.type.TimeOfDay stop_time = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.type.TimeOfDay,
com.google.type.TimeOfDay.Builder,
com.google.type.TimeOfDayOrBuilder>
getStopTimeFieldBuilder() {
if (stopTimeBuilder_ == null) {
stopTimeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.type.TimeOfDay,
com.google.type.TimeOfDay.Builder,
com.google.type.TimeOfDayOrBuilder>(
getStopTime(), getParentForChildren(), isClean());
stopTime_ = null;
}
return stopTimeBuilder_;
}
@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.ScheduledOperationDetails)
}
// @@protoc_insertion_point(class_scope:google.cloud.oracledatabase.v1.ScheduledOperationDetails)
private static final com.google.cloud.oracledatabase.v1.ScheduledOperationDetails
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.oracledatabase.v1.ScheduledOperationDetails();
}
public static com.google.cloud.oracledatabase.v1.ScheduledOperationDetails getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ScheduledOperationDetails> PARSER =
new com.google.protobuf.AbstractParser<ScheduledOperationDetails>() {
@java.lang.Override
public ScheduledOperationDetails 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<ScheduledOperationDetails> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ScheduledOperationDetails> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.oracledatabase.v1.ScheduledOperationDetails getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,383 | java-appengine-admin/proto-google-cloud-appengine-admin-v1/src/main/java/com/google/appengine/v1/ListDomainMappingsResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/appengine/v1/appengine.proto
// Protobuf Java Version: 3.25.8
package com.google.appengine.v1;
/**
*
*
* <pre>
* Response message for `DomainMappings.ListDomainMappings`.
* </pre>
*
* Protobuf type {@code google.appengine.v1.ListDomainMappingsResponse}
*/
public final class ListDomainMappingsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.appengine.v1.ListDomainMappingsResponse)
ListDomainMappingsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListDomainMappingsResponse.newBuilder() to construct.
private ListDomainMappingsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListDomainMappingsResponse() {
domainMappings_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListDomainMappingsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.appengine.v1.AppengineProto
.internal_static_google_appengine_v1_ListDomainMappingsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.appengine.v1.AppengineProto
.internal_static_google_appengine_v1_ListDomainMappingsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.appengine.v1.ListDomainMappingsResponse.class,
com.google.appengine.v1.ListDomainMappingsResponse.Builder.class);
}
public static final int DOMAIN_MAPPINGS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.appengine.v1.DomainMapping> domainMappings_;
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.appengine.v1.DomainMapping> getDomainMappingsList() {
return domainMappings_;
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.appengine.v1.DomainMappingOrBuilder>
getDomainMappingsOrBuilderList() {
return domainMappings_;
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
@java.lang.Override
public int getDomainMappingsCount() {
return domainMappings_.size();
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
@java.lang.Override
public com.google.appengine.v1.DomainMapping getDomainMappings(int index) {
return domainMappings_.get(index);
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
@java.lang.Override
public com.google.appengine.v1.DomainMappingOrBuilder getDomainMappingsOrBuilder(int index) {
return domainMappings_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Continuation token for fetching the next page of results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Continuation token for fetching the next page of results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < domainMappings_.size(); i++) {
output.writeMessage(1, domainMappings_.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 < domainMappings_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, domainMappings_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.appengine.v1.ListDomainMappingsResponse)) {
return super.equals(obj);
}
com.google.appengine.v1.ListDomainMappingsResponse other =
(com.google.appengine.v1.ListDomainMappingsResponse) obj;
if (!getDomainMappingsList().equals(other.getDomainMappingsList())) 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 (getDomainMappingsCount() > 0) {
hash = (37 * hash) + DOMAIN_MAPPINGS_FIELD_NUMBER;
hash = (53 * hash) + getDomainMappingsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.appengine.v1.ListDomainMappingsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.appengine.v1.ListDomainMappingsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.appengine.v1.ListDomainMappingsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.appengine.v1.ListDomainMappingsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.appengine.v1.ListDomainMappingsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.appengine.v1.ListDomainMappingsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.appengine.v1.ListDomainMappingsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.appengine.v1.ListDomainMappingsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.appengine.v1.ListDomainMappingsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.appengine.v1.ListDomainMappingsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.appengine.v1.ListDomainMappingsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.appengine.v1.ListDomainMappingsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.appengine.v1.ListDomainMappingsResponse 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 `DomainMappings.ListDomainMappings`.
* </pre>
*
* Protobuf type {@code google.appengine.v1.ListDomainMappingsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.appengine.v1.ListDomainMappingsResponse)
com.google.appengine.v1.ListDomainMappingsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.appengine.v1.AppengineProto
.internal_static_google_appengine_v1_ListDomainMappingsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.appengine.v1.AppengineProto
.internal_static_google_appengine_v1_ListDomainMappingsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.appengine.v1.ListDomainMappingsResponse.class,
com.google.appengine.v1.ListDomainMappingsResponse.Builder.class);
}
// Construct using com.google.appengine.v1.ListDomainMappingsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (domainMappingsBuilder_ == null) {
domainMappings_ = java.util.Collections.emptyList();
} else {
domainMappings_ = null;
domainMappingsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.appengine.v1.AppengineProto
.internal_static_google_appengine_v1_ListDomainMappingsResponse_descriptor;
}
@java.lang.Override
public com.google.appengine.v1.ListDomainMappingsResponse getDefaultInstanceForType() {
return com.google.appengine.v1.ListDomainMappingsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.appengine.v1.ListDomainMappingsResponse build() {
com.google.appengine.v1.ListDomainMappingsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.appengine.v1.ListDomainMappingsResponse buildPartial() {
com.google.appengine.v1.ListDomainMappingsResponse result =
new com.google.appengine.v1.ListDomainMappingsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.appengine.v1.ListDomainMappingsResponse result) {
if (domainMappingsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
domainMappings_ = java.util.Collections.unmodifiableList(domainMappings_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.domainMappings_ = domainMappings_;
} else {
result.domainMappings_ = domainMappingsBuilder_.build();
}
}
private void buildPartial0(com.google.appengine.v1.ListDomainMappingsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.appengine.v1.ListDomainMappingsResponse) {
return mergeFrom((com.google.appengine.v1.ListDomainMappingsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.appengine.v1.ListDomainMappingsResponse other) {
if (other == com.google.appengine.v1.ListDomainMappingsResponse.getDefaultInstance())
return this;
if (domainMappingsBuilder_ == null) {
if (!other.domainMappings_.isEmpty()) {
if (domainMappings_.isEmpty()) {
domainMappings_ = other.domainMappings_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureDomainMappingsIsMutable();
domainMappings_.addAll(other.domainMappings_);
}
onChanged();
}
} else {
if (!other.domainMappings_.isEmpty()) {
if (domainMappingsBuilder_.isEmpty()) {
domainMappingsBuilder_.dispose();
domainMappingsBuilder_ = null;
domainMappings_ = other.domainMappings_;
bitField0_ = (bitField0_ & ~0x00000001);
domainMappingsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getDomainMappingsFieldBuilder()
: null;
} else {
domainMappingsBuilder_.addAllMessages(other.domainMappings_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.appengine.v1.DomainMapping m =
input.readMessage(
com.google.appengine.v1.DomainMapping.parser(), extensionRegistry);
if (domainMappingsBuilder_ == null) {
ensureDomainMappingsIsMutable();
domainMappings_.add(m);
} else {
domainMappingsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.appengine.v1.DomainMapping> domainMappings_ =
java.util.Collections.emptyList();
private void ensureDomainMappingsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
domainMappings_ =
new java.util.ArrayList<com.google.appengine.v1.DomainMapping>(domainMappings_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.appengine.v1.DomainMapping,
com.google.appengine.v1.DomainMapping.Builder,
com.google.appengine.v1.DomainMappingOrBuilder>
domainMappingsBuilder_;
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public java.util.List<com.google.appengine.v1.DomainMapping> getDomainMappingsList() {
if (domainMappingsBuilder_ == null) {
return java.util.Collections.unmodifiableList(domainMappings_);
} else {
return domainMappingsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public int getDomainMappingsCount() {
if (domainMappingsBuilder_ == null) {
return domainMappings_.size();
} else {
return domainMappingsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public com.google.appengine.v1.DomainMapping getDomainMappings(int index) {
if (domainMappingsBuilder_ == null) {
return domainMappings_.get(index);
} else {
return domainMappingsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public Builder setDomainMappings(int index, com.google.appengine.v1.DomainMapping value) {
if (domainMappingsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDomainMappingsIsMutable();
domainMappings_.set(index, value);
onChanged();
} else {
domainMappingsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public Builder setDomainMappings(
int index, com.google.appengine.v1.DomainMapping.Builder builderForValue) {
if (domainMappingsBuilder_ == null) {
ensureDomainMappingsIsMutable();
domainMappings_.set(index, builderForValue.build());
onChanged();
} else {
domainMappingsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public Builder addDomainMappings(com.google.appengine.v1.DomainMapping value) {
if (domainMappingsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDomainMappingsIsMutable();
domainMappings_.add(value);
onChanged();
} else {
domainMappingsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public Builder addDomainMappings(int index, com.google.appengine.v1.DomainMapping value) {
if (domainMappingsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDomainMappingsIsMutable();
domainMappings_.add(index, value);
onChanged();
} else {
domainMappingsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public Builder addDomainMappings(
com.google.appengine.v1.DomainMapping.Builder builderForValue) {
if (domainMappingsBuilder_ == null) {
ensureDomainMappingsIsMutable();
domainMappings_.add(builderForValue.build());
onChanged();
} else {
domainMappingsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public Builder addDomainMappings(
int index, com.google.appengine.v1.DomainMapping.Builder builderForValue) {
if (domainMappingsBuilder_ == null) {
ensureDomainMappingsIsMutable();
domainMappings_.add(index, builderForValue.build());
onChanged();
} else {
domainMappingsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public Builder addAllDomainMappings(
java.lang.Iterable<? extends com.google.appengine.v1.DomainMapping> values) {
if (domainMappingsBuilder_ == null) {
ensureDomainMappingsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, domainMappings_);
onChanged();
} else {
domainMappingsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public Builder clearDomainMappings() {
if (domainMappingsBuilder_ == null) {
domainMappings_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
domainMappingsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public Builder removeDomainMappings(int index) {
if (domainMappingsBuilder_ == null) {
ensureDomainMappingsIsMutable();
domainMappings_.remove(index);
onChanged();
} else {
domainMappingsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public com.google.appengine.v1.DomainMapping.Builder getDomainMappingsBuilder(int index) {
return getDomainMappingsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public com.google.appengine.v1.DomainMappingOrBuilder getDomainMappingsOrBuilder(int index) {
if (domainMappingsBuilder_ == null) {
return domainMappings_.get(index);
} else {
return domainMappingsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public java.util.List<? extends com.google.appengine.v1.DomainMappingOrBuilder>
getDomainMappingsOrBuilderList() {
if (domainMappingsBuilder_ != null) {
return domainMappingsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(domainMappings_);
}
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public com.google.appengine.v1.DomainMapping.Builder addDomainMappingsBuilder() {
return getDomainMappingsFieldBuilder()
.addBuilder(com.google.appengine.v1.DomainMapping.getDefaultInstance());
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public com.google.appengine.v1.DomainMapping.Builder addDomainMappingsBuilder(int index) {
return getDomainMappingsFieldBuilder()
.addBuilder(index, com.google.appengine.v1.DomainMapping.getDefaultInstance());
}
/**
*
*
* <pre>
* The domain mappings for the application.
* </pre>
*
* <code>repeated .google.appengine.v1.DomainMapping domain_mappings = 1;</code>
*/
public java.util.List<com.google.appengine.v1.DomainMapping.Builder>
getDomainMappingsBuilderList() {
return getDomainMappingsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.appengine.v1.DomainMapping,
com.google.appengine.v1.DomainMapping.Builder,
com.google.appengine.v1.DomainMappingOrBuilder>
getDomainMappingsFieldBuilder() {
if (domainMappingsBuilder_ == null) {
domainMappingsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.appengine.v1.DomainMapping,
com.google.appengine.v1.DomainMapping.Builder,
com.google.appengine.v1.DomainMappingOrBuilder>(
domainMappings_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
domainMappings_ = null;
}
return domainMappingsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Continuation token for fetching the next page of results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Continuation token for fetching the next page of results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Continuation token for fetching the next page of results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Continuation token for fetching the next page of results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Continuation token for fetching the next page of results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.appengine.v1.ListDomainMappingsResponse)
}
// @@protoc_insertion_point(class_scope:google.appengine.v1.ListDomainMappingsResponse)
private static final com.google.appengine.v1.ListDomainMappingsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.appengine.v1.ListDomainMappingsResponse();
}
public static com.google.appengine.v1.ListDomainMappingsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListDomainMappingsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListDomainMappingsResponse>() {
@java.lang.Override
public ListDomainMappingsResponse 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<ListDomainMappingsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListDomainMappingsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.appengine.v1.ListDomainMappingsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,400 | java-analytics-admin/proto-google-analytics-admin-v1alpha/src/main/java/com/google/analytics/admin/v1alpha/UpdateAudienceRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/analytics/admin/v1alpha/analytics_admin.proto
// Protobuf Java Version: 3.25.8
package com.google.analytics.admin.v1alpha;
/**
*
*
* <pre>
* Request message for UpdateAudience RPC.
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1alpha.UpdateAudienceRequest}
*/
public final class UpdateAudienceRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.analytics.admin.v1alpha.UpdateAudienceRequest)
UpdateAudienceRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateAudienceRequest.newBuilder() to construct.
private UpdateAudienceRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateAudienceRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateAudienceRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdateAudienceRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdateAudienceRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1alpha.UpdateAudienceRequest.class,
com.google.analytics.admin.v1alpha.UpdateAudienceRequest.Builder.class);
}
private int bitField0_;
public static final int AUDIENCE_FIELD_NUMBER = 1;
private com.google.analytics.admin.v1alpha.Audience audience_;
/**
*
*
* <pre>
* Required. The audience to update.
* The audience's `name` field is used to identify the audience to be updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Audience audience = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the audience field is set.
*/
@java.lang.Override
public boolean hasAudience() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The audience to update.
* The audience's `name` field is used to identify the audience to be updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Audience audience = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The audience.
*/
@java.lang.Override
public com.google.analytics.admin.v1alpha.Audience getAudience() {
return audience_ == null
? com.google.analytics.admin.v1alpha.Audience.getDefaultInstance()
: audience_;
}
/**
*
*
* <pre>
* Required. The audience to update.
* The audience's `name` field is used to identify the audience to be updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Audience audience = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.analytics.admin.v1alpha.AudienceOrBuilder getAudienceOrBuilder() {
return audience_ == null
? com.google.analytics.admin.v1alpha.Audience.getDefaultInstance()
: audience_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getAudience());
}
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, getAudience());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.analytics.admin.v1alpha.UpdateAudienceRequest)) {
return super.equals(obj);
}
com.google.analytics.admin.v1alpha.UpdateAudienceRequest other =
(com.google.analytics.admin.v1alpha.UpdateAudienceRequest) obj;
if (hasAudience() != other.hasAudience()) return false;
if (hasAudience()) {
if (!getAudience().equals(other.getAudience())) 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 (hasAudience()) {
hash = (37 * hash) + AUDIENCE_FIELD_NUMBER;
hash = (53 * hash) + getAudience().hashCode();
}
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.analytics.admin.v1alpha.UpdateAudienceRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.UpdateAudienceRequest 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.UpdateAudienceRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.UpdateAudienceRequest 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.UpdateAudienceRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.UpdateAudienceRequest 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.UpdateAudienceRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.UpdateAudienceRequest 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.UpdateAudienceRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.UpdateAudienceRequest 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.UpdateAudienceRequest 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.UpdateAudienceRequest 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.UpdateAudienceRequest 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 UpdateAudience RPC.
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1alpha.UpdateAudienceRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.analytics.admin.v1alpha.UpdateAudienceRequest)
com.google.analytics.admin.v1alpha.UpdateAudienceRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdateAudienceRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdateAudienceRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1alpha.UpdateAudienceRequest.class,
com.google.analytics.admin.v1alpha.UpdateAudienceRequest.Builder.class);
}
// Construct using com.google.analytics.admin.v1alpha.UpdateAudienceRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getAudienceFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
audience_ = null;
if (audienceBuilder_ != null) {
audienceBuilder_.dispose();
audienceBuilder_ = null;
}
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdateAudienceRequest_descriptor;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.UpdateAudienceRequest getDefaultInstanceForType() {
return com.google.analytics.admin.v1alpha.UpdateAudienceRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.UpdateAudienceRequest build() {
com.google.analytics.admin.v1alpha.UpdateAudienceRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.UpdateAudienceRequest buildPartial() {
com.google.analytics.admin.v1alpha.UpdateAudienceRequest result =
new com.google.analytics.admin.v1alpha.UpdateAudienceRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.analytics.admin.v1alpha.UpdateAudienceRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.audience_ = audienceBuilder_ == null ? audience_ : audienceBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build();
to_bitField0_ |= 0x00000002;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.analytics.admin.v1alpha.UpdateAudienceRequest) {
return mergeFrom((com.google.analytics.admin.v1alpha.UpdateAudienceRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.analytics.admin.v1alpha.UpdateAudienceRequest other) {
if (other == com.google.analytics.admin.v1alpha.UpdateAudienceRequest.getDefaultInstance())
return this;
if (other.hasAudience()) {
mergeAudience(other.getAudience());
}
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(getAudienceFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.analytics.admin.v1alpha.Audience audience_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.analytics.admin.v1alpha.Audience,
com.google.analytics.admin.v1alpha.Audience.Builder,
com.google.analytics.admin.v1alpha.AudienceOrBuilder>
audienceBuilder_;
/**
*
*
* <pre>
* Required. The audience to update.
* The audience's `name` field is used to identify the audience to be updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Audience audience = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the audience field is set.
*/
public boolean hasAudience() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The audience to update.
* The audience's `name` field is used to identify the audience to be updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Audience audience = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The audience.
*/
public com.google.analytics.admin.v1alpha.Audience getAudience() {
if (audienceBuilder_ == null) {
return audience_ == null
? com.google.analytics.admin.v1alpha.Audience.getDefaultInstance()
: audience_;
} else {
return audienceBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The audience to update.
* The audience's `name` field is used to identify the audience to be updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Audience audience = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setAudience(com.google.analytics.admin.v1alpha.Audience value) {
if (audienceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
audience_ = value;
} else {
audienceBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The audience to update.
* The audience's `name` field is used to identify the audience to be updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Audience audience = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setAudience(
com.google.analytics.admin.v1alpha.Audience.Builder builderForValue) {
if (audienceBuilder_ == null) {
audience_ = builderForValue.build();
} else {
audienceBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The audience to update.
* The audience's `name` field is used to identify the audience to be updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Audience audience = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeAudience(com.google.analytics.admin.v1alpha.Audience value) {
if (audienceBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& audience_ != null
&& audience_ != com.google.analytics.admin.v1alpha.Audience.getDefaultInstance()) {
getAudienceBuilder().mergeFrom(value);
} else {
audience_ = value;
}
} else {
audienceBuilder_.mergeFrom(value);
}
if (audience_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The audience to update.
* The audience's `name` field is used to identify the audience to be updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Audience audience = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearAudience() {
bitField0_ = (bitField0_ & ~0x00000001);
audience_ = null;
if (audienceBuilder_ != null) {
audienceBuilder_.dispose();
audienceBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The audience to update.
* The audience's `name` field is used to identify the audience to be updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Audience audience = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.analytics.admin.v1alpha.Audience.Builder getAudienceBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getAudienceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The audience to update.
* The audience's `name` field is used to identify the audience to be updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Audience audience = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.analytics.admin.v1alpha.AudienceOrBuilder getAudienceOrBuilder() {
if (audienceBuilder_ != null) {
return audienceBuilder_.getMessageOrBuilder();
} else {
return audience_ == null
? com.google.analytics.admin.v1alpha.Audience.getDefaultInstance()
: audience_;
}
}
/**
*
*
* <pre>
* Required. The audience to update.
* The audience's `name` field is used to identify the audience to be updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Audience audience = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.analytics.admin.v1alpha.Audience,
com.google.analytics.admin.v1alpha.Audience.Builder,
com.google.analytics.admin.v1alpha.AudienceOrBuilder>
getAudienceFieldBuilder() {
if (audienceBuilder_ == null) {
audienceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.analytics.admin.v1alpha.Audience,
com.google.analytics.admin.v1alpha.Audience.Builder,
com.google.analytics.admin.v1alpha.AudienceOrBuilder>(
getAudience(), getParentForChildren(), isClean());
audience_ = null;
}
return audienceBuilder_;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
updateMaskBuilder_;
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
} else {
updateMaskBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& updateMask_ != null
&& updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) {
getUpdateMaskBuilder().mergeFrom(value);
} else {
updateMask_ = value;
}
} else {
updateMaskBuilder_.mergeFrom(value);
}
if (updateMask_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000002);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.analytics.admin.v1alpha.UpdateAudienceRequest)
}
// @@protoc_insertion_point(class_scope:google.analytics.admin.v1alpha.UpdateAudienceRequest)
private static final com.google.analytics.admin.v1alpha.UpdateAudienceRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.analytics.admin.v1alpha.UpdateAudienceRequest();
}
public static com.google.analytics.admin.v1alpha.UpdateAudienceRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateAudienceRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateAudienceRequest>() {
@java.lang.Override
public UpdateAudienceRequest 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<UpdateAudienceRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateAudienceRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.UpdateAudienceRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,387 | java-retail/proto-google-cloud-retail-v2/src/main/java/com/google/cloud/retail/v2/ListProductsResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/retail/v2/product_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.retail.v2;
/**
*
*
* <pre>
* Response message for
* [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts]
* method.
* </pre>
*
* Protobuf type {@code google.cloud.retail.v2.ListProductsResponse}
*/
public final class ListProductsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.retail.v2.ListProductsResponse)
ListProductsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListProductsResponse.newBuilder() to construct.
private ListProductsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListProductsResponse() {
products_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListProductsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.retail.v2.ProductServiceProto
.internal_static_google_cloud_retail_v2_ListProductsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.retail.v2.ProductServiceProto
.internal_static_google_cloud_retail_v2_ListProductsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.retail.v2.ListProductsResponse.class,
com.google.cloud.retail.v2.ListProductsResponse.Builder.class);
}
public static final int PRODUCTS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.retail.v2.Product> products_;
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.retail.v2.Product> getProductsList() {
return products_;
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.retail.v2.ProductOrBuilder>
getProductsOrBuilderList() {
return products_;
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
@java.lang.Override
public int getProductsCount() {
return products_.size();
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
@java.lang.Override
public com.google.cloud.retail.v2.Product getProducts(int index) {
return products_.get(index);
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
@java.lang.Override
public com.google.cloud.retail.v2.ProductOrBuilder getProductsOrBuilder(int index) {
return products_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token that can be sent as
* [ListProductsRequest.page_token][google.cloud.retail.v2.ListProductsRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListProductsRequest.page_token][google.cloud.retail.v2.ListProductsRequest.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 < products_.size(); i++) {
output.writeMessage(1, products_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < products_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, products_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.retail.v2.ListProductsResponse)) {
return super.equals(obj);
}
com.google.cloud.retail.v2.ListProductsResponse other =
(com.google.cloud.retail.v2.ListProductsResponse) obj;
if (!getProductsList().equals(other.getProductsList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getProductsCount() > 0) {
hash = (37 * hash) + PRODUCTS_FIELD_NUMBER;
hash = (53 * hash) + getProductsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.retail.v2.ListProductsResponse parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.retail.v2.ListProductsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.retail.v2.ListProductsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.retail.v2.ListProductsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.retail.v2.ListProductsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.retail.v2.ListProductsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.retail.v2.ListProductsResponse parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.retail.v2.ListProductsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.retail.v2.ListProductsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.retail.v2.ListProductsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.retail.v2.ListProductsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.retail.v2.ListProductsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.retail.v2.ListProductsResponse 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
* [ProductService.ListProducts][google.cloud.retail.v2.ProductService.ListProducts]
* method.
* </pre>
*
* Protobuf type {@code google.cloud.retail.v2.ListProductsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.retail.v2.ListProductsResponse)
com.google.cloud.retail.v2.ListProductsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.retail.v2.ProductServiceProto
.internal_static_google_cloud_retail_v2_ListProductsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.retail.v2.ProductServiceProto
.internal_static_google_cloud_retail_v2_ListProductsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.retail.v2.ListProductsResponse.class,
com.google.cloud.retail.v2.ListProductsResponse.Builder.class);
}
// Construct using com.google.cloud.retail.v2.ListProductsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (productsBuilder_ == null) {
products_ = java.util.Collections.emptyList();
} else {
products_ = null;
productsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.retail.v2.ProductServiceProto
.internal_static_google_cloud_retail_v2_ListProductsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.retail.v2.ListProductsResponse getDefaultInstanceForType() {
return com.google.cloud.retail.v2.ListProductsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.retail.v2.ListProductsResponse build() {
com.google.cloud.retail.v2.ListProductsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.retail.v2.ListProductsResponse buildPartial() {
com.google.cloud.retail.v2.ListProductsResponse result =
new com.google.cloud.retail.v2.ListProductsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.retail.v2.ListProductsResponse result) {
if (productsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
products_ = java.util.Collections.unmodifiableList(products_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.products_ = products_;
} else {
result.products_ = productsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.retail.v2.ListProductsResponse 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.retail.v2.ListProductsResponse) {
return mergeFrom((com.google.cloud.retail.v2.ListProductsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.retail.v2.ListProductsResponse other) {
if (other == com.google.cloud.retail.v2.ListProductsResponse.getDefaultInstance())
return this;
if (productsBuilder_ == null) {
if (!other.products_.isEmpty()) {
if (products_.isEmpty()) {
products_ = other.products_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureProductsIsMutable();
products_.addAll(other.products_);
}
onChanged();
}
} else {
if (!other.products_.isEmpty()) {
if (productsBuilder_.isEmpty()) {
productsBuilder_.dispose();
productsBuilder_ = null;
products_ = other.products_;
bitField0_ = (bitField0_ & ~0x00000001);
productsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getProductsFieldBuilder()
: null;
} else {
productsBuilder_.addAllMessages(other.products_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.retail.v2.Product m =
input.readMessage(
com.google.cloud.retail.v2.Product.parser(), extensionRegistry);
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.add(m);
} else {
productsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.retail.v2.Product> products_ =
java.util.Collections.emptyList();
private void ensureProductsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
products_ = new java.util.ArrayList<com.google.cloud.retail.v2.Product>(products_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.retail.v2.Product,
com.google.cloud.retail.v2.Product.Builder,
com.google.cloud.retail.v2.ProductOrBuilder>
productsBuilder_;
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public java.util.List<com.google.cloud.retail.v2.Product> getProductsList() {
if (productsBuilder_ == null) {
return java.util.Collections.unmodifiableList(products_);
} else {
return productsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public int getProductsCount() {
if (productsBuilder_ == null) {
return products_.size();
} else {
return productsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public com.google.cloud.retail.v2.Product getProducts(int index) {
if (productsBuilder_ == null) {
return products_.get(index);
} else {
return productsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public Builder setProducts(int index, com.google.cloud.retail.v2.Product value) {
if (productsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureProductsIsMutable();
products_.set(index, value);
onChanged();
} else {
productsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public Builder setProducts(
int index, com.google.cloud.retail.v2.Product.Builder builderForValue) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.set(index, builderForValue.build());
onChanged();
} else {
productsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public Builder addProducts(com.google.cloud.retail.v2.Product value) {
if (productsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureProductsIsMutable();
products_.add(value);
onChanged();
} else {
productsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public Builder addProducts(int index, com.google.cloud.retail.v2.Product value) {
if (productsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureProductsIsMutable();
products_.add(index, value);
onChanged();
} else {
productsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public Builder addProducts(com.google.cloud.retail.v2.Product.Builder builderForValue) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.add(builderForValue.build());
onChanged();
} else {
productsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public Builder addProducts(
int index, com.google.cloud.retail.v2.Product.Builder builderForValue) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.add(index, builderForValue.build());
onChanged();
} else {
productsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public Builder addAllProducts(
java.lang.Iterable<? extends com.google.cloud.retail.v2.Product> values) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, products_);
onChanged();
} else {
productsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public Builder clearProducts() {
if (productsBuilder_ == null) {
products_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
productsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public Builder removeProducts(int index) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.remove(index);
onChanged();
} else {
productsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public com.google.cloud.retail.v2.Product.Builder getProductsBuilder(int index) {
return getProductsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public com.google.cloud.retail.v2.ProductOrBuilder getProductsOrBuilder(int index) {
if (productsBuilder_ == null) {
return products_.get(index);
} else {
return productsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public java.util.List<? extends com.google.cloud.retail.v2.ProductOrBuilder>
getProductsOrBuilderList() {
if (productsBuilder_ != null) {
return productsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(products_);
}
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public com.google.cloud.retail.v2.Product.Builder addProductsBuilder() {
return getProductsFieldBuilder()
.addBuilder(com.google.cloud.retail.v2.Product.getDefaultInstance());
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public com.google.cloud.retail.v2.Product.Builder addProductsBuilder(int index) {
return getProductsFieldBuilder()
.addBuilder(index, com.google.cloud.retail.v2.Product.getDefaultInstance());
}
/**
*
*
* <pre>
* The [Product][google.cloud.retail.v2.Product]s.
* </pre>
*
* <code>repeated .google.cloud.retail.v2.Product products = 1;</code>
*/
public java.util.List<com.google.cloud.retail.v2.Product.Builder> getProductsBuilderList() {
return getProductsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.retail.v2.Product,
com.google.cloud.retail.v2.Product.Builder,
com.google.cloud.retail.v2.ProductOrBuilder>
getProductsFieldBuilder() {
if (productsBuilder_ == null) {
productsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.retail.v2.Product,
com.google.cloud.retail.v2.Product.Builder,
com.google.cloud.retail.v2.ProductOrBuilder>(
products_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
products_ = null;
}
return productsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token that can be sent as
* [ListProductsRequest.page_token][google.cloud.retail.v2.ListProductsRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListProductsRequest.page_token][google.cloud.retail.v2.ListProductsRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListProductsRequest.page_token][google.cloud.retail.v2.ListProductsRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListProductsRequest.page_token][google.cloud.retail.v2.ListProductsRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListProductsRequest.page_token][google.cloud.retail.v2.ListProductsRequest.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.retail.v2.ListProductsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.retail.v2.ListProductsResponse)
private static final com.google.cloud.retail.v2.ListProductsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.retail.v2.ListProductsResponse();
}
public static com.google.cloud.retail.v2.ListProductsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListProductsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListProductsResponse>() {
@java.lang.Override
public ListProductsResponse 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<ListProductsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListProductsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.retail.v2.ListProductsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/jena | 36,586 | jena-core/src/main/java/org/apache/jena/reasoner/rulesys/FBRuleInfGraph.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.jena.reasoner.rulesys;
import java.util.* ;
import org.apache.jena.datatypes.RDFDatatype ;
import org.apache.jena.datatypes.TypeMapper ;
import org.apache.jena.graph.* ;
import org.apache.jena.graph.impl.LiteralLabel ;
import org.apache.jena.rdf.model.Model ;
import org.apache.jena.rdf.model.ModelFactory ;
import org.apache.jena.rdf.model.RDFNode ;
import org.apache.jena.reasoner.* ;
import org.apache.jena.reasoner.rulesys.impl.* ;
import org.apache.jena.reasoner.transitiveReasoner.TransitiveEngine ;
import org.apache.jena.reasoner.transitiveReasoner.TransitiveGraphCache ;
import org.apache.jena.reasoner.transitiveReasoner.TransitiveReasoner ;
import org.apache.jena.shared.impl.JenaParameters ;
import org.apache.jena.util.OneToManyMap ;
import org.apache.jena.util.PrintUtil ;
import org.apache.jena.util.iterator.ExtendedIterator ;
import org.apache.jena.util.iterator.UniqueFilter ;
import org.apache.jena.vocabulary.RDFS ;
import org.apache.jena.vocabulary.ReasonerVocabulary ;
import org.slf4j.Logger ;
import org.slf4j.LoggerFactory ;
/**
* An inference graph that uses a mixture of forward and backward
* chaining rules. The forward rules can create direct deductions from
* the source data and schema and can also create backward rules. A
* query is answered by consulting the union of the raw data, the forward
* derived results and any relevant backward rules (whose answers are tabled
* for future reference).
*/
public class FBRuleInfGraph extends BasicForwardRuleInfGraph implements BackwardRuleInfGraphI {
/** Single context for the reasoner, used when passing information to builtins */
protected BBRuleContext context;
/** A finder that searches across the data, schema, axioms and forward deductions*/
protected Finder dataFind;
/** The core backward rule engine which includes all the memoized results */
protected LPBRuleEngine bEngine;
/** The original rule set as supplied */
protected List<Rule> rawRules;
/** The rule list after possible extension by preprocessing hooks */
protected List<Rule> rules;
/** Static switch from Basic to RETE implementation of the forward component */
public static boolean useRETE = true;
/** Flag, if true then subClass and subProperty lattices will be optimized using TGCs */
protected boolean useTGCCaching = false;
/** Optional precomputed cache of the subClass/subproperty lattices */
protected TransitiveEngine transitiveEngine;
/** Optional list of preprocessing hooks to be run in sequence during preparation time */
protected List<RulePreprocessHook> preprocessorHooks;
/** Cache of temporary property values inferred through getTemp calls */
protected TempNodeCache tempNodecache;
/** Table of temp nodes which should be hidden from output listings */
protected Set<Node> hiddenNodes;
/** Optional map of property node to datatype ranges */
protected HashMap<Node, List<RDFDatatype>> dtRange = null;
/** Flag to request datatype range validation be included in the validation step */
protected boolean requestDatatypeRangeValidation = false;
static Logger logger = LoggerFactory.getLogger(FBRuleInfGraph.class);
// =======================================================================
// Constructors
/**
* Constructor.
* @param reasoner the reasoner which created this inf graph instance
* @param schema the (optional) schema graph to be included
*/
public FBRuleInfGraph(Reasoner reasoner, Graph schema) {
super(reasoner, schema);
constructorInit(schema);
}
/**
* Constructor.
* @param reasoner the reasoner which created this inf graph instance
* @param rules the rules to process
* @param schema the (optional) schema graph to be included
*/
public FBRuleInfGraph(Reasoner reasoner, List<Rule> rules, Graph schema) {
super( reasoner, rules, schema );
this.rawRules = rules;
constructorInit( schema );
}
/**
* Constructor.
* @param reasoner the reasoner which created this inf graph instance
* @param rules the rules to process
* @param schema the (optional) schema graph to be included
* @param data the data graph to be processed
*/
public FBRuleInfGraph( Reasoner reasoner, List<Rule> rules, Graph schema, Graph data ) {
super(reasoner, rules, schema, data);
this.rawRules = rules;
constructorInit(schema);
}
/**
* Common pieces of initialization code which apply in all constructor cases.
*/
private void constructorInit(Graph schema) {
initLP(schema);
tempNodecache = new TempNodeCache(this);
if (JenaParameters.enableFilteringOfHiddenInfNodes) {
hiddenNodes = new HashSet<>();
if (schema != null && schema instanceof FBRuleInfGraph) {
hiddenNodes.addAll(((FBRuleInfGraph)schema).hiddenNodes);
}
}
}
/**
* Instantiate the forward rule engine to use.
* Subclasses can override this to switch to, say, a RETE implementation.
* @param rules the rule set or null if there are not rules bound in yet.
*/
@Override
protected void instantiateRuleEngine(List<Rule> rules) {
engine = FRuleEngineIFactory.getInstance().createFRuleEngineI(this, rules, useRETE);
}
/**
* Initialize the LP engine, based on an optional schema graph.
*/
private void initLP(Graph schema) {
if (schema != null && schema instanceof FBRuleInfGraph) {
LPRuleStore newStore = new LPRuleStore();
newStore.addAll(((FBRuleInfGraph)schema).bEngine.getRuleStore());
bEngine = new LPBRuleEngine(this, newStore);
} else {
bEngine = new LPBRuleEngine(this);
}
}
/**
* Instantiate the optional caches for the subclass/suproperty lattices.
* Unless this call is made the TGC caching will not be used.
*/
public void setUseTGCCache() {
useTGCCaching = true;
resetTGCCache();
}
/**
* Rest the transitive graph caches
*/
private void resetTGCCache() {
if (schemaGraph != null) {
transitiveEngine = new TransitiveEngine(((FBRuleInfGraph)schemaGraph).transitiveEngine);
} else {
transitiveEngine = new TransitiveEngine(
new TransitiveGraphCache(ReasonerVocabulary.directSubClassOf.asNode(), RDFS.subClassOf.asNode()),
new TransitiveGraphCache(ReasonerVocabulary.directSubPropertyOf.asNode(), RDFS.subPropertyOf.asNode()));
}
}
// =======================================================================
// Interface between infGraph and the goal processing machinery
/**
* Search the combination of data and deductions graphs for the given triple pattern.
* This may different from the normal find operation in the base of hybrid reasoners
* where we are side-stepping the backward deduction step.
*/
@Override
public ExtendedIterator<Triple> findDataMatches(Node subject, Node predicate, Node object) {
return dataFind.find(new TriplePattern(subject, predicate, object));
}
/**
* Search the combination of data and deductions graphs for the given triple pattern.
* This may different from the normal find operation in the base of hybrid reasoners
* where we are side-stepping the backward deduction step.
*/
@Override
public ExtendedIterator<Triple> findDataMatches(TriplePattern pattern) {
return dataFind.find(pattern);
}
/**
* Process a call to a builtin predicate
* @param clause the Functor representing the call
* @param env the BindingEnvironment for this call
* @param rule the rule which is invoking this call
* @return true if the predicate succeeds
*/
@Override
public boolean processBuiltin(ClauseEntry clause, Rule rule, BindingEnvironment env) {
throw new ReasonerException("Internal error in FBLP rule engine, incorrect invocation of builtin in rule " + rule);
// TODO: Remove
// if (clause instanceof Functor) {
// context.setEnv(env);
// context.setRule(rule);
// return((Functor)clause).evalAsBodyClause(context);
// } else {
// throw new ReasonerException("Illegal builtin predicate: " + clause + " in rule " + rule);
// }
}
/**
* Adds a new Backward rule as a result of a forward rule process. Only some
* infgraphs support this.
*/
@Override
public void addBRule(Rule brule) {
if (logger.isDebugEnabled()) {
logger.debug("Adding rule " + brule);
}
bEngine.addRule(brule);
bEngine.reset();
}
/**
* Deletes a new Backward rule as a rules of a forward rule process. Only some
* infgraphs support this.
*/
@Override
public void deleteBRule(Rule brule) {
if (logger.isDebugEnabled()) {
logger.debug("Deleting rule " + brule);
}
bEngine.deleteRule(brule);
bEngine.reset();
}
/**
* Adds a set of new Backward rules
*/
public void addBRules(List<Rule> rules) {
for ( Rule rule : rules )
{
// logger.debug("Adding rule " + rule);
bEngine.addRule( rule );
}
bEngine.reset();
}
/**
* Return an ordered list of all registered backward rules. Includes those
* generated by forward productions.
*/
public List<Rule> getBRules() {
return bEngine.getAllRules();
}
/**
* Return the originally supplied set of rules, may be a mix of forward
* and backward rules.
*/
public List<Rule> getRules() {
return rules;
}
/**
* Set a predicate to be tabled/memoized by the LP engine.
*/
public void setTabled(Node predicate) {
bEngine.tablePredicate(predicate);
if (traceOn) {
logger.info("LP TABLE " + predicate);
}
}
/**
* Return a compiled representation of all the registered
* forward rules.
*/
private Object getForwardRuleStore() {
return engine.getRuleStore();
}
/**
* Add a new deduction to the deductions graph.
*/
@Override
public void addDeduction(Triple t) {
getCurrentDeductionsGraph().add(t);
if (useTGCCaching) {
transitiveEngine.add(t);
}
}
/**
* Retrieve or create a bNode representing an inferred property value.
* @param instance the base instance node to which the property applies
* @param prop the property node whose value is being inferred
* @param pclass the (optional, can be null) class for the inferred value.
* @return the bNode representing the property value
*/
@Override
public Node getTemp(Node instance, Node prop, Node pclass) {
return tempNodecache.getTemp(instance, prop, pclass);
}
// =======================================================================
// Core inf graph methods
/**
* Add a new rule to the rule set. This should only be used by implementations
* of RuleProprocessHook (which are called during rule system preparation phase).
* If called at other times the rule won't be correctly transferred into the
* underlying engines.
*/
public void addRuleDuringPrepare(Rule rule) {
if (rules == rawRules) {
// Ensure the original is preserved in case we need to do a restart
rules = new ArrayList<>( rawRules );
// if (rawRules instanceof ArrayList) {
// rules = (ArrayList<Rule>) ((ArrayList<Rule>)rawRules).clone();
// } else {
// rules = new ArrayList<Rule>(rawRules);
// }
// Rebuild the forward engine to use the cloned rules
instantiateRuleEngine(rules);
}
rules.add(rule);
}
/**
* Add a new preprocessing hook defining an operation that
* should be run when the preparation phase is underway.
*/
public void addPreprocessingHook(RulePreprocessHook hook) {
if (preprocessorHooks == null) {
preprocessorHooks = new ArrayList<>();
}
preprocessorHooks.add(hook);
}
/**
* Perform any initial processing and caching. This call is optional. Most
* engines either have negligable set up work or will perform an implicit
* "prepare" if necessary. The call is provided for those occasions where
* substantial preparation work is possible (e.g. running a forward chaining
* rule system) and where an application might wish greater control over when
* this preparation is done.
*/
@Override
public synchronized void prepare() {
if (this.isPrepared()) return;
this.setPreparedState(true);
// Restore the original pre-hookProcess rules
rules = rawRules;
// Is there any data to bind in yet?
Graph data = null;
if (fdata != null) data = fdata.getGraph();
// initilize the deductions graph
if (fdeductions != null) {
Graph oldDeductions = (fdeductions).getGraph();
oldDeductions.clear();
} else {
fdeductions = new FGraph( createDeductionsGraph() );
}
dataFind = (data == null) ? fdeductions : FinderUtil.cascade(fdeductions, fdata);
Finder dataSource = fdata;
// Initialize the optional TGC caches
if (useTGCCaching) {
resetTGCCache();
if (schemaGraph != null) {
// Check if we can just reuse the copy of the raw
if (
(transitiveEngine.checkOccurance(TransitiveReasoner.subPropertyOf, data) ||
transitiveEngine.checkOccurance(TransitiveReasoner.subClassOf, data) ||
transitiveEngine.checkOccurance(RDFS.domain.asNode(), data) ||
transitiveEngine.checkOccurance(RDFS.range.asNode(), data) )) {
// The data graph contains some ontology knowledge so split the caches
// now and rebuild them using merged data
transitiveEngine.insert(((FBRuleInfGraph)schemaGraph).fdata, fdata);
}
} else {
if (data != null) {
transitiveEngine.insert(null, fdata);
}
}
// Insert any axiomatic statements into the caches
for ( Rule r : rules )
{
if ( r.bodyLength() == 0 )
{
// An axiom
for ( int j = 0; j < r.headLength(); j++ )
{
ClauseEntry head = r.getHeadElement( j );
if ( head instanceof TriplePattern )
{
TriplePattern h = (TriplePattern) head;
transitiveEngine.add( h.asTriple() );
}
}
}
}
transitiveEngine.setCaching(true, true);
// dataFind = FinderUtil.cascade(subClassCache, subPropertyCache, dataFind);
dataFind = FinderUtil.cascade(dataFind, transitiveEngine.getSubClassCache(), transitiveEngine.getSubPropertyCache());
// Without the next statement then the transitive closures are not seen by the forward rules
dataSource = FinderUtil.cascade(dataSource, transitiveEngine.getSubClassCache(), transitiveEngine.getSubPropertyCache());
}
// Make sure there are no Brules left over from pior runs
bEngine.deleteAllRules();
// Call any optional preprocessing hook
if (preprocessorHooks != null && preprocessorHooks.size() > 0) {
Graph inserts = GraphMemFactory.createDefaultGraph();
for ( RulePreprocessHook hook : preprocessorHooks )
{
hook.run( this, dataFind, inserts );
}
if (inserts.size() > 0) {
FGraph finserts = new FGraph(inserts);
dataSource = FinderUtil.cascade(fdata, finserts);
dataFind = FinderUtil.cascade(dataFind, finserts);
}
}
boolean rulesLoaded = false;
if (schemaGraph != null) {
Graph rawPreload = ((InfGraph)schemaGraph).getRawGraph();
if (rawPreload != null) {
dataFind = FinderUtil.cascade(dataFind, new FGraph(rawPreload));
}
rulesLoaded = preloadDeductions(schemaGraph);
}
if (rulesLoaded) {
engine.fastInit(dataSource);
} else {
// No preload so do the rule separation
addBRules(extractPureBackwardRules(rules));
engine.init(true, dataSource);
}
// Prepare the context for builtins run in backwards engine
context = new BBRuleContext(this);
}
/**
* Cause the inference graph to reconsult the underlying graph to take
* into account changes. Normally changes are made through the InfGraph's add and
* remove calls are will be handled appropriately. However, in some cases changes
* are made "behind the InfGraph's back" and this forces a full reconsult of
* the changed data.
*/
@Override
public void rebind() {
version++;
if (bEngine != null) bEngine.reset();
this.setPreparedState(false);
}
/**
* Cause the inference graph to reconsult both the underlying graph and
* the reasoner ruleset, permits the forward rule set to be dynamically changed.
* Causes the entire rule engine to be rebuilt from the current ruleset and
* reinitialized against the current data. Not needed for normal cases.
*/
public void rebindAll() {
rawRules = ((FBRuleReasoner)reasoner).getRules();
instantiateRuleEngine( rawRules );
rebind();
}
/**
* Set the state of the trace flag. If set to true then rule firings
* are logged out to the Log at "INFO" level.
*/
@Override
public void setTraceOn(boolean state) {
super.setTraceOn(state);
bEngine.setTraceOn(state);
}
/**
* Set to true to enable derivation caching
*/
@Override
public void setDerivationLogging(boolean recordDerivations) {
this.recordDerivations = recordDerivations;
engine.setDerivationLogging(recordDerivations);
bEngine.setDerivationLogging(recordDerivations);
if (recordDerivations) {
derivations = new OneToManyMap<>();
} else {
derivations = null;
}
}
/**
* Return the number of rules fired since this rule engine instance
* was created and initialized. The current implementation only counts
* forward rules and does not track dynamic backward rules needed for
* specific queries.
*/
@Override
public long getNRulesFired() {
return engine.getNRulesFired();
}
/**
* Extended find interface used in situations where the implementator
* may or may not be able to answer the complete query. It will
* attempt to answer the pattern but if its answers are not known
* to be complete then it will also pass the request on to the nested
* Finder to append more results.
* @param pattern a TriplePattern to be matched against the data
* @param continuation either a Finder or a normal Graph which
* will be asked for additional match results if the implementor
* may not have completely satisfied the query.
*/
@Override
public ExtendedIterator<Triple> findWithContinuation(TriplePattern pattern, Finder continuation) {
checkOpen();
this.requirePrepared();
ExtendedIterator<Triple> result =bEngine.find(pattern).filterKeep( new UniqueFilter<Triple>());
if (continuation != null) {
result = result.andThen(continuation.find(pattern));
}
if (filterFunctors) {
// return result.filterDrop(Functor.acceptFilter);
return result.filterDrop( t -> FBRuleInfGraph.this.accept( t ) );
} else {
return result;
}
}
/**
* Internal variant of find which omits the filters which block illegal RDF data.
* @param pattern a TriplePattern to be matched against the data
*/
public ExtendedIterator<Triple> findFull(TriplePattern pattern) {
checkOpen();
this.requirePrepared();
return bEngine.find(pattern).filterKeep( new UniqueFilter<Triple>());
}
/**
* Returns an iterator over Triples.
* This implementation assumes that the underlying findWithContinuation
* will have also consulted the raw data.
*/
@Override
public ExtendedIterator<Triple> graphBaseFind(Node subject, Node property, Node object) {
return findWithContinuation(new TriplePattern(subject, property, object), null);
}
/**
* Basic pattern lookup interface.
* This implementation assumes that the underlying findWithContinuation
* will have also consulted the raw data.
* @param pattern a TriplePattern to be matched against the data
* @return a ExtendedIterator over all Triples in the data set
* that match the pattern
*/
@Override
public ExtendedIterator<Triple> find(TriplePattern pattern) {
return findWithContinuation(pattern, null);
}
/**
* Flush out all cached results. Future queries have to start from scratch.
*/
@Override
public synchronized void reset() {
version++;
bEngine.reset();
this.setPreparedState(false);
}
/**
* Add one triple to the data graph, run any rules triggered by
* the new data item, recursively adding any generated triples.
*/
@Override
public synchronized void performAdd(Triple t) {
version++;
fdata.getGraph().add(t);
if (useTGCCaching) {
if (transitiveEngine.add(t)) this.setPreparedState(false);
}
if (this.isPrepared()) {
boolean needReset = false;
if (preprocessorHooks != null && preprocessorHooks.size() > 0) {
if (preprocessorHooks.size() > 1) {
for ( RulePreprocessHook preprocessorHook : preprocessorHooks )
{
if ( preprocessorHook.needsRerun( this, t ) )
{
needReset = true;
break;
}
}
} else {
needReset = preprocessorHooks.get(0).needsRerun(this, t);
}
}
if (needReset) {
this.setPreparedState(false);
} else {
engine.add(t);
}
}
bEngine.reset();
}
/**
* Removes the triple t (if possible) from the set belonging to this graph.
*/
@Override
public void performDelete(Triple t) {
version++;
//boolean removeIsFromBase = fdata.getGraph().contains(t);
fdata.getGraph().delete(t);
if (useTGCCaching) {
if (transitiveEngine.delete(t)) {
if (this.isPrepared()) {
bEngine.deleteAllRules();
}
this.setPreparedState(false);
}
}
// Full incremental remove processing requires reference counting
// of all deductions. It's not clear the cost of maintaining the
// reference counts is worth it so the current implementation
// forces a recompute if any external deletes are performed.
if (this.isPrepared()) {
bEngine.deleteAllRules();
this.setPreparedState(false);
// Re-enable the code below when/if ref counting is added and remove above
// if (removeIsFromBase) engine.delete(t);
}
bEngine.reset();
}
/**
* Return a new inference graph which is a clone of the current graph
* together with an additional set of data premises. Attempts to the replace
* the default brute force implementation by one that can reuse some of the
* existing deductions.
*/
// This implementatin was incomplete. By commenting it out we revert to
// the global brute force solution of cloning the full graph
// public InfGraph cloneWithPremises(Graph premises) {
// prepare();
// FBRuleInfGraph graph = new FBRuleInfGraph(getReasoner(), rawRules, this);
// if (useTGCCaching) graph.setUseTGCCache();
// graph.setDerivationLogging(recordDerivations);
// graph.setTraceOn(traceOn);
// // Implementation note: whilst current tests pass its not clear that
// // the nested passing of FBRuleInfGraph's will correctly handle all
// // cases of indirectly bound schema data. If we do uncover a problem here
// // then either include the raw schema in a Union with the premises or
// // revert of a more brute force version.
// graph.rebind(premises);
// return graph;
// }
/**
* Free all resources, any further use of this Graph is an error.
*/
@Override
public void close() {
if (!closed) {
bEngine.halt();
bEngine = null;
transitiveEngine = null;
super.close();
}
}
// =======================================================================
// Generalized validation machinery. Assumes rule set has special validation
// rules that can be turned on.
/**
* Test the consistency of the bound data. This normally tests
* the validity of the bound instance data against the bound
* schema data.
* @return a ValidityReport structure
*/
@Override
public ValidityReport validate() {
checkOpen();
StandardValidityReport report = new StandardValidityReport();
// Switch on validation
Triple validateOn = Triple.create(NodeFactory.createBlankNode(),
ReasonerVocabulary.RB_VALIDATION.asNode(),
Functor.makeFunctorNode("on", new Node[] {}));
// We sneak this switch directly into the engine to avoid contaminating the
// real data - this is only possible only the forward engine has been prepared
// add(validateOn);
this.requirePrepared();
engine.add(validateOn);
// Look for all reports
TriplePattern pattern = new TriplePattern(null, ReasonerVocabulary.RB_VALIDATION_REPORT.asNode(), null);
final Model forConversion = ModelFactory.createDefaultModel();
for (Iterator<Triple> i = findFull(pattern); i.hasNext(); ) {
Triple t = i.next();
Node rNode = t.getObject();
if (rNode.isLiteral()) {
Object rVal = rNode.getLiteralValue();
if (rVal instanceof Functor) {
Functor rFunc = (Functor)rVal;
StringBuilder description = new StringBuilder();
String nature = rFunc.getName();
String type = rFunc.getArgs()[0].toString();
String text = rFunc.getArgs()[1].toString();
description.append( text + "\n");
description.append( "Culprit = " + PrintUtil.print(t.getSubject()) +"\n");
for (int j = 2; j < rFunc.getArgLength(); j++) {
description.append( "Implicated node: " + PrintUtil.print(rFunc.getArgs()[j]) + "\n");
}
RDFNode culprit = forConversion.asRDFNode( t.getSubject() );
report.add(nature.equalsIgnoreCase("error"), type, description.toString(), culprit);
}
}
}
if (requestDatatypeRangeValidation) {
performDatatypeRangeValidation( report );
}
return report;
}
/**
* Switch on/off datatype range validation
*/
public void setDatatypeRangeValidation(boolean on) {
requestDatatypeRangeValidation = on;
}
/**
* Run a datatype range check on all literal values of all properties with a range declaration.
* @param report
*/
protected void performDatatypeRangeValidation(StandardValidityReport report) {
HashMap<Node, List<RDFDatatype>> dtRange = getDTRange();
for ( Node prop : dtRange.keySet() )
{
for ( Iterator<Triple> i = find( null, prop, null ); i.hasNext(); )
{
Triple triple = i.next();
report.add( checkLiteral( prop, triple ) );
}
}
}
/**
* Check a given literal value for a property against the set of
* known range constraints for it.
* @param prop the property node whose range is under scrutiny
* @param triple the statement whose object value is to be checked.
* @return null if the range is legal, otherwise a ValidityReport.Report
* which describes the problem.
*/
public ValidityReport.Report checkLiteral(Node prop, Triple triple) {
Node value = triple.getObject();
List<RDFDatatype> range = getDTRange().get(prop);
if (range != null) {
if (value.isBlank()) return null;
if (!value.isLiteral()) {
return new ValidityReport.Report(true, "dtRange",
"Property " + prop + " has a typed range but was given a non literal value " + value);
}
LiteralLabel ll = value.getLiteral();
for ( RDFDatatype dt : range )
{
if ( !dt.isValidLiteral( ll ) )
{
return new ValidityReport.Report( true, "dtRange", "Property " + prop + " has a typed range " + dt +
"that is not compatible with " + value, triple );
}
}
}
return null;
}
/**
* Return a map from property nodes to a list of RDFDatatype objects
* which have been declared as the range of that property.
*/
protected HashMap<Node, List<RDFDatatype>> getDTRange() {
if (dtRange == null) {
dtRange = new HashMap<>();
for (Iterator<Triple> i = find(null, RDFS.range.asNode(), null); i.hasNext(); ) {
Triple triple = i.next();
Node prop = triple.getSubject();
Node rangeValue = triple.getObject();
if (rangeValue.isURI()) {
RDFDatatype dt = TypeMapper.getInstance().getTypeByName(rangeValue.getURI());
if (dt != null) {
List<RDFDatatype> range = dtRange.get(prop);
if (range == null) {
range = new ArrayList<>();
dtRange.put(prop, range);
}
range.add(dt);
}
}
}
}
return dtRange;
}
// =======================================================================
// Helper methods
/**
* Scan the initial rule set and pick out all the backward-only rules with non-null bodies,
* and transfer these rules to the backward engine.
*/
private static List<Rule> extractPureBackwardRules(List<Rule> rules) {
List<Rule> bRules = new ArrayList<>();
for ( Rule r : rules )
{
if ( r.isBackward() && r.bodyLength() > 0 )
{
bRules.add( r );
}
}
return bRules;
}
/**
* Adds a set of precomputed triples to the deductions store. These do not, themselves,
* fire any rules but provide additional axioms that might enable future rule
* firing when real data is added. Used to implement bindSchema processing
* in the parent Reasoner.
* @return true if the preload was able to load rules as well
*/
@Override
protected boolean preloadDeductions(Graph preloadIn) {
Graph d = fdeductions.getGraph();
FBRuleInfGraph preload = (FBRuleInfGraph)preloadIn;
// If the rule set is the same we can reuse those as well
if (preload.rules == rules) {
// Load raw deductions
for (Iterator<Triple> i = preload.getDeductionsGraph().find(null, null, null); i.hasNext(); ) {
d.add( i.next() );
}
// Load backward rules
addBRules(preload.getBRules());
// Load forward rules
engine.setRuleStore(preload.getForwardRuleStore());
// Add access to raw data
return true;
} else {
return false;
}
}
/**
* Called to flag that a node should be hidden from external queries.
*/
public void hideNode(Node n) {
if (! JenaParameters.enableFilteringOfHiddenInfNodes) return;
if (hiddenNodes == null) {
hiddenNodes = new HashSet<>();
}
synchronized (hiddenNodes) {
hiddenNodes.add(n);
}
}
// =======================================================================
// Support for LP engine profiling
/**
* Reset the LP engine profile.
* @param enable it true then profiling will continue with a new empty profile table,
* if false profiling will stop all current data lost.
*/
public void resetLPProfile(boolean enable) {
bEngine.resetProfile(enable);
}
/**
* Print a profile of LP rules used since the last reset.
*/
public void printLPProfile() {
bEngine.printProfile();
}
// =======================================================================
// Implement Filter signature
/**
* Post-filter query results to hide unwanted
* triples from the glare of publicity. Unwanted triples
* are triples with Functor literals and triples with hidden nodes
* as subject or object.
*/
public boolean accept(Object tin) {
Triple t = (Triple)tin;
if ((t).getSubject().isLiteral()) return true;
if (JenaParameters.enableFilteringOfHiddenInfNodes && hiddenNodes != null) {
if (hiddenNodes.contains(t.getSubject()) || hiddenNodes.contains(t.getObject()) || hiddenNodes.contains(t.getPredicate())) {
return true;
}
}
if (filterFunctors) {
if (Functor.isFunctor(t.getObject())) {
return true;
}
}
return false;
}
// =======================================================================
// Inner classes
/**
* Structure used to wrap up pre-processed/compiled rule sets.
*/
public static class RuleStore {
/** The raw rules */
protected List<Rule> rawRules;
/** The indexed store used by the forward chainer */
protected Object fRuleStore;
/** The separated backward rules */
protected List<Rule> bRules;
/**
* Constructor.
*/
public RuleStore(List<Rule> rawRules, Object fRuleStore, List<Rule> bRules) {
this.rawRules = rawRules;
this.fRuleStore = fRuleStore;
this.bRules = bRules;
}
}
}
|
googleapis/google-cloud-java | 36,336 | java-securitycentermanagement/proto-google-cloud-securitycentermanagement-v1/src/main/java/com/google/cloud/securitycentermanagement/v1/ValidateEventThreatDetectionCustomModuleRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/securitycentermanagement/v1/security_center_management.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.securitycentermanagement.v1;
/**
*
*
* <pre>
* Request message for
* [SecurityCenterManagement.ValidateEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ValidateEventThreatDetectionCustomModule].
* </pre>
*
* Protobuf type {@code
* google.cloud.securitycentermanagement.v1.ValidateEventThreatDetectionCustomModuleRequest}
*/
public final class ValidateEventThreatDetectionCustomModuleRequest
extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.securitycentermanagement.v1.ValidateEventThreatDetectionCustomModuleRequest)
ValidateEventThreatDetectionCustomModuleRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ValidateEventThreatDetectionCustomModuleRequest.newBuilder() to construct.
private ValidateEventThreatDetectionCustomModuleRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ValidateEventThreatDetectionCustomModuleRequest() {
parent_ = "";
rawText_ = "";
type_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ValidateEventThreatDetectionCustomModuleRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto
.internal_static_google_cloud_securitycentermanagement_v1_ValidateEventThreatDetectionCustomModuleRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto
.internal_static_google_cloud_securitycentermanagement_v1_ValidateEventThreatDetectionCustomModuleRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest.class,
com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Resource name of the parent to validate the custom modules under,
* in one of the following formats:
*
* * `organizations/{organization}/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. Resource name of the parent to validate the custom modules under,
* in one of the following formats:
*
* * `organizations/{organization}/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 RAW_TEXT_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object rawText_ = "";
/**
*
*
* <pre>
* Required. The raw text of the module's contents. Used to generate error
* messages.
* </pre>
*
* <code>string raw_text = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The rawText.
*/
@java.lang.Override
public java.lang.String getRawText() {
java.lang.Object ref = rawText_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
rawText_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The raw text of the module's contents. Used to generate error
* messages.
* </pre>
*
* <code>string raw_text = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for rawText.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRawTextBytes() {
java.lang.Object ref = rawText_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
rawText_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TYPE_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object type_ = "";
/**
*
*
* <pre>
* Required. The type of the module. For example, `CONFIGURABLE_BAD_IP`.
* </pre>
*
* <code>string type = 3 [(.google.api.field_behavior) = REQUIRED];</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>
* Required. The type of the module. For example, `CONFIGURABLE_BAD_IP`.
* </pre>
*
* <code>string type = 3 [(.google.api.field_behavior) = REQUIRED];</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;
}
}
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(rawText_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, rawText_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(type_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, 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(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(rawText_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, rawText_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(type_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, 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.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest)) {
return super.equals(obj);
}
com.google.cloud.securitycentermanagement.v1.ValidateEventThreatDetectionCustomModuleRequest
other =
(com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest)
obj;
if (!getParent().equals(other.getParent())) return false;
if (!getRawText().equals(other.getRawText())) return false;
if (!getType().equals(other.getType())) 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) + RAW_TEXT_FIELD_NUMBER;
hash = (53 * hash) + getRawText().hashCode();
hash = (37 * hash) + TYPE_FIELD_NUMBER;
hash = (53 * hash) + getType().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.securitycentermanagement.v1.ValidateEventThreatDetectionCustomModuleRequest
prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request message for
* [SecurityCenterManagement.ValidateEventThreatDetectionCustomModule][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ValidateEventThreatDetectionCustomModule].
* </pre>
*
* Protobuf type {@code
* google.cloud.securitycentermanagement.v1.ValidateEventThreatDetectionCustomModuleRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.securitycentermanagement.v1.ValidateEventThreatDetectionCustomModuleRequest)
com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto
.internal_static_google_cloud_securitycentermanagement_v1_ValidateEventThreatDetectionCustomModuleRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto
.internal_static_google_cloud_securitycentermanagement_v1_ValidateEventThreatDetectionCustomModuleRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest.class,
com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest.Builder.class);
}
// Construct using
// com.google.cloud.securitycentermanagement.v1.ValidateEventThreatDetectionCustomModuleRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
rawText_ = "";
type_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto
.internal_static_google_cloud_securitycentermanagement_v1_ValidateEventThreatDetectionCustomModuleRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
getDefaultInstanceForType() {
return com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
build() {
com.google.cloud.securitycentermanagement.v1.ValidateEventThreatDetectionCustomModuleRequest
result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
buildPartial() {
com.google.cloud.securitycentermanagement.v1.ValidateEventThreatDetectionCustomModuleRequest
result =
new com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.securitycentermanagement.v1.ValidateEventThreatDetectionCustomModuleRequest
result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.rawText_ = rawText_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.type_ = type_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other
instanceof
com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest) {
return mergeFrom(
(com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest)
other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.securitycentermanagement.v1.ValidateEventThreatDetectionCustomModuleRequest
other) {
if (other
== com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getRawText().isEmpty()) {
rawText_ = other.rawText_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getType().isEmpty()) {
type_ = other.type_;
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:
{
rawText_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
type_ = 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. Resource name of the parent to validate the custom modules under,
* in one of the following formats:
*
* * `organizations/{organization}/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. Resource name of the parent to validate the custom modules under,
* in one of the following formats:
*
* * `organizations/{organization}/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. Resource name of the parent to validate the custom modules under,
* in one of the following formats:
*
* * `organizations/{organization}/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. Resource name of the parent to validate the custom modules under,
* in one of the following formats:
*
* * `organizations/{organization}/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. Resource name of the parent to validate the custom modules under,
* in one of the following formats:
*
* * `organizations/{organization}/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 rawText_ = "";
/**
*
*
* <pre>
* Required. The raw text of the module's contents. Used to generate error
* messages.
* </pre>
*
* <code>string raw_text = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The rawText.
*/
public java.lang.String getRawText() {
java.lang.Object ref = rawText_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
rawText_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The raw text of the module's contents. Used to generate error
* messages.
* </pre>
*
* <code>string raw_text = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for rawText.
*/
public com.google.protobuf.ByteString getRawTextBytes() {
java.lang.Object ref = rawText_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
rawText_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The raw text of the module's contents. Used to generate error
* messages.
* </pre>
*
* <code>string raw_text = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The rawText to set.
* @return This builder for chaining.
*/
public Builder setRawText(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
rawText_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The raw text of the module's contents. Used to generate error
* messages.
* </pre>
*
* <code>string raw_text = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearRawText() {
rawText_ = getDefaultInstance().getRawText();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The raw text of the module's contents. Used to generate error
* messages.
* </pre>
*
* <code>string raw_text = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for rawText to set.
* @return This builder for chaining.
*/
public Builder setRawTextBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
rawText_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object type_ = "";
/**
*
*
* <pre>
* Required. The type of the module. For example, `CONFIGURABLE_BAD_IP`.
* </pre>
*
* <code>string type = 3 [(.google.api.field_behavior) = REQUIRED];</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>
* Required. The type of the module. For example, `CONFIGURABLE_BAD_IP`.
* </pre>
*
* <code>string type = 3 [(.google.api.field_behavior) = REQUIRED];</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>
* Required. The type of the module. For example, `CONFIGURABLE_BAD_IP`.
* </pre>
*
* <code>string type = 3 [(.google.api.field_behavior) = REQUIRED];</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_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The type of the module. For example, `CONFIGURABLE_BAD_IP`.
* </pre>
*
* <code>string type = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearType() {
type_ = getDefaultInstance().getType();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The type of the module. For example, `CONFIGURABLE_BAD_IP`.
* </pre>
*
* <code>string type = 3 [(.google.api.field_behavior) = REQUIRED];</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_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.securitycentermanagement.v1.ValidateEventThreatDetectionCustomModuleRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.securitycentermanagement.v1.ValidateEventThreatDetectionCustomModuleRequest)
private static final com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE =
new com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest();
}
public static com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ValidateEventThreatDetectionCustomModuleRequest>
PARSER =
new com.google.protobuf.AbstractParser<
ValidateEventThreatDetectionCustomModuleRequest>() {
@java.lang.Override
public ValidateEventThreatDetectionCustomModuleRequest 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<ValidateEventThreatDetectionCustomModuleRequest>
parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ValidateEventThreatDetectionCustomModuleRequest>
getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.securitycentermanagement.v1
.ValidateEventThreatDetectionCustomModuleRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
oracle/fastr | 36,673 | com.oracle.truffle.r.test.tck/src/com/oracle/truffle/r/test/tck/RTCKLanguageProvider.java | /*
* Copyright (c) 2017, 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 3 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 3 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
* 3 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.truffle.r.test.tck;
import static org.graalvm.polyglot.tck.TypeDescriptor.OBJECT;
import static org.graalvm.polyglot.tck.TypeDescriptor.array;
import static org.graalvm.polyglot.tck.TypeDescriptor.intersection;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.PolyglotException;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.SourceSection;
import org.graalvm.polyglot.Value;
import org.graalvm.polyglot.tck.InlineSnippet;
import org.graalvm.polyglot.tck.LanguageProvider;
import org.graalvm.polyglot.tck.ResultVerifier;
import org.graalvm.polyglot.tck.Snippet;
import org.graalvm.polyglot.tck.TypeDescriptor;
import org.junit.Assert;
public final class RTCKLanguageProvider implements LanguageProvider {
private static final String ID = "R";
private static final String PATTERN_VALUE_FNC = "function () {\n" +
"%s\n" +
"}";
private static final String PATTERN_BIN_OP_FNC = "function(a,b) {\n" +
"a %s b\n" +
"}";
private static final String PATTERN_PREFIX_OP_FNC = "function(a) {\n" +
"%s a\n" +
"}";
private static final String[] PATTERN_STATEMENT = {
"function() {\n" +
"r <- NULL\n" +
"%s\n" +
"r\n" +
"}",
"function(p1) {\n" +
"r <- NULL\n" +
"%s\n" +
"r\n" +
"}",
"function(p1, p2) {\n" +
"r <- NULL\n" +
"%s\n" +
"r\n" +
"}"
};
public RTCKLanguageProvider() {
}
@Override
public String getId() {
return ID;
}
@Override
public Value createIdentityFunction(Context context) {
return eval(context, "function(a) {\n" +
"a\n" +
"}\n");
}
@Override
public Snippet createIdentityFunctionSnippet(Context context) {
// TODO HOTFIX
// FastR should not converts foreign values already
// at the moment when they are passed to a function
Value value = createIdentityFunction(context);
return (Snippet.newBuilder("identity", value, TypeDescriptor.ANY).parameterTypes(TypeDescriptor.ANY).resultVerifier(new IdentityFunctionResultVerifier()).build());
}
@Override
public Collection<? extends Snippet> createValueConstructors(Context context) {
List<Snippet> vals = new ArrayList<>();
// Scalar types
vals.add(createValueConstructor(context, "1L", intersection(TypeDescriptor.NUMBER, array(TypeDescriptor.NUMBER))));
vals.add(createValueConstructor(context, "1.42", intersection(TypeDescriptor.NUMBER, array(TypeDescriptor.NUMBER))));
vals.add(createValueConstructor(context, "FALSE", intersection(TypeDescriptor.BOOLEAN, array(TypeDescriptor.BOOLEAN))));
vals.add(createValueConstructor(context, "'TEST'", intersection(TypeDescriptor.STRING, array(TypeDescriptor.STRING))));
vals.add(createValueConstructor(context, "1+1i", intersection(OBJECT, array(OBJECT))));
// TODO NULL, raw, s4, env, list, empty, ...
vals.add(createValueConstructor(context, "NULL", TypeDescriptor.NULL));
// Vectors & Lists
Snippet v = createValueConstructor(context, "c(1L:10L)", TypeDescriptor.array(TypeDescriptor.NUMBER));
vals.add(v);
v = createValueConstructor(context, "c(1:10)", TypeDescriptor.array(TypeDescriptor.NUMBER));
vals.add(v);
vals.add(createValueConstructor(context, "c(TRUE, FALSE)", TypeDescriptor.array(TypeDescriptor.BOOLEAN)));
vals.add(createValueConstructor(context, "c(1L, 'STRING')", TypeDescriptor.array(TypeDescriptor.STRING)));
// vals.add(createValueConstructor(context, "c(1L, NULL)",
// TypeDescriptor.array(TypeDescriptor.OBJECT)));
return Collections.unmodifiableList(vals);
}
@Override
public Collection<? extends Snippet> createExpressions(Context context) {
List<Snippet> ops = new ArrayList<>();
TypeDescriptor numOrBool = TypeDescriptor.union(TypeDescriptor.NUMBER, TypeDescriptor.BOOLEAN);
TypeDescriptor numOrBoolOrNull = TypeDescriptor.union(numOrBool, TypeDescriptor.NULL);
TypeDescriptor numOrBoolOrArray = TypeDescriptor.union(numOrBool, TypeDescriptor.ARRAY);
TypeDescriptor numOrBoolOrArrayPrNull = TypeDescriptor.union(numOrBoolOrArray, TypeDescriptor.NULL);
TypeDescriptor arrNumBool = TypeDescriptor.array(numOrBool);
TypeDescriptor numOrBoolOrArrNumBool = TypeDescriptor.union(numOrBool, arrNumBool);
TypeDescriptor numOrBoolOrNullOrArrNumBool = TypeDescriptor.union(numOrBoolOrNull, arrNumBool);
TypeDescriptor boolOrArrBool = TypeDescriptor.union(TypeDescriptor.BOOLEAN, TypeDescriptor.array(TypeDescriptor.BOOLEAN));
TypeDescriptor[] acceptedParameterTypes = new TypeDescriptor[]{numOrBoolOrNullOrArrNumBool, numOrBoolOrNullOrArrNumBool};
TypeDescriptor[] declaredParameterTypes = new TypeDescriptor[]{numOrBoolOrArrayPrNull, numOrBoolOrArrayPrNull};
var binaryOpsVerifier = new NonPrimitiveNumberParameterThrows(true,
RResultVerifier.newBuilder(acceptedParameterTypes, declaredParameterTypes).ignoreBigInts().primitiveAndArrayMismatchCheck().emptyArrayCheck().build());
// +
ops.add(createBinaryOperator(context, "+", numOrBoolOrArrNumBool, TypeDescriptor.ANY, TypeDescriptor.ANY, binaryOpsVerifier));
// -
ops.add(createBinaryOperator(context, "-", numOrBoolOrArrNumBool, TypeDescriptor.ANY, TypeDescriptor.ANY, binaryOpsVerifier));
// *
ops.add(createBinaryOperator(context, "*", numOrBoolOrArrNumBool, TypeDescriptor.ANY, TypeDescriptor.ANY, binaryOpsVerifier));
// /
ops.add(createBinaryOperator(context, "/", numOrBoolOrArrNumBool, TypeDescriptor.ANY, TypeDescriptor.ANY, binaryOpsVerifier));
acceptedParameterTypes = new TypeDescriptor[]{TypeDescriptor.ANY, TypeDescriptor.ANY};
// <
ops.add(createBinaryOperator(context, "<", boolOrArrBool, TypeDescriptor.ANY, TypeDescriptor.ANY,
new NonPrimitiveNumberParameterThrows(RResultVerifier.newBuilder(acceptedParameterTypes).primitiveAndArrayMismatchCheck().compareParametersCheck().build())));
// >
ops.add(createBinaryOperator(context, ">", boolOrArrBool, TypeDescriptor.ANY, TypeDescriptor.ANY,
new NonPrimitiveNumberParameterThrows(RResultVerifier.newBuilder(acceptedParameterTypes).primitiveAndArrayMismatchCheck().compareParametersCheck().build())));
// <=
ops.add(createBinaryOperator(context, "<=", boolOrArrBool, TypeDescriptor.ANY, TypeDescriptor.ANY,
new NonPrimitiveNumberParameterThrows(RResultVerifier.newBuilder(acceptedParameterTypes).primitiveAndArrayMismatchCheck().compareParametersCheck().build())));
// >=
ops.add(createBinaryOperator(context, ">=", boolOrArrBool, TypeDescriptor.ANY, TypeDescriptor.ANY,
new NonPrimitiveNumberParameterThrows(RResultVerifier.newBuilder(acceptedParameterTypes).primitiveAndArrayMismatchCheck().compareParametersCheck().build())));
// ==
ops.add(createBinaryOperator(context, "==", boolOrArrBool, TypeDescriptor.ANY, TypeDescriptor.ANY,
new NonPrimitiveNumberParameterThrows(RResultVerifier.newBuilder(acceptedParameterTypes).primitiveAndArrayMismatchCheck().compareParametersCheck().build())));
// !=
ops.add(createBinaryOperator(context, "!=", boolOrArrBool, TypeDescriptor.ANY, TypeDescriptor.ANY,
new NonPrimitiveNumberParameterThrows(RResultVerifier.newBuilder(acceptedParameterTypes).primitiveAndArrayMismatchCheck().compareParametersCheck().build())));
// // TODO &, |, &&, ||
// !
ops.add(createPrefixOperator(context, "!", boolOrArrBool, numOrBoolOrArray,
new NonPrimitiveNumberParameterThrows(RResultVerifier.newBuilder(new TypeDescriptor[]{numOrBoolOrNullOrArrNumBool},
new TypeDescriptor[]{numOrBoolOrArray}).primitiveAndArrayMismatchCheck().emptyArrayCheck().build())));
// TODO unary +, -, ...
return Collections.unmodifiableList(ops);
}
@Override
public Collection<? extends Snippet> createStatements(Context context) {
Collection<Snippet> res = new ArrayList<>();
TypeDescriptor numberOrBoolean = TypeDescriptor.union(TypeDescriptor.NUMBER, TypeDescriptor.BOOLEAN);
TypeDescriptor arrayNumberBoolean = TypeDescriptor.array(numberOrBoolean);
TypeDescriptor numOrBoolOrArray = TypeDescriptor.union(numberOrBoolean, TypeDescriptor.ARRAY);
TypeDescriptor numberOrBooleanOrArrayNumberBoolean = TypeDescriptor.union(numberOrBoolean, arrayNumberBoolean);
TypeDescriptor[] acceptedParameterTypes = new TypeDescriptor[]{numberOrBooleanOrArrayNumberBoolean};
TypeDescriptor[] declaredParameterTypes = new TypeDescriptor[]{numOrBoolOrArray};
// if
String ifStatement = "if ({1}) '{'\n{0}<-TRUE\n'}' else '{'\n{0}<-FALSE\n'}'";
res.add(createStatement(context, "if", ifStatement,
new NonPrimitiveNumberParameterThrows(
RResultVerifier.newBuilder(acceptedParameterTypes, new TypeDescriptor[]{numOrBoolOrArray}).primitiveAndArrayMismatchCheck().emptyArrayCheck().build()),
TypeDescriptor.BOOLEAN, numOrBoolOrArray));
// while
String whileStatement = "while ({1})'{'\nbreak\n'}'";
res.add(createStatement(context, "while", whileStatement,
new NonPrimitiveNumberParameterThrows(RResultVerifier.newBuilder(acceptedParameterTypes, declaredParameterTypes).primitiveAndArrayMismatchCheck().emptyArrayCheck().build()),
TypeDescriptor.NULL, numOrBoolOrArray));
// for
String forStatement = "for (val in {1}) '{'\n'}'";
res.add(createStatement(context, "for", forStatement, TypeDescriptor.NULL, TypeDescriptor.ANY));
return Collections.unmodifiableCollection(res);
}
@Override
public Collection<? extends Snippet> createScripts(Context context) {
List<Snippet> res = new ArrayList<>();
res.add(loadScript(
context,
"resources/quicksort.R",
TypeDescriptor.BOOLEAN,
(snippetRun) -> {
Assert.assertEquals(true, snippetRun.getResult().asBoolean());
}));
res.add(loadScript(
context,
"resources/mandel.R",
TypeDescriptor.NUMBER,
(snippetRun) -> {
Assert.assertEquals(14791, snippetRun.getResult().asInt());
}));
res.add(loadScript(
context,
"resources/rand_mat_mul.R",
TypeDescriptor.BOOLEAN,
(snippetRun) -> {
Assert.assertEquals(true, snippetRun.getResult().asBoolean());
}));
res.add(loadScript(
context,
"resources/rand_mat_stat.R",
TypeDescriptor.BOOLEAN,
(snippetRun) -> {
Assert.assertEquals(true, snippetRun.getResult().asBoolean());
}));
res.add(loadScript(
context,
"resources/pi_sum.R",
TypeDescriptor.BOOLEAN,
(snippetRun) -> {
Assert.assertEquals(true, snippetRun.getResult().asBoolean());
}));
res.add(loadScript(
context,
"resources/fib.R",
TypeDescriptor.NUMBER,
(snippetRun) -> {
Assert.assertEquals(6765, snippetRun.getResult().asInt());
}));
return Collections.unmodifiableList(res);
}
@Override
public Collection<? extends Source> createInvalidSyntaxScripts(Context context) {
try {
List<Source> res = new ArrayList<>();
res.add(createSource("resources/invalidSyntax01.R"));
return Collections.unmodifiableList(res);
} catch (IOException ioe) {
throw new AssertionError("IOException while creating a test script.", ioe);
}
}
@Override
public Collection<? extends InlineSnippet> createInlineScripts(Context context) {
List<InlineSnippet> res = new ArrayList<>();
res.add(createInlineSnippet(
context,
"resources/mandel.R",
25,
26,
"resources/mandel_inline1.R"));
res.add(createInlineSnippet(
context,
"resources/mandel.R",
38,
39,
"resources/mandel_inline2.R"));
res.add(createInlineSnippet(
context,
"resources/quicksort.R",
25,
41,
"resources/quicksort_inline.R"));
return Collections.unmodifiableList(res);
}
private static Snippet createValueConstructor(
Context context,
String value,
TypeDescriptor type) {
return Snippet.newBuilder(value, eval(context, String.format(PATTERN_VALUE_FNC, value)), type).build();
}
private static Snippet createBinaryOperator(
Context context,
String operator,
TypeDescriptor type,
TypeDescriptor ltype,
TypeDescriptor rtype,
ResultVerifier verifier) {
Value fnc = eval(context, String.format(PATTERN_BIN_OP_FNC, operator));
Snippet.Builder opb = Snippet.newBuilder(operator, fnc, type).parameterTypes(ltype, rtype).resultVerifier(verifier);
return opb.build();
}
private static Snippet createPrefixOperator(
Context context,
String operator,
TypeDescriptor type,
TypeDescriptor rtype,
ResultVerifier verifier) {
Value fnc = eval(context, String.format(PATTERN_PREFIX_OP_FNC, operator));
Snippet.Builder opb = Snippet.newBuilder(operator, fnc, type).parameterTypes(rtype).resultVerifier(verifier);
return opb.build();
}
private static Snippet createStatement(
Context context,
String name,
String expression,
TypeDescriptor type,
TypeDescriptor... paramTypes) {
return createStatement(context, name, expression, null, type, paramTypes);
}
private static Snippet createStatement(
Context context,
String name,
String expression,
ResultVerifier verifier,
TypeDescriptor type,
TypeDescriptor... paramTypes) {
String fncFormat = PATTERN_STATEMENT[paramTypes.length];
Object[] formalParams = new String[paramTypes.length + 1];
formalParams[0] = "r";
for (int i = 1; i < formalParams.length; i++) {
formalParams[i] = "p" + i;
}
String exprWithFormalParams = MessageFormat.format(expression, formalParams);
Value fnc = eval(context, String.format(fncFormat, exprWithFormalParams));
Snippet.Builder opb = Snippet.newBuilder(name, fnc, type).parameterTypes(paramTypes).resultVerifier(verifier);
return opb.build();
}
private static InlineSnippet createInlineSnippet(Context context, String sourceName, int l1, int l2, String snippetName) {
Snippet script = loadScript(context, sourceName, TypeDescriptor.ANY, null);
String simpleName = sourceName.substring(sourceName.lastIndexOf('/') + 1);
try {
InlineSnippet.Builder snippetBuilder = InlineSnippet.newBuilder(script, createSource(snippetName).getCharacters());
if (l1 > 0) {
Predicate<SourceSection> locationPredicate = (SourceSection ss) -> {
return ss.getSource().getName().endsWith(simpleName) && l1 <= ss.getStartLine() && ss.getEndLine() <= l2;
};
snippetBuilder.locationPredicate(locationPredicate);
}
snippetBuilder.resultVerifier((ResultVerifier.SnippetRun snippetRun) -> {
PolyglotException exception = snippetRun.getException();
if (exception != null) {
throw exception;
}
Value result = snippetRun.getResult();
if (!result.isNumber()) {
throw new AssertionError("Wrong value " + result.toString() + " from " + sourceName);
}
});
return snippetBuilder.build();
} catch (IOException ioe) {
throw new AssertionError("IOException while creating a test script.", ioe);
}
}
private static Snippet loadScript(
Context context,
String resourceName,
TypeDescriptor type,
ResultVerifier verifier) {
try {
Source src = createSource(resourceName);
return Snippet.newBuilder(src.getName(), context.eval(src), type).resultVerifier(verifier).build();
} catch (IOException ioe) {
throw new AssertionError("IOException while creating a test script.", ioe);
}
}
private static Source createSource(String resourceName) throws IOException {
int slashIndex = resourceName.lastIndexOf('/');
String scriptName = slashIndex >= 0 ? resourceName.substring(slashIndex + 1) : resourceName;
Reader in = new InputStreamReader(RTCKLanguageProvider.class.getResourceAsStream(resourceName), "UTF-8");
return Source.newBuilder(ID, in, scriptName).build();
}
private static Value eval(Context context, String statement) {
return context.eval(ID, statement);
}
final class IdentityFunctionResultVerifier implements ResultVerifier {
ResultVerifier delegate = ResultVerifier.getIdentityFunctionDefaultResultVerifier();
private IdentityFunctionResultVerifier() {
}
@Override
public void accept(SnippetRun snippetRun) throws PolyglotException {
// We ignore objects that FastR automatically unboxes to an R vector on the boundary,
// but they happen to have some more extra traits that the TCK would than check
// on the result and fail
for (Value p : snippetRun.getParameters()) {
if (isUnboxable(p) && hasExtraTrait(p)) {
return;
}
}
delegate.accept(snippetRun);
}
public static boolean hasExtraTrait(Value value) {
return value.hasMembers() || value.hasIterator() || value.canExecute() || value.hasArrayElements() ||
value.hasHashEntries() || value.hasBufferElements() || value.isMetaObject() ||
value.isDate() || value.isDuration() || value.isException() || value.isInstant() ||
value.isNativePointer() || value.isProxyObject() || value.isTime() || value.isTimeZone();
}
public static boolean isUnboxable(Value value) {
return value.isBoolean() || value.isString() || value.fitsInByte() || value.fitsInShort() ||
value.fitsInInt() || value.fitsInLong() || value.fitsInFloat() || value.fitsInDouble() ||
value.isNull();
}
}
private static class NonPrimitiveNumberParameterThrows implements ResultVerifier {
private final boolean stringOrObjectParameterForbidden;
private final ResultVerifier next;
NonPrimitiveNumberParameterThrows(ResultVerifier next) {
this(false, next);
}
NonPrimitiveNumberParameterThrows(boolean stringOrObjectParameterForbidden, ResultVerifier next) {
this.next = next != null ? next : ResultVerifier.getDefaultResultVerifier();
this.stringOrObjectParameterForbidden = stringOrObjectParameterForbidden;
}
@Override
public void accept(ResultVerifier.SnippetRun snippetRun) throws PolyglotException {
boolean stringOrObjectParameter = false;
boolean nonPrimitiveNumberParameter = false;
boolean nonPrimitiveNumberParameterWrappedInArray = false;
boolean numberOrBooleanParameters = true;
boolean numberOrBooleanOrStringParameters = true;
for (Value actualParameter : snippetRun.getParameters()) {
Value parameterToCheck = actualParameter;
if (actualParameter.hasArrayElements() && actualParameter.getArraySize() > 0) {
parameterToCheck = actualParameter.getArrayElement(0);
}
if (!parameterToCheck.isBoolean() && !parameterToCheck.isNumber()) {
numberOrBooleanParameters = false;
if (!parameterToCheck.isString()) {
numberOrBooleanOrStringParameters = false;
}
}
if (parameterToCheck.isNumber() && !parameterToCheck.fitsInLong() && !parameterToCheck.fitsInDouble()) {
nonPrimitiveNumberParameter = true;
if (actualParameter != parameterToCheck) {
nonPrimitiveNumberParameterWrappedInArray = true;
}
}
if (parameterToCheck.isString() || (!parameterToCheck.isNumber() && !parameterToCheck.isBoolean() && !parameterToCheck.isString() && !parameterToCheck.isNull() &&
!(parameterToCheck.hasMember("re") && parameterToCheck.hasMember("im")))) {
stringOrObjectParameter = true;
}
}
if ((numberOrBooleanParameters && nonPrimitiveNumberParameter) ||
(numberOrBooleanOrStringParameters && !numberOrBooleanParameters && nonPrimitiveNumberParameter && !nonPrimitiveNumberParameterWrappedInArray) ||
(stringOrObjectParameter && stringOrObjectParameterForbidden)) {
if (snippetRun.getException() == null) {
throw new AssertionError("TypeError expected but no error has been thrown.");
} // else exception expected => ignore
} else {
next.accept(snippetRun); // no exception expected
}
}
}
private static final class RResultVerifier implements ResultVerifier {
/**
* Declared is a superset of accepted; If a parameter is an object array, we declare it as
* such, but a conversion to a fastr vector accepts it only of it contains homogenous values
* of some specific type - e.g. new Object[] {Integer, Integer}
*
*/
private TypeDescriptor[] declaredParameterTypes;
private TypeDescriptor[] acceptedParameterTypes;
BiFunction<Boolean, SnippetRun, Void> next;
private RResultVerifier(
TypeDescriptor[] acceptedParameterTypes,
TypeDescriptor[] declaredParameterTypes,
BiFunction<Boolean, SnippetRun, Void> next) {
this.acceptedParameterTypes = Objects.requireNonNull(acceptedParameterTypes, "The acceptedParameterTypes cannot be null.");
this.declaredParameterTypes = declaredParameterTypes;
this.next = Objects.requireNonNull(next, "The verifier chain cannot be null.");
}
@Override
public void accept(SnippetRun snippetRun) throws PolyglotException {
boolean hasValidArgumentTypes = isAssignable(acceptedParameterTypes, snippetRun.getParameters());
List<? extends Value> args = snippetRun.getParameters();
boolean hasValidDeclaredTypes = isAssignable(declaredParameterTypes, args);
if (hasValidDeclaredTypes) {
if (hasValidArgumentTypes) {
next.apply(hasValidArgumentTypes, snippetRun);
}
} else {
next.apply(hasValidArgumentTypes, snippetRun);
}
}
private static boolean isAssignable(TypeDescriptor[] types, List<? extends Value> args) {
if (types == null) {
return false;
}
for (int i = 0; i < types.length; i++) {
if (!types[i].isAssignable(TypeDescriptor.forValue(args.get(i)))) {
return false;
}
}
return true;
}
static Builder newBuilder(TypeDescriptor[] acceptedParameterTypes) {
return new Builder(acceptedParameterTypes, null);
}
static Builder newBuilder(TypeDescriptor[] acceptedParameterTypes, TypeDescriptor[] declaredParameterTypes) {
return new Builder(acceptedParameterTypes, declaredParameterTypes);
}
static final class Builder {
private final TypeDescriptor[] acceptedParameterTypes;
private final TypeDescriptor[] declaredParameterTypes;
private BiFunction<Boolean, SnippetRun, Void> chain;
private Builder(TypeDescriptor[] acceptedParameterTypes, TypeDescriptor[] declaredParameterTypes) {
this.acceptedParameterTypes = acceptedParameterTypes;
this.declaredParameterTypes = declaredParameterTypes;
chain = (valid, snippetRun) -> {
ResultVerifier.getDefaultResultVerifier().accept(snippetRun);
return null;
};
}
/**
* Enables result verifier to handle empty arrays. Use this for R expressions,
* statements which accept array but not an empty array
*
* @return the Builder
*/
Builder emptyArrayCheck() {
chain = new BiFunction<>() {
private final BiFunction<Boolean, SnippetRun, Void> next = chain;
@Override
public Void apply(Boolean valid, SnippetRun sr) {
if (valid && sr.getException() != null && hasEmptyArrayArg(sr.getParameters())) {
return null;
}
return next.apply(valid, sr);
}
private boolean hasEmptyArrayArg(List<? extends Value> args) {
for (Value arg : args) {
if (arg.hasArrayElements() && arg.getArraySize() == 0) {
return true;
}
}
return false;
}
};
return this;
}
/**
* Ignores errors from interop values that unbox to a different type than what is their
* array type from FastR default conversions point of view. Example: object that
* {@code isString}, but its array elements are bytes. Another example: object that
* looks like integer, but is also an integer array of size > 1.
*
* @return the Builder
*/
Builder primitiveAndArrayMismatchCheck() {
chain = new BiFunction<>() {
private final BiFunction<Boolean, SnippetRun, Void> next = chain;
@Override
public Void apply(Boolean valid, SnippetRun sr) {
if (valid && sr.getException() != null && hasMismatchingArgs(sr.getParameters())) {
return null;
}
return next.apply(valid, sr);
}
private boolean hasMismatchingArgs(List<? extends Value> args) {
for (Value arg : args) {
if (checkPrimitive(arg, Value::isString) ||
checkPrimitive(arg, Value::fitsInByte) ||
checkPrimitive(arg, Value::fitsInShort) ||
checkPrimitive(arg, Value::fitsInInt) ||
checkPrimitive(arg, Value::fitsInLong) ||
checkPrimitive(arg, Value::fitsInDouble) ||
checkPrimitive(arg, Value::fitsInFloat)) {
return true;
}
}
return false;
}
private boolean checkPrimitive(Value arg, Function<Value, Boolean> fitsIn) {
return fitsIn.apply(arg) && arg.hasArrayElements() && (arg.getArraySize() != 1 || !fitsIn.apply(arg.getArrayElement(0)));
}
};
return this;
}
/**
* Ignores the result if the snippet contains pure big integers, i.e., numbers larger
* than max long.
*/
Builder ignoreBigInts() {
chain = new BiFunction<>() {
private final BiFunction<Boolean, SnippetRun, Void> next = chain;
@Override
public Void apply(Boolean valid, SnippetRun sr) {
if (valid && sr.getException() != null && hasBigInt(sr.getParameters())) {
return null;
}
return next.apply(valid, sr);
}
private boolean hasBigInt(List<? extends Value> args) {
for (Value arg : args) {
if (arg.fitsInBigInteger() && !arg.fitsInLong()) {
return true;
}
}
return false;
}
};
return this;
}
// - not empty homogenous number, boolean or string arrays -> vector
// - any other array -> list
//
// comparing:
// - null with anything does not fail - logical(0)
// - empty list or vector with anything does not fail - logical(0)
// - atomic vectors does not fail
// - a list with an atomic vector does not fail
// - a list with another list FAILS
// - other kind of object with anything but null or empty list or vector FAILS
Builder compareParametersCheck() {
chain = new BiFunction<>() {
private final BiFunction<Boolean, SnippetRun, Void> next = chain;
@Override
public Void apply(Boolean valid, SnippetRun sr) {
if (valid && sr.getException() != null && expectsException(sr.getParameters())) {
return null;
}
return next.apply(valid, sr);
}
private boolean expectsException(List<? extends Value> args) {
boolean parametersValid = false;
int mixed = 0;
for (Value arg : args) {
parametersValid = false;
if (arg.isNull()) {
// one of the given parameters is NULL
// this is never expected to fail
return false;
}
if (arg.isNumber() || arg.isString() || arg.isBoolean()) {
parametersValid = true;
} else if (arg.hasArrayElements()) {
if (arg.getArraySize() == 0) {
// one of the given parameters is an emtpy list or vector,
// this is never expected to fail
return false;
} else {
boolean str = false;
boolean num = false;
boolean other = false;
for (int i = 0; i < arg.getArraySize(); i++) {
TypeDescriptor td = TypeDescriptor.forValue(arg.getArrayElement(i));
if (TypeDescriptor.STRING.isAssignable(td)) {
str = true;
} else if (TypeDescriptor.NUMBER.isAssignable(td) || TypeDescriptor.BOOLEAN.isAssignable(td)) {
num = true;
} else {
other = true;
}
}
parametersValid = !other;
if (str && num) {
mixed++;
}
}
}
if (!parametersValid) {
break;
}
}
return !(parametersValid && mixed < args.size());
}
};
return this;
}
RResultVerifier build() {
return new RResultVerifier(acceptedParameterTypes, declaredParameterTypes, chain);
}
}
}
}
|
googleapis/google-cloud-java | 36,504 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/ListOptimalTrialsResponse.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/vizier_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1;
/**
*
*
* <pre>
* Response message for
* [VizierService.ListOptimalTrials][google.cloud.aiplatform.v1beta1.VizierService.ListOptimalTrials].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse}
*/
public final class ListOptimalTrialsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse)
ListOptimalTrialsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListOptimalTrialsResponse.newBuilder() to construct.
private ListOptimalTrialsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListOptimalTrialsResponse() {
optimalTrials_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListOptimalTrialsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.VizierServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListOptimalTrialsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.VizierServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListOptimalTrialsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse.class,
com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse.Builder.class);
}
public static final int OPTIMAL_TRIALS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.aiplatform.v1beta1.Trial> optimalTrials_;
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.aiplatform.v1beta1.Trial> getOptimalTrialsList() {
return optimalTrials_;
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.TrialOrBuilder>
getOptimalTrialsOrBuilderList() {
return optimalTrials_;
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
@java.lang.Override
public int getOptimalTrialsCount() {
return optimalTrials_.size();
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.Trial getOptimalTrials(int index) {
return optimalTrials_.get(index);
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.TrialOrBuilder getOptimalTrialsOrBuilder(int index) {
return optimalTrials_.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 < optimalTrials_.size(); i++) {
output.writeMessage(1, optimalTrials_.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 < optimalTrials_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, optimalTrials_.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.aiplatform.v1beta1.ListOptimalTrialsResponse)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse other =
(com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse) obj;
if (!getOptimalTrialsList().equals(other.getOptimalTrialsList())) 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 (getOptimalTrialsCount() > 0) {
hash = (37 * hash) + OPTIMAL_TRIALS_FIELD_NUMBER;
hash = (53 * hash) + getOptimalTrialsList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse 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.ListOptimalTrialsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse 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.ListOptimalTrialsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse 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.ListOptimalTrialsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse 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.ListOptimalTrialsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse 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.ListOptimalTrialsResponse 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.ListOptimalTrialsResponse 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.ListOptimalTrialsResponse 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
* [VizierService.ListOptimalTrials][google.cloud.aiplatform.v1beta1.VizierService.ListOptimalTrials].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse)
com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.VizierServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListOptimalTrialsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.VizierServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListOptimalTrialsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse.class,
com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (optimalTrialsBuilder_ == null) {
optimalTrials_ = java.util.Collections.emptyList();
} else {
optimalTrials_ = null;
optimalTrialsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1beta1.VizierServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListOptimalTrialsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse build() {
com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse buildPartial() {
com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse result =
new com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse result) {
if (optimalTrialsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
optimalTrials_ = java.util.Collections.unmodifiableList(optimalTrials_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.optimalTrials_ = optimalTrials_;
} else {
result.optimalTrials_ = optimalTrialsBuilder_.build();
}
}
private void buildPartial0(
com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse 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.aiplatform.v1beta1.ListOptimalTrialsResponse) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse other) {
if (other
== com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse.getDefaultInstance())
return this;
if (optimalTrialsBuilder_ == null) {
if (!other.optimalTrials_.isEmpty()) {
if (optimalTrials_.isEmpty()) {
optimalTrials_ = other.optimalTrials_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureOptimalTrialsIsMutable();
optimalTrials_.addAll(other.optimalTrials_);
}
onChanged();
}
} else {
if (!other.optimalTrials_.isEmpty()) {
if (optimalTrialsBuilder_.isEmpty()) {
optimalTrialsBuilder_.dispose();
optimalTrialsBuilder_ = null;
optimalTrials_ = other.optimalTrials_;
bitField0_ = (bitField0_ & ~0x00000001);
optimalTrialsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getOptimalTrialsFieldBuilder()
: null;
} else {
optimalTrialsBuilder_.addAllMessages(other.optimalTrials_);
}
}
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.aiplatform.v1beta1.Trial m =
input.readMessage(
com.google.cloud.aiplatform.v1beta1.Trial.parser(), extensionRegistry);
if (optimalTrialsBuilder_ == null) {
ensureOptimalTrialsIsMutable();
optimalTrials_.add(m);
} else {
optimalTrialsBuilder_.addMessage(m);
}
break;
} // case 10
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.aiplatform.v1beta1.Trial> optimalTrials_ =
java.util.Collections.emptyList();
private void ensureOptimalTrialsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
optimalTrials_ =
new java.util.ArrayList<com.google.cloud.aiplatform.v1beta1.Trial>(optimalTrials_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Trial,
com.google.cloud.aiplatform.v1beta1.Trial.Builder,
com.google.cloud.aiplatform.v1beta1.TrialOrBuilder>
optimalTrialsBuilder_;
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.Trial> getOptimalTrialsList() {
if (optimalTrialsBuilder_ == null) {
return java.util.Collections.unmodifiableList(optimalTrials_);
} else {
return optimalTrialsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public int getOptimalTrialsCount() {
if (optimalTrialsBuilder_ == null) {
return optimalTrials_.size();
} else {
return optimalTrialsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Trial getOptimalTrials(int index) {
if (optimalTrialsBuilder_ == null) {
return optimalTrials_.get(index);
} else {
return optimalTrialsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public Builder setOptimalTrials(int index, com.google.cloud.aiplatform.v1beta1.Trial value) {
if (optimalTrialsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureOptimalTrialsIsMutable();
optimalTrials_.set(index, value);
onChanged();
} else {
optimalTrialsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public Builder setOptimalTrials(
int index, com.google.cloud.aiplatform.v1beta1.Trial.Builder builderForValue) {
if (optimalTrialsBuilder_ == null) {
ensureOptimalTrialsIsMutable();
optimalTrials_.set(index, builderForValue.build());
onChanged();
} else {
optimalTrialsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public Builder addOptimalTrials(com.google.cloud.aiplatform.v1beta1.Trial value) {
if (optimalTrialsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureOptimalTrialsIsMutable();
optimalTrials_.add(value);
onChanged();
} else {
optimalTrialsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public Builder addOptimalTrials(int index, com.google.cloud.aiplatform.v1beta1.Trial value) {
if (optimalTrialsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureOptimalTrialsIsMutable();
optimalTrials_.add(index, value);
onChanged();
} else {
optimalTrialsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public Builder addOptimalTrials(
com.google.cloud.aiplatform.v1beta1.Trial.Builder builderForValue) {
if (optimalTrialsBuilder_ == null) {
ensureOptimalTrialsIsMutable();
optimalTrials_.add(builderForValue.build());
onChanged();
} else {
optimalTrialsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public Builder addOptimalTrials(
int index, com.google.cloud.aiplatform.v1beta1.Trial.Builder builderForValue) {
if (optimalTrialsBuilder_ == null) {
ensureOptimalTrialsIsMutable();
optimalTrials_.add(index, builderForValue.build());
onChanged();
} else {
optimalTrialsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public Builder addAllOptimalTrials(
java.lang.Iterable<? extends com.google.cloud.aiplatform.v1beta1.Trial> values) {
if (optimalTrialsBuilder_ == null) {
ensureOptimalTrialsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, optimalTrials_);
onChanged();
} else {
optimalTrialsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public Builder clearOptimalTrials() {
if (optimalTrialsBuilder_ == null) {
optimalTrials_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
optimalTrialsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public Builder removeOptimalTrials(int index) {
if (optimalTrialsBuilder_ == null) {
ensureOptimalTrialsIsMutable();
optimalTrials_.remove(index);
onChanged();
} else {
optimalTrialsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Trial.Builder getOptimalTrialsBuilder(int index) {
return getOptimalTrialsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.TrialOrBuilder getOptimalTrialsOrBuilder(int index) {
if (optimalTrialsBuilder_ == null) {
return optimalTrials_.get(index);
} else {
return optimalTrialsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.TrialOrBuilder>
getOptimalTrialsOrBuilderList() {
if (optimalTrialsBuilder_ != null) {
return optimalTrialsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(optimalTrials_);
}
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Trial.Builder addOptimalTrialsBuilder() {
return getOptimalTrialsFieldBuilder()
.addBuilder(com.google.cloud.aiplatform.v1beta1.Trial.getDefaultInstance());
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Trial.Builder addOptimalTrialsBuilder(int index) {
return getOptimalTrialsFieldBuilder()
.addBuilder(index, com.google.cloud.aiplatform.v1beta1.Trial.getDefaultInstance());
}
/**
*
*
* <pre>
* The pareto-optimal Trials for multiple objective Study or the
* optimal trial for single objective Study. The definition of
* pareto-optimal can be checked in wiki page.
* https://en.wikipedia.org/wiki/Pareto_efficiency
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Trial optimal_trials = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.Trial.Builder>
getOptimalTrialsBuilderList() {
return getOptimalTrialsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Trial,
com.google.cloud.aiplatform.v1beta1.Trial.Builder,
com.google.cloud.aiplatform.v1beta1.TrialOrBuilder>
getOptimalTrialsFieldBuilder() {
if (optimalTrialsBuilder_ == null) {
optimalTrialsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Trial,
com.google.cloud.aiplatform.v1beta1.Trial.Builder,
com.google.cloud.aiplatform.v1beta1.TrialOrBuilder>(
optimalTrials_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
optimalTrials_ = null;
}
return optimalTrialsBuilder_;
}
@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.ListOptimalTrialsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse)
private static final com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse();
}
public static com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListOptimalTrialsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListOptimalTrialsResponse>() {
@java.lang.Override
public ListOptimalTrialsResponse 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<ListOptimalTrialsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListOptimalTrialsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListOptimalTrialsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
google/nomulus | 36,855 | core/src/main/java/google/registry/flows/domain/DomainCreateFlow.java | // Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.flows.domain;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static google.registry.dns.DnsUtils.requestDomainDnsRefresh;
import static google.registry.flows.FlowUtils.persistEntityChanges;
import static google.registry.flows.FlowUtils.validateRegistrarIsLoggedIn;
import static google.registry.flows.domain.DomainFlowUtils.COLLISION_MESSAGE;
import static google.registry.flows.domain.DomainFlowUtils.checkAllowedAccessToTld;
import static google.registry.flows.domain.DomainFlowUtils.checkHasBillingAccount;
import static google.registry.flows.domain.DomainFlowUtils.cloneAndLinkReferences;
import static google.registry.flows.domain.DomainFlowUtils.createFeeCreateResponse;
import static google.registry.flows.domain.DomainFlowUtils.getReservationTypes;
import static google.registry.flows.domain.DomainFlowUtils.isAnchorTenant;
import static google.registry.flows.domain.DomainFlowUtils.isReserved;
import static google.registry.flows.domain.DomainFlowUtils.isValidReservedCreate;
import static google.registry.flows.domain.DomainFlowUtils.validateCreateCommandContactsAndNameservers;
import static google.registry.flows.domain.DomainFlowUtils.validateDomainName;
import static google.registry.flows.domain.DomainFlowUtils.validateDomainNameWithIdnTables;
import static google.registry.flows.domain.DomainFlowUtils.validateFeeChallenge;
import static google.registry.flows.domain.DomainFlowUtils.validateLaunchCreateNotice;
import static google.registry.flows.domain.DomainFlowUtils.validateRegistrationPeriod;
import static google.registry.flows.domain.DomainFlowUtils.validateSecDnsExtension;
import static google.registry.flows.domain.DomainFlowUtils.verifyClaimsNoticeIfAndOnlyIfNeeded;
import static google.registry.flows.domain.DomainFlowUtils.verifyClaimsPeriodNotEnded;
import static google.registry.flows.domain.DomainFlowUtils.verifyLaunchPhaseMatchesRegistryPhase;
import static google.registry.flows.domain.DomainFlowUtils.verifyNoCodeMarks;
import static google.registry.flows.domain.DomainFlowUtils.verifyNotBlockedByBsa;
import static google.registry.flows.domain.DomainFlowUtils.verifyNotReserved;
import static google.registry.flows.domain.DomainFlowUtils.verifyPremiumNameIsNotBlocked;
import static google.registry.flows.domain.DomainFlowUtils.verifyRegistrarIsActive;
import static google.registry.flows.domain.DomainFlowUtils.verifyUnitIsYears;
import static google.registry.model.EppResourceUtils.createDomainRepoId;
import static google.registry.model.eppcommon.StatusValue.SERVER_HOLD;
import static google.registry.model.reporting.HistoryEntry.Type.DOMAIN_CREATE;
import static google.registry.model.tld.Tld.TldState.GENERAL_AVAILABILITY;
import static google.registry.model.tld.Tld.TldState.QUIET_PERIOD;
import static google.registry.model.tld.Tld.TldState.START_DATE_SUNRISE;
import static google.registry.model.tld.label.ReservationType.NAME_COLLISION;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.leapSafeAddYears;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.net.InternetDomainName;
import google.registry.config.RegistryConfig;
import google.registry.flows.EppException;
import google.registry.flows.EppException.CommandUseErrorException;
import google.registry.flows.EppException.ParameterValuePolicyErrorException;
import google.registry.flows.ExtensionManager;
import google.registry.flows.FlowModule.RegistrarId;
import google.registry.flows.FlowModule.Superuser;
import google.registry.flows.FlowModule.TargetId;
import google.registry.flows.MutatingFlow;
import google.registry.flows.annotations.ReportingSpec;
import google.registry.flows.custom.DomainCreateFlowCustomLogic;
import google.registry.flows.custom.DomainCreateFlowCustomLogic.BeforeResponseParameters;
import google.registry.flows.custom.DomainCreateFlowCustomLogic.BeforeResponseReturnData;
import google.registry.flows.custom.EntityChanges;
import google.registry.flows.domain.DomainFlowUtils.RegistrantProhibitedException;
import google.registry.flows.domain.token.AllocationTokenFlowUtils;
import google.registry.flows.exceptions.ContactsProhibitedException;
import google.registry.flows.exceptions.ResourceAlreadyExistsForThisClientException;
import google.registry.flows.exceptions.ResourceCreateContentionException;
import google.registry.model.ImmutableObject;
import google.registry.model.billing.BillingBase.Flag;
import google.registry.model.billing.BillingBase.Reason;
import google.registry.model.billing.BillingBase.RenewalPriceBehavior;
import google.registry.model.billing.BillingEvent;
import google.registry.model.billing.BillingRecurrence;
import google.registry.model.domain.Domain;
import google.registry.model.domain.DomainCommand;
import google.registry.model.domain.DomainCommand.Create;
import google.registry.model.domain.DomainHistory;
import google.registry.model.domain.GracePeriod;
import google.registry.model.domain.Period;
import google.registry.model.domain.fee.FeeCreateCommandExtension;
import google.registry.model.domain.fee.FeeQueryCommandExtensionItem.CommandName;
import google.registry.model.domain.fee.FeeTransformResponseExtension;
import google.registry.model.domain.launch.LaunchCreateExtension;
import google.registry.model.domain.metadata.MetadataExtension;
import google.registry.model.domain.rgp.GracePeriodStatus;
import google.registry.model.domain.secdns.SecDnsCreateExtension;
import google.registry.model.domain.token.AllocationToken;
import google.registry.model.domain.token.AllocationToken.RegistrationBehavior;
import google.registry.model.domain.token.AllocationToken.TokenType;
import google.registry.model.domain.token.AllocationTokenExtension;
import google.registry.model.eppcommon.StatusValue;
import google.registry.model.eppinput.EppInput;
import google.registry.model.eppinput.ResourceCommand;
import google.registry.model.eppoutput.CreateData.DomainCreateData;
import google.registry.model.eppoutput.EppResponse;
import google.registry.model.poll.PendingActionNotificationResponse.DomainPendingActionNotificationResponse;
import google.registry.model.poll.PollMessage;
import google.registry.model.poll.PollMessage.Autorenew;
import google.registry.model.reporting.DomainTransactionRecord;
import google.registry.model.reporting.DomainTransactionRecord.TransactionReportField;
import google.registry.model.reporting.HistoryEntry;
import google.registry.model.reporting.HistoryEntry.HistoryEntryId;
import google.registry.model.reporting.IcannReportingTypes.ActivityReportField;
import google.registry.model.tld.Tld;
import google.registry.model.tld.Tld.TldState;
import google.registry.model.tld.Tld.TldType;
import google.registry.model.tld.label.ReservationType;
import google.registry.model.tmch.ClaimsList;
import google.registry.model.tmch.ClaimsListDao;
import google.registry.tmch.LordnTaskUtils.LordnPhase;
import jakarta.inject.Inject;
import java.util.Optional;
import org.joda.time.DateTime;
import org.joda.time.Duration;
/**
* An EPP flow that creates a new domain resource.
*
* @error {@link
* google.registry.flows.domain.token.AllocationTokenFlowUtils.AllocationTokenNotInPromotionException}
* @error {@link
* google.registry.flows.domain.token.AllocationTokenFlowUtils.AllocationTokenNotValidForDomainException}
* @error {@link
* google.registry.flows.domain.token.AllocationTokenFlowUtils.AllocationTokenNotValidForRegistrarException}
* @error {@link
* google.registry.flows.domain.token.AllocationTokenFlowUtils.AlreadyRedeemedAllocationTokenException}
* @error {@link AllocationTokenFlowUtils.NonexistentAllocationTokenException}
* @error {@link google.registry.flows.exceptions.OnlyToolCanPassMetadataException}
* @error {@link ResourceAlreadyExistsForThisClientException}
* @error {@link ResourceCreateContentionException}
* @error {@link google.registry.flows.EppException.UnimplementedExtensionException}
* @error {@link google.registry.flows.ExtensionManager.UndeclaredServiceExtensionException}
* @error {@link google.registry.flows.FlowUtils.NotLoggedInException}
* @error {@link google.registry.flows.FlowUtils.UnknownCurrencyEppException}
* @error {@link DomainCreateFlow.AnchorTenantCreatePeriodException}
* @error {@link DomainCreateFlow.MustHaveSignedMarksInCurrentPhaseException}
* @error {@link DomainCreateFlow.NoGeneralRegistrationsInCurrentPhaseException}
* @error {@link DomainCreateFlow.NoTrademarkedRegistrationsBeforeSunriseException}
* @error {@link BulkDomainRegisteredForTooManyYearsException}
* @error {@link ContactsProhibitedException}
* @error {@link DomainCreateFlow.SignedMarksOnlyDuringSunriseException}
* @error {@link DomainFlowTmchUtils.NoMarksFoundMatchingDomainException}
* @error {@link DomainFlowTmchUtils.FoundMarkNotYetValidException}
* @error {@link DomainFlowTmchUtils.FoundMarkExpiredException}
* @error {@link DomainFlowTmchUtils.SignedMarkRevokedErrorException}
* @error {@link DomainFlowUtils.NotAuthorizedForTldException}
* @error {@link DomainFlowUtils.AcceptedTooLongAgoException}
* @error {@link DomainFlowUtils.BadDomainNameCharacterException}
* @error {@link DomainFlowUtils.BadDomainNamePartsCountException}
* @error {@link DomainFlowUtils.DomainNameExistsAsTldException}
* @error {@link DomainFlowUtils.BadPeriodUnitException}
* @error {@link DomainFlowUtils.ClaimsPeriodEndedException}
* @error {@link DomainFlowUtils.CurrencyUnitMismatchException}
* @error {@link DomainFlowUtils.CurrencyValueScaleException}
* @error {@link DomainFlowUtils.DashesInThirdAndFourthException}
* @error {@link DomainFlowUtils.DomainLabelBlockedByBsaException}
* @error {@link DomainFlowUtils.DomainLabelTooLongException}
* @error {@link DomainFlowUtils.DomainReservedException}
* @error {@link DomainFlowUtils.DuplicateContactForRoleException}
* @error {@link DomainFlowUtils.EmptyDomainNamePartException}
* @error {@link DomainFlowUtils.ExceedsMaxRegistrationYearsException}
* @error {@link DomainFlowUtils.ExpiredClaimException}
* @error {@link DomainFlowUtils.FeeDescriptionMultipleMatchesException}
* @error {@link DomainFlowUtils.FeeDescriptionParseException}
* @error {@link DomainFlowUtils.FeesMismatchException}
* @error {@link DomainFlowUtils.FeesRequiredDuringEarlyAccessProgramException}
* @error {@link DomainFlowUtils.FeesRequiredForPremiumNameException}
* @error {@link DomainFlowUtils.InvalidDsRecordException}
* @error {@link DomainFlowUtils.InvalidIdnDomainLabelException}
* @error {@link DomainFlowUtils.InvalidPunycodeException}
* @error {@link DomainFlowUtils.InvalidTcnIdChecksumException}
* @error {@link DomainFlowUtils.InvalidTrademarkValidatorException}
* @error {@link DomainFlowUtils.LeadingDashException}
* @error {@link DomainFlowUtils.LinkedResourcesDoNotExistException}
* @error {@link DomainFlowUtils.LinkedResourceInPendingDeleteProhibitsOperationException}
* @error {@link DomainFlowUtils.MalformedTcnIdException}
* @error {@link DomainFlowUtils.MaxSigLifeNotSupportedException}
* @error {@link DomainFlowUtils.MissingAdminContactException}
* @error {@link DomainFlowUtils.MissingBillingAccountMapException}
* @error {@link DomainFlowUtils.MissingClaimsNoticeException}
* @error {@link DomainFlowUtils.MissingContactTypeException}
* @error {@link DomainFlowUtils.MissingRegistrantException}
* @error {@link DomainFlowUtils.MissingTechnicalContactException}
* @error {@link DomainFlowUtils.NameserversNotAllowedForTldException}
* @error {@link DomainFlowUtils.NameserversNotSpecifiedForTldWithNameserverAllowListException}
* @error {@link DomainFlowUtils.PremiumNameBlockedException}
* @error {@link DomainFlowUtils.RegistrantNotAllowedException}
* @error {@link RegistrantProhibitedException}
* @error {@link DomainFlowUtils.RegistrarMustBeActiveForThisOperationException}
* @error {@link DomainFlowUtils.TldDoesNotExistException}
* @error {@link DomainFlowUtils.TooManyDsRecordsException}
* @error {@link DomainFlowUtils.TooManyNameserversException}
* @error {@link DomainFlowUtils.TrailingDashException}
* @error {@link DomainFlowUtils.UnexpectedClaimsNoticeException}
* @error {@link DomainFlowUtils.UnsupportedFeeAttributeException}
* @error {@link DomainFlowUtils.UnsupportedMarkTypeException}
*/
@ReportingSpec(ActivityReportField.DOMAIN_CREATE)
public final class DomainCreateFlow implements MutatingFlow {
/** Anchor tenant creates should always be for 2 years, since they get 2 years free. */
private static final int ANCHOR_TENANT_CREATE_VALID_YEARS = 2;
@Inject ExtensionManager extensionManager;
@Inject EppInput eppInput;
@Inject ResourceCommand resourceCommand;
@Inject @RegistrarId String registrarId;
@Inject @TargetId String targetId;
@Inject @Superuser boolean isSuperuser;
@Inject DomainHistory.Builder historyBuilder;
@Inject EppResponse.Builder responseBuilder;
@Inject DomainCreateFlowCustomLogic flowCustomLogic;
@Inject DomainFlowTmchUtils tmchUtils;
@Inject DomainPricingLogic pricingLogic;
@Inject DomainDeletionTimeCache domainDeletionTimeCache;
@Inject DomainCreateFlow() {}
@Override
public EppResponse run() throws EppException {
extensionManager.register(
FeeCreateCommandExtension.class,
SecDnsCreateExtension.class,
MetadataExtension.class,
LaunchCreateExtension.class,
AllocationTokenExtension.class);
flowCustomLogic.beforeValidation();
validateRegistrarIsLoggedIn(registrarId);
verifyRegistrarIsActive(registrarId);
extensionManager.validate();
verifyDomainDoesNotExist();
DateTime now = tm().getTransactionTime();
DomainCommand.Create command = cloneAndLinkReferences((Create) resourceCommand, now);
Period period = command.getPeriod();
verifyUnitIsYears(period);
int years = period.getValue();
validateRegistrationPeriod(years);
// Validate that this is actually a legal domain name on a TLD that the registrar has access to.
InternetDomainName domainName = validateDomainName(command.getDomainName());
String domainLabel = domainName.parts().getFirst();
Tld tld = Tld.get(domainName.parent().toString());
validateCreateCommandContactsAndNameservers(command, tld, domainName);
TldState tldState = tld.getTldState(now);
Optional<LaunchCreateExtension> launchCreate =
eppInput.getSingleExtension(LaunchCreateExtension.class);
boolean hasSignedMarks =
launchCreate.isPresent() && !launchCreate.get().getSignedMarks().isEmpty();
boolean hasClaimsNotice = launchCreate.isPresent() && launchCreate.get().getNotice() != null;
if (launchCreate.isPresent()) {
verifyNoCodeMarks(launchCreate.get());
validateLaunchCreateNotice(launchCreate.get().getNotice(), domainLabel, isSuperuser, now);
}
boolean isSunriseCreate = hasSignedMarks && (tldState == START_DATE_SUNRISE);
Optional<AllocationToken> allocationToken =
AllocationTokenFlowUtils.loadTokenFromExtensionOrGetDefault(
registrarId,
now,
eppInput.getSingleExtension(AllocationTokenExtension.class),
tld,
command.getDomainName(),
CommandName.CREATE);
boolean defaultTokenUsed =
allocationToken.map(t -> t.getTokenType().equals(TokenType.DEFAULT_PROMO)).orElse(false);
boolean isAnchorTenant =
isAnchorTenant(
domainName, allocationToken, eppInput.getSingleExtension(MetadataExtension.class));
verifyAnchorTenantValidPeriod(isAnchorTenant, years);
// Superusers can create reserved domains, force creations on domains that require a claims
// notice without specifying a claims key, ignore the registry phase, and override blocks on
// registering premium domains.
if (!isSuperuser) {
checkAllowedAccessToTld(registrarId, tld.getTldStr());
checkHasBillingAccount(registrarId, tld.getTldStr());
boolean isValidReservedCreate = isValidReservedCreate(domainName, allocationToken);
ClaimsList claimsList = ClaimsListDao.get();
verifyIsGaOrSpecialCase(
tld,
claimsList,
now,
domainLabel,
allocationToken,
isAnchorTenant,
isValidReservedCreate,
hasSignedMarks);
if (launchCreate.isPresent()) {
verifyLaunchPhaseMatchesRegistryPhase(tld, launchCreate.get(), now);
}
if (!isAnchorTenant && !isValidReservedCreate) {
verifyNotReserved(domainName, isSunriseCreate);
}
if (hasClaimsNotice) {
verifyClaimsPeriodNotEnded(tld, now);
}
if (now.isBefore(tld.getClaimsPeriodEnd())) {
verifyClaimsNoticeIfAndOnlyIfNeeded(
domainName, claimsList, hasSignedMarks, hasClaimsNotice);
}
verifyPremiumNameIsNotBlocked(targetId, now, registrarId);
verifySignedMarkOnlyInSunrise(hasSignedMarks, tldState);
}
String signedMarkId = null;
if (hasSignedMarks) {
// If a signed mark was provided, then it must match the desired domain label. Get the mark
// at this point so that we can verify it before the "after validation" extension point.
signedMarkId =
tmchUtils
.verifySignedMarks(launchCreate.get().getSignedMarks(), domainLabel, now)
.getId();
}
verifyNotBlockedByBsa(domainName, tld, now, allocationToken);
flowCustomLogic.afterValidation(
DomainCreateFlowCustomLogic.AfterValidationParameters.newBuilder()
.setDomainName(domainName)
.setYears(years)
.setSignedMarkId(Optional.ofNullable(signedMarkId))
.build());
Optional<FeeCreateCommandExtension> feeCreate =
eppInput.getSingleExtension(FeeCreateCommandExtension.class);
FeesAndCredits feesAndCredits =
pricingLogic.getCreatePrice(
tld, targetId, now, years, isAnchorTenant, isSunriseCreate, allocationToken);
validateFeeChallenge(feeCreate, feesAndCredits, defaultTokenUsed);
Optional<SecDnsCreateExtension> secDnsCreate =
validateSecDnsExtension(eppInput.getSingleExtension(SecDnsCreateExtension.class));
DateTime registrationExpirationTime = leapSafeAddYears(now, years);
String repoId = createDomainRepoId(tm().allocateId(), tld.getTldStr());
long historyRevisionId = tm().allocateId();
HistoryEntryId domainHistoryId = new HistoryEntryId(repoId, historyRevisionId);
historyBuilder.setRevisionId(historyRevisionId);
// Bill for the create.
BillingEvent createBillingEvent =
createBillingEvent(
tld,
isAnchorTenant,
isSunriseCreate,
isReserved(domainName, isSunriseCreate),
years,
feesAndCredits,
domainHistoryId,
allocationToken,
now);
// Create a new autorenew billing event and poll message starting at the expiration time.
BillingRecurrence autorenewBillingEvent =
createAutorenewBillingEvent(
domainHistoryId, registrationExpirationTime, isAnchorTenant, allocationToken);
PollMessage.Autorenew autorenewPollMessage =
createAutorenewPollMessage(domainHistoryId, registrationExpirationTime);
ImmutableSet.Builder<ImmutableObject> entitiesToSave = new ImmutableSet.Builder<>();
entitiesToSave.add(createBillingEvent, autorenewBillingEvent, autorenewPollMessage);
// Bill for EAP cost, if any.
if (!feesAndCredits.getEapCost().isZero()) {
entitiesToSave.add(createEapBillingEvent(feesAndCredits, createBillingEvent));
}
ImmutableSet<ReservationType> reservationTypes = getReservationTypes(domainName);
ImmutableSet<StatusValue> statuses =
reservationTypes.contains(NAME_COLLISION)
? ImmutableSet.of(SERVER_HOLD)
: ImmutableSet.of();
Domain.Builder domainBuilder =
new Domain.Builder()
.setCreationRegistrarId(registrarId)
.setPersistedCurrentSponsorRegistrarId(registrarId)
.setRepoId(repoId)
.setIdnTableName(validateDomainNameWithIdnTables(domainName))
.setRegistrationExpirationTime(registrationExpirationTime)
.setAutorenewBillingEvent(autorenewBillingEvent.createVKey())
.setAutorenewPollMessage(autorenewPollMessage.createVKey())
.setLaunchNotice(hasClaimsNotice ? launchCreate.get().getNotice() : null)
.setSmdId(signedMarkId)
.setDsData(secDnsCreate.map(SecDnsCreateExtension::getDsData).orElse(null))
.setRegistrant(command.getRegistrant())
.setAuthInfo(command.getAuthInfo())
.setDomainName(targetId)
.setNameservers(command.getNameservers().stream().collect(toImmutableSet()))
.setStatusValues(statuses)
.setContacts(command.getContacts())
.addGracePeriod(
GracePeriod.forBillingEvent(GracePeriodStatus.ADD, repoId, createBillingEvent))
.setLordnPhase(
hasSignedMarks
? LordnPhase.SUNRISE
: hasClaimsNotice ? LordnPhase.CLAIMS : LordnPhase.NONE);
Domain domain = domainBuilder.build();
if (allocationToken.isPresent()
&& allocationToken.get().getTokenType().equals(TokenType.BULK_PRICING)) {
if (years > 1) {
throw new BulkDomainRegisteredForTooManyYearsException(allocationToken.get().getToken());
}
domain = domain.asBuilder().setCurrentBulkToken(allocationToken.get().createVKey()).build();
}
DomainHistory domainHistory =
buildDomainHistory(domain, tld, now, period, tld.getAddGracePeriodLength());
if (reservationTypes.contains(NAME_COLLISION)) {
entitiesToSave.add(
createNameCollisionOneTimePollMessage(targetId, domainHistory, registrarId, now));
}
entitiesToSave.add(domain, domainHistory);
if (allocationToken.isPresent() && allocationToken.get().getTokenType().isOneTimeUse()) {
entitiesToSave.add(
AllocationTokenFlowUtils.redeemToken(
allocationToken.get(), domainHistory.getHistoryEntryId()));
}
if (domain.shouldPublishToDns()) {
requestDomainDnsRefresh(domain.getDomainName());
}
EntityChanges entityChanges =
flowCustomLogic.beforeSave(
DomainCreateFlowCustomLogic.BeforeSaveParameters.newBuilder()
.setNewDomain(domain)
.setHistoryEntry(domainHistory)
.setEntityChanges(
EntityChanges.newBuilder().setSaves(entitiesToSave.build()).build())
.setYears(years)
.build());
persistEntityChanges(entityChanges);
// If the registrar is participating in tiered pricing promos, return the standard price in the
// response (even if the actual charged price is less)
boolean shouldShowDefaultPrice =
defaultTokenUsed
&& RegistryConfig.getTieredPricingPromotionRegistrarIds().contains(registrarId);
FeesAndCredits responseFeesAndCredits =
shouldShowDefaultPrice
? pricingLogic.getCreatePrice(
tld, targetId, now, years, isAnchorTenant, isSunriseCreate, Optional.empty())
: feesAndCredits;
BeforeResponseReturnData responseData =
flowCustomLogic.beforeResponse(
BeforeResponseParameters.newBuilder()
.setResData(DomainCreateData.create(targetId, now, registrationExpirationTime))
.setResponseExtensions(createResponseExtensions(feeCreate, responseFeesAndCredits))
.build());
return responseBuilder
.setResData(responseData.resData())
.setExtensions(responseData.responseExtensions())
.build();
}
/**
* Verifies that signed marks are only sent during sunrise.
*
* <p>A trademarked domain name requires either a signed mark or a claims notice. We then need to
* send out a LORDN message - either a "sunrise" LORDN if we have a signed mark, or a "claims"
* LORDN if we have a claims notice.
*
* <p>This verification prevents us from either sending out a "sunrise" LORDN out of sunrise, or
* not sending out any LORDN, for a trademarked domain with a signed mark in GA.
*/
static void verifySignedMarkOnlyInSunrise(boolean hasSignedMarks, TldState tldState)
throws EppException {
if (hasSignedMarks && tldState != START_DATE_SUNRISE) {
throw new SignedMarksOnlyDuringSunriseException();
}
}
/**
* Verifies anchor tenant creates are only done for {@value ANCHOR_TENANT_CREATE_VALID_YEARS} year
* periods, as anchor tenants get exactly that many years of free registration.
*/
static void verifyAnchorTenantValidPeriod(boolean isAnchorTenant, int registrationYears)
throws EppException {
if (isAnchorTenant && registrationYears != ANCHOR_TENANT_CREATE_VALID_YEARS) {
throw new AnchorTenantCreatePeriodException(registrationYears);
}
}
/**
* Prohibit registrations unless they're in GA or a special case.
*
* <p>Non-trademarked names can be registered at any point with a special allocation token
* registration behavior.
*
* <p>Trademarked names require signed marks in sunrise no matter what, and can be registered with
* a special allocation token behavior in any quiet period that is post-sunrise.
*
* <p>Note that "superuser" status isn't tested here - this should only be called for
* non-superusers.
*/
private void verifyIsGaOrSpecialCase(
Tld tld,
ClaimsList claimsList,
DateTime now,
String domainLabel,
Optional<AllocationToken> allocationToken,
boolean isAnchorTenant,
boolean isValidReservedCreate,
boolean hasSignedMarks)
throws NoGeneralRegistrationsInCurrentPhaseException,
MustHaveSignedMarksInCurrentPhaseException,
NoTrademarkedRegistrationsBeforeSunriseException {
// We allow general registration during GA.
TldState currentState = tld.getTldState(now);
if (currentState.equals(GENERAL_AVAILABILITY)) {
return;
}
// Determine if there should be any behavior dictated by the allocation token
RegistrationBehavior behavior =
allocationToken
.map(AllocationToken::getRegistrationBehavior)
.orElse(RegistrationBehavior.DEFAULT);
// Bypass most TLD state checks if that behavior is specified by the token
if (behavior.equals(RegistrationBehavior.BYPASS_TLD_STATE)
|| behavior.equals(RegistrationBehavior.ANCHOR_TENANT)) {
// Non-trademarked names with the state check bypassed are always available
if (claimsList.getClaimKey(domainLabel).isEmpty()) {
return;
}
if (!currentState.equals(START_DATE_SUNRISE)) {
// Trademarked domains cannot be registered until after the sunrise period has ended, unless
// a valid signed mark is provided. Signed marks can only be provided during sunrise.
// Thus, when bypassing TLD state checks, a post-sunrise state is always fine.
if (tld.getTldStateTransitions().headMap(now).containsValue(START_DATE_SUNRISE)) {
return;
} else {
// If sunrise hasn't happened yet, trademarked domains are unavailable
throw new NoTrademarkedRegistrationsBeforeSunriseException(domainLabel);
}
}
}
// Otherwise, signed marks are necessary and sufficient in the sunrise period
if (currentState.equals(START_DATE_SUNRISE)) {
if (!hasSignedMarks) {
throw new MustHaveSignedMarksInCurrentPhaseException();
}
return;
}
// Anchor tenant overrides any remaining considerations to allow registration
if (isAnchorTenant) {
return;
}
// We allow creates of specifically reserved domain names during quiet periods
if (currentState.equals(QUIET_PERIOD)) {
if (isValidReservedCreate) {
return;
}
}
// All other phases do not allow registration
throw new NoGeneralRegistrationsInCurrentPhaseException();
}
private DomainHistory buildDomainHistory(
Domain domain, Tld tld, DateTime now, Period period, Duration addGracePeriod) {
// We ignore prober transactions
if (tld.getTldType() == TldType.REAL) {
historyBuilder.setDomainTransactionRecords(
ImmutableSet.of(
DomainTransactionRecord.create(
tld.getTldStr(),
now.plus(addGracePeriod),
TransactionReportField.netAddsFieldFromYears(period.getValue()),
1)));
}
return historyBuilder.setType(DOMAIN_CREATE).setPeriod(period).setDomain(domain).build();
}
private BillingEvent createBillingEvent(
Tld tld,
boolean isAnchorTenant,
boolean isSunriseCreate,
boolean isReserved,
int years,
FeesAndCredits feesAndCredits,
HistoryEntryId domainHistoryId,
Optional<AllocationToken> allocationToken,
DateTime now) {
ImmutableSet.Builder<Flag> flagsBuilder = new ImmutableSet.Builder<>();
// Sunrise and anchor tenancy are orthogonal tags and thus both can be present together.
if (isSunriseCreate) {
flagsBuilder.add(Flag.SUNRISE);
}
if (isAnchorTenant) {
flagsBuilder.add(Flag.ANCHOR_TENANT);
} else if (isReserved) {
// Don't add this flag if the domain is an anchor tenant (which are also reserved); only add
// it if it's reserved for other reasons.
flagsBuilder.add(Flag.RESERVED);
}
return new BillingEvent.Builder()
.setReason(Reason.CREATE)
.setTargetId(targetId)
.setRegistrarId(registrarId)
.setPeriodYears(years)
.setCost(feesAndCredits.getCreateCost())
.setEventTime(now)
.setAllocationToken(allocationToken.map(AllocationToken::createVKey).orElse(null))
.setBillingTime(
now.plus(
isAnchorTenant
? tld.getAnchorTenantAddGracePeriodLength()
: tld.getAddGracePeriodLength()))
.setFlags(flagsBuilder.build())
.setDomainHistoryId(domainHistoryId)
.build();
}
private BillingRecurrence createAutorenewBillingEvent(
HistoryEntryId domainHistoryId,
DateTime registrationExpirationTime,
boolean isAnchorTenant,
Optional<AllocationToken> allocationToken) {
// Non-standard renewal behaviors can occur for anchor tenants (always NONPREMIUM pricing) or if
// explicitly configured in the token (either NONPREMIUM or directly SPECIFIED). Use DEFAULT if
// none is configured.
RenewalPriceBehavior renewalPriceBehavior =
isAnchorTenant
? RenewalPriceBehavior.NONPREMIUM
: allocationToken
.map(AllocationToken::getRenewalPriceBehavior)
.orElse(RenewalPriceBehavior.DEFAULT);
return new BillingRecurrence.Builder()
.setReason(Reason.RENEW)
.setFlags(ImmutableSet.of(Flag.AUTO_RENEW))
.setTargetId(targetId)
.setRegistrarId(registrarId)
.setEventTime(registrationExpirationTime)
.setRecurrenceEndTime(END_OF_TIME)
.setDomainHistoryId(domainHistoryId)
.setRenewalPriceBehavior(renewalPriceBehavior)
.setRenewalPrice(allocationToken.flatMap(AllocationToken::getRenewalPrice).orElse(null))
.build();
}
private Autorenew createAutorenewPollMessage(
HistoryEntryId domainHistoryId, DateTime registrationExpirationTime) {
return new PollMessage.Autorenew.Builder()
.setTargetId(targetId)
.setRegistrarId(registrarId)
.setEventTime(registrationExpirationTime)
.setMsg("Domain was auto-renewed.")
.setDomainHistoryId(domainHistoryId)
.build();
}
private void verifyDomainDoesNotExist() throws ResourceCreateContentionException {
Optional<DateTime> previousDeletionTime =
domainDeletionTimeCache.getDeletionTimeForDomain(targetId);
if (previousDeletionTime.isPresent()
&& !tm().getTransactionTime().isAfter(previousDeletionTime.get())) {
throw new ResourceCreateContentionException(targetId);
}
}
private static BillingEvent createEapBillingEvent(
FeesAndCredits feesAndCredits, BillingEvent createBillingEvent) {
return new BillingEvent.Builder()
.setReason(Reason.FEE_EARLY_ACCESS)
.setTargetId(createBillingEvent.getTargetId())
.setRegistrarId(createBillingEvent.getRegistrarId())
.setPeriodYears(1)
.setCost(feesAndCredits.getEapCost())
.setEventTime(createBillingEvent.getEventTime())
.setBillingTime(createBillingEvent.getBillingTime())
.setFlags(createBillingEvent.getFlags())
.setDomainHistoryId(createBillingEvent.getHistoryEntryId())
.build();
}
private static PollMessage.OneTime createNameCollisionOneTimePollMessage(
String domainName, HistoryEntry historyEntry, String registrarId, DateTime now) {
return new PollMessage.OneTime.Builder()
.setRegistrarId(registrarId)
.setEventTime(now)
.setMsg(COLLISION_MESSAGE) // Remind the registrar of the name collision policy.
.setResponseData(
ImmutableList.of(
DomainPendingActionNotificationResponse.create(
domainName, true, historyEntry.getTrid(), now)))
.setHistoryEntry(historyEntry)
.build();
}
private static ImmutableList<FeeTransformResponseExtension> createResponseExtensions(
Optional<FeeCreateCommandExtension> feeCreate, FeesAndCredits feesAndCredits) {
return feeCreate
.map(
feeCreateCommandExtension ->
ImmutableList.of(
createFeeCreateResponse(feeCreateCommandExtension, feesAndCredits)))
.orElseGet(ImmutableList::of);
}
/** Signed marks are only allowed during sunrise. */
static class SignedMarksOnlyDuringSunriseException extends CommandUseErrorException {
public SignedMarksOnlyDuringSunriseException() {
super("Signed marks are only allowed during sunrise");
}
}
/** The current registry phase does not allow for general registrations. */
static class NoGeneralRegistrationsInCurrentPhaseException extends CommandUseErrorException {
public NoGeneralRegistrationsInCurrentPhaseException() {
super("The current registry phase does not allow for general registrations");
}
}
/** The current registry phase allows registrations only with signed marks. */
static class MustHaveSignedMarksInCurrentPhaseException extends CommandUseErrorException {
public MustHaveSignedMarksInCurrentPhaseException() {
super("The current registry phase requires a signed mark for registrations");
}
}
/** Trademarked domains cannot be registered before the sunrise period. */
static class NoTrademarkedRegistrationsBeforeSunriseException
extends ParameterValuePolicyErrorException {
public NoTrademarkedRegistrationsBeforeSunriseException(String domainLabel) {
super(
String.format(
"The trademarked label %s cannot be registered before the sunrise period.",
domainLabel));
}
}
/** Anchor tenant domain create is for the wrong number of years. */
static class AnchorTenantCreatePeriodException extends ParameterValuePolicyErrorException {
public AnchorTenantCreatePeriodException(int invalidYears) {
super(
String.format(
"Anchor tenant domain creates must be for a period of %s years, got %s instead.",
ANCHOR_TENANT_CREATE_VALID_YEARS, invalidYears));
}
}
/** Bulk pricing domain registered for too many years. */
static class BulkDomainRegisteredForTooManyYearsException extends CommandUseErrorException {
public BulkDomainRegisteredForTooManyYearsException(String token) {
super(
String.format(
"The bulk token %s cannot be used to register names for longer than 1 year.", token));
}
}
}
|
apache/geode | 36,493 | geode-core/src/main/java/org/apache/geode/internal/cache/DistributedRemoveAllOperation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.cache;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.logging.log4j.Logger;
import org.apache.geode.DataSerializer;
import org.apache.geode.cache.CacheEvent;
import org.apache.geode.cache.DataPolicy;
import org.apache.geode.cache.EntryNotFoundException;
import org.apache.geode.cache.Operation;
import org.apache.geode.cache.RegionAttributes;
import org.apache.geode.cache.Scope;
import org.apache.geode.cache.persistence.PersistentReplicatesOfflineException;
import org.apache.geode.cache.query.internal.cq.CqService;
import org.apache.geode.cache.query.internal.cq.ServerCQ;
import org.apache.geode.distributed.internal.DirectReplyProcessor;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.InternalDataSerializer;
import org.apache.geode.internal.cache.DistributedPutAllOperation.EntryVersionsList;
import org.apache.geode.internal.cache.FilterRoutingInfo.FilterInfo;
import org.apache.geode.internal.cache.ha.ThreadIdentifier;
import org.apache.geode.internal.cache.partitioned.RemoveAllPRMessage;
import org.apache.geode.internal.cache.tier.MessageType;
import org.apache.geode.internal.cache.tier.sockets.ClientProxyMembershipID;
import org.apache.geode.internal.cache.tier.sockets.VersionedObjectList;
import org.apache.geode.internal.cache.tx.RemoteRemoveAllMessage;
import org.apache.geode.internal.cache.versions.ConcurrentCacheModificationException;
import org.apache.geode.internal.cache.versions.DiskVersionTag;
import org.apache.geode.internal.cache.versions.VersionSource;
import org.apache.geode.internal.cache.versions.VersionTag;
import org.apache.geode.internal.offheap.annotations.Released;
import org.apache.geode.internal.offheap.annotations.Retained;
import org.apache.geode.internal.offheap.annotations.Unretained;
import org.apache.geode.internal.serialization.DataSerializableFixedID;
import org.apache.geode.internal.serialization.DeserializationContext;
import org.apache.geode.internal.serialization.SerializationContext;
import org.apache.geode.logging.internal.log4j.api.LogService;
/**
* Handles distribution of a Region.removeAll operation.
*
* TODO: extend DistributedCacheOperation instead of AbstractUpdateOperation
*
* @since GemFire 8.1
*/
public class DistributedRemoveAllOperation extends AbstractUpdateOperation {
private static final Logger logger = LogService.getLogger();
/**
* Release is called by freeOffHeapResources.
*/
@Retained
protected final RemoveAllEntryData[] removeAllData;
public int removeAllDataSize;
protected boolean isBridgeOp = false;
static final byte USED_FAKE_EVENT_ID = 0x01;
static final byte NOTIFY_ONLY = 0x02;
static final byte FILTER_ROUTING = 0x04;
static final byte VERSION_TAG = 0x08;
static final byte POSDUP = 0x10;
static final byte PERSISTENT_TAG = 0x20;
static final byte HAS_CALLBACKARG = 0x40;
static final byte HAS_TAILKEY = (byte) 0x80;
public DistributedRemoveAllOperation(CacheEvent event, int size, boolean isBridgeOp) {
super(event, ((EntryEventImpl) event).getEventTime(0L));
removeAllData = new RemoveAllEntryData[size];
removeAllDataSize = 0;
this.isBridgeOp = isBridgeOp;
}
/**
* return if the operation is bridge operation
*/
public boolean isBridgeOperation() {
return isBridgeOp;
}
public RemoveAllEntryData[] getRemoveAllEntryData() {
return removeAllData;
}
public void setRemoveAllEntryData(RemoveAllEntryData[] removeAllEntryData) {
for (int i = 0; i < removeAllEntryData.length; i++) {
removeAllData[i] = removeAllEntryData[i];
}
removeAllDataSize = removeAllEntryData.length;
}
/**
* Add an entry that this removeAll operation should distribute.
*/
public void addEntry(RemoveAllEntryData removeAllEntry) {
removeAllData[removeAllDataSize] = removeAllEntry;
removeAllDataSize += 1;
}
/**
* Add an entry that this removeAll operation should distribute.
*/
public void addEntry(EntryEventImpl ev) {
removeAllData[removeAllDataSize] = new RemoveAllEntryData(ev);
removeAllDataSize += 1;
}
/**
* Add an entry that this removeAll operation should distribute. This method is for a special
* case: the callback will be called after this in hasSeenEvent() case, so we should change the
* status beforehand
*/
public void addEntry(EntryEventImpl ev, boolean newCallbackInvoked) {
removeAllData[removeAllDataSize] = new RemoveAllEntryData(ev);
removeAllData[removeAllDataSize].setCallbacksInvoked(newCallbackInvoked);
removeAllDataSize += 1;
}
/**
* Add an entry for PR bucket's msg.
*
* @param ev event to be added
* @param bucketId message is for this bucket
*/
public void addEntry(EntryEventImpl ev, Integer bucketId) {
removeAllData[removeAllDataSize] = new RemoveAllEntryData(ev);
removeAllData[removeAllDataSize].setBucketId(bucketId);
removeAllDataSize += 1;
}
/**
* set using fake thread id
*
* @param status whether the entry is using fake event id
*/
public void setUseFakeEventId(boolean status) {
for (int i = 0; i < removeAllDataSize; i++) {
removeAllData[i].setUsedFakeEventId(status);
}
}
/**
* In the originating cache, this returns an iterator on the list of events caused by the
* removeAll operation. This is cached for listener notification purposes. The iterator is
* guaranteed to return events in the order they are present in putAllData[]
*/
public Iterator eventIterator() {
return new Iterator() {
int position = 0;
@Override
public boolean hasNext() {
return removeAllDataSize > position;
}
@Override
@Unretained
public Object next() {
@Unretained
EntryEventImpl ev = getEventForPosition(position);
position++;
return ev;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public void freeOffHeapResources() {
// I do not use eventIterator here because it forces the lazy creation of EntryEventImpl by
// calling getEventForPosition.
for (int i = 0; i < removeAllDataSize; i++) {
RemoveAllEntryData entry = removeAllData[i];
if (entry != null && entry.event != null) {
entry.event.release();
}
}
}
@Unretained
public EntryEventImpl getEventForPosition(int position) {
RemoveAllEntryData entry = removeAllData[position];
if (entry == null) {
return null;
}
if (entry.event != null) {
return entry.event;
}
LocalRegion region = (LocalRegion) event.getRegion();
// owned by this.removeAllData once entry.event = ev is done
@Retained
EntryEventImpl ev = EntryEventImpl.create(region, entry.getOp(), entry.getKey(),
null/* value */, event.getCallbackArgument(), false /* originRemote */,
event.getDistributedMember(), event.isGenerateCallbacks(), entry.getEventID());
boolean returnedEv = false;
try {
ev.setPossibleDuplicate(entry.isPossibleDuplicate());
ev.setIsRedestroyedEntry(entry.getRedestroyedEntry());
if (entry.versionTag != null && region.getConcurrencyChecksEnabled()) {
VersionSource id = entry.versionTag.getMemberID();
if (id != null) {
entry.versionTag.setMemberID(ev.getRegion().getVersionVector().getCanonicalId(id));
}
ev.setVersionTag(entry.versionTag);
}
entry.event = ev;
returnedEv = true;
ev.setOldValue(entry.getOldValue());
CqService cqService = region.getCache().getCqService();
if (cqService.isRunning() && !entry.getOp().isCreate() && !ev.hasOldValue()) {
ev.setOldValueForQueryProcessing();
}
ev.setInvokePRCallbacks(!entry.isNotifyOnly());
if (getBaseEvent().getContext() != null) {
ev.setContext(getBaseEvent().getContext());
}
ev.callbacksInvoked(entry.isCallbacksInvoked());
ev.setTailKey(entry.getTailKey());
return ev;
} finally {
if (!returnedEv) {
ev.release();
}
}
}
public EntryEventImpl getBaseEvent() {
return getEvent();
}
/**
* Data that represents a single entry being RemoveAll'd.
*/
public static class RemoveAllEntryData {
final Object key;
private final Object oldValue;
private final Operation op;
private EventID eventID;
transient EntryEventImpl event;
private Integer bucketId = -1;
protected transient boolean callbacksInvoked = false;
public FilterRoutingInfo filterRouting;
// One flags byte for all booleans
protected byte flags = 0x00;
// TODO: Yogesh, this should be intialized and sent on wire only when
// parallel wan is enabled
private Long tailKey = 0L;
public VersionTag versionTag;
transient boolean inhibitDistribution;
transient boolean redestroyedEntry;
/**
* Constructor to use when preparing to send putall data out
*/
public RemoveAllEntryData(EntryEventImpl event) {
key = event.getKey();
Object oldValue = event.getRawOldValue();
if (oldValue == Token.NOT_AVAILABLE || Token.isRemoved(oldValue)) {
this.oldValue = null;
} else {
this.oldValue = oldValue;
}
op = event.getOperation();
eventID = event.getEventId();
tailKey = event.getTailKey();
versionTag = event.getVersionTag();
setNotifyOnly(!event.getInvokePRCallbacks());
setCallbacksInvoked(event.callbacksInvoked());
setPossibleDuplicate(event.isPossibleDuplicate());
setInhibitDistribution(event.getInhibitDistribution());
setRedestroyedEntry(event.getIsRedestroyedEntry());
}
/**
* Constructor to use when receiving a putall from someone else
*/
public RemoveAllEntryData(DataInput in, EventID baseEventID, int idx,
DeserializationContext context) throws IOException, ClassNotFoundException {
key = context.getDeserializer().readObject(in);
oldValue = null;
op = Operation.fromOrdinal(in.readByte());
flags = in.readByte();
if ((flags & FILTER_ROUTING) != 0) {
filterRouting = context.getDeserializer().readObject(in);
}
if ((flags & VERSION_TAG) != 0) {
boolean persistentTag = (flags & PERSISTENT_TAG) != 0;
versionTag = VersionTag.create(persistentTag, in);
}
if (isUsedFakeEventId()) {
eventID = new EventID();
InternalDataSerializer.invokeFromData(eventID, in);
} else {
eventID = new EventID(baseEventID, idx);
}
if ((flags & HAS_TAILKEY) != 0) {
tailKey = DataSerializer.readLong(in);
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(50);
sb.append("(").append(getKey()).append(",").append(getOldValue());
if (bucketId > 0) {
sb.append(", b").append(bucketId);
}
if (versionTag != null) {
sb.append(",v").append(versionTag.getEntryVersion())
.append(",rv=" + versionTag.getRegionVersion());
}
if (filterRouting != null) {
sb.append(", ").append(filterRouting);
}
sb.append(")");
return sb.toString();
}
void setSender(InternalDistributedMember sender) {
if (versionTag != null) {
versionTag.replaceNullIDs(sender);
}
}
/**
* Used to serialize this instances data to <code>out</code>. If changes are made to this method
* make sure that it is backwards compatible by creating toDataPreXX methods. Also make sure
* that the callers to this method are backwards compatible by creating toDataPreXX methods for
* them even if they are not changed. <br>
* Callers for this method are: <br>
* {@link DataSerializableFixedID#toData(DataOutput, SerializationContext)} <br>
* {@link DataSerializableFixedID#toData(DataOutput, SerializationContext)} <br>
* {@link DataSerializableFixedID#toData(DataOutput, SerializationContext)} <br>
*/
public void serializeTo(final DataOutput out,
SerializationContext context) throws IOException {
Object key = this.key;
context.getSerializer().writeObject(key, out);
out.writeByte(op.ordinal);
byte bits = flags;
if (filterRouting != null) {
bits |= FILTER_ROUTING;
}
if (versionTag != null) {
bits |= VERSION_TAG;
if (versionTag instanceof DiskVersionTag) {
bits |= PERSISTENT_TAG;
}
}
// TODO: Yogesh, this should be conditional,
// make sure that we sent it on wire only
// when parallel wan is enabled
bits |= HAS_TAILKEY;
out.writeByte(bits);
if (filterRouting != null) {
context.getSerializer().writeObject(filterRouting, out);
}
if (versionTag != null) {
InternalDataSerializer.invokeToData(versionTag, out);
}
if (isUsedFakeEventId()) {
// fake event id should be serialized
InternalDataSerializer.invokeToData(eventID, out);
}
// TODO: Yogesh, this should be conditional,
// make sure that we sent it on wire only
// when parallel wan is enabled
DataSerializer.writeLong(tailKey, out);
}
/**
* Returns the key
*/
public Object getKey() {
return key;
}
/**
* Returns the old value
*/
public Object getOldValue() {
return oldValue;
}
public Long getTailKey() {
return tailKey;
}
public void setTailKey(Long key) {
tailKey = key;
}
/**
* Returns the operation
*/
public Operation getOp() {
return op;
}
public EventID getEventID() {
return eventID;
}
/**
* change event id for the entry
*
* @param eventId new event id
*/
public void setEventId(EventID eventId) {
eventID = eventId;
}
/**
* change bucket id for the entry
*
* @param bucketId new bucket id
*/
public void setBucketId(Integer bucketId) {
this.bucketId = bucketId;
}
/**
* get bucket id for the entry
*
* @return bucket id
*/
public Integer getBucketId() {
return bucketId;
}
/**
* change event id into fake event id The algorithm is to change the threadid into
* bucketid*MAX_THREAD_PER_CLIENT+oldthreadid. So from the log, we can derive the original
* thread id.
*
* @return wether current event id is fake or not new bucket id
*/
public boolean setFakeEventID() {
if (bucketId < 0) {
return false;
}
if (!isUsedFakeEventId()) {
// assign a fake big thread id. bucket id starts from 0. In order to distinguish
// with other read thread, let bucket id starts from 1 in fake thread id
long threadId = ThreadIdentifier.createFakeThreadIDForBulkOp(bucketId,
eventID.getThreadID());
eventID = new EventID(eventID.getMembershipID(), threadId, eventID.getSequenceID());
setUsedFakeEventId(true);
}
return true;
}
public boolean isUsedFakeEventId() {
return (flags & USED_FAKE_EVENT_ID) != 0;
}
public void setUsedFakeEventId(boolean usedFakeEventId) {
if (usedFakeEventId) {
flags |= USED_FAKE_EVENT_ID;
} else {
flags &= ~(USED_FAKE_EVENT_ID);
}
}
public boolean isNotifyOnly() {
return (flags & NOTIFY_ONLY) != 0;
}
public void setNotifyOnly(boolean notifyOnly) {
if (notifyOnly) {
flags |= NOTIFY_ONLY;
} else {
flags &= ~(NOTIFY_ONLY);
}
}
boolean isPossibleDuplicate() {
return (flags & POSDUP) != 0;
}
public void setPossibleDuplicate(boolean possibleDuplicate) {
if (possibleDuplicate) {
flags |= POSDUP;
} else {
flags &= ~(POSDUP);
}
}
public boolean isInhibitDistribution() {
return inhibitDistribution;
}
public void setInhibitDistribution(boolean inhibitDistribution) {
this.inhibitDistribution = inhibitDistribution;
}
public boolean getRedestroyedEntry() {
return redestroyedEntry;
}
public void setRedestroyedEntry(boolean redestroyedEntry) {
this.redestroyedEntry = redestroyedEntry;
}
public boolean isCallbacksInvoked() {
return callbacksInvoked;
}
public void setCallbacksInvoked(boolean callbacksInvoked) {
this.callbacksInvoked = callbacksInvoked;
}
}
@Override
protected FilterRoutingInfo getRecipientFilterRouting(Set cacheOpRecipients) {
// for removeAll, we need to determine the routing information for each event and
// create a consolidated routing object representing all events that can be
// used for distribution
CacheDistributionAdvisor advisor;
LocalRegion region = (LocalRegion) event.getRegion();
if (region instanceof PartitionedRegion) {
advisor = ((PartitionedRegion) region).getCacheDistributionAdvisor();
} else if (region.isUsedForPartitionedRegionBucket()) {
advisor = region.getPartitionedRegion().getCacheDistributionAdvisor();
} else {
advisor = ((DistributedRegion) region).getCacheDistributionAdvisor();
}
FilterRoutingInfo consolidated = new FilterRoutingInfo();
for (int i = 0; i < removeAllData.length; i++) {
@Unretained
EntryEventImpl ev = getEventForPosition(i);
if (ev != null) {
FilterRoutingInfo eventRouting = advisor.adviseFilterRouting(ev, cacheOpRecipients);
if (eventRouting != null) {
consolidated.addFilterInfo(eventRouting);
}
removeAllData[i].filterRouting = eventRouting;
}
}
// we need to create routing information for each PUT event
return consolidated;
}
@Override
void doRemoveDestroyTokensFromCqResultKeys(FilterInfo filterInfo, ServerCQ cq) {
for (Map.Entry<Long, MessageType> e : filterInfo.getCQs().entrySet()) {
Long cqID = e.getKey();
// For the CQs satisfying the event with destroy CQEvent, remove
// the entry from CQ cache.
for (int i = 0; i < removeAllData.length; i++) {
@Unretained
EntryEventImpl entryEvent = getEventForPosition(i);
if (entryEvent != null && entryEvent.getKey() != null && cq != null
&& cq.getFilterID() != null && cq.getFilterID().equals(cqID)
&& e.getValue() != null && e.getValue().equals(MessageType.LOCAL_DESTROY)) {
cq.removeFromCqResultKeys(entryEvent.getKey(), true);
}
}
}
}
@Override
protected FilterInfo getLocalFilterRouting(FilterRoutingInfo frInfo) {
FilterProfile fp = getRegion().getFilterProfile();
if (fp == null) {
return null;
}
// this will set the local FilterInfo in the events
if (removeAllData != null && removeAllData.length > 0) {
fp.getLocalFilterRoutingForRemoveAllOp(this, removeAllData);
}
return null;
}
@Override
protected CacheOperationMessage createMessage() {
EntryEventImpl event = getBaseEvent();
RemoveAllMessage msg = new RemoveAllMessage();
msg.eventId = event.getEventId();
msg.context = event.getContext();
return msg;
}
/**
* Create RemoveAllPRMessage for notify only (to adjunct nodes)
*
* @param bucketId create message to send to this bucket
*/
public RemoveAllPRMessage createPRMessagesNotifyOnly(int bucketId) {
final EntryEventImpl event = getBaseEvent();
RemoveAllPRMessage prMsg = new RemoveAllPRMessage(bucketId, removeAllDataSize, true,
event.isPossibleDuplicate(), !event.isGenerateCallbacks(), event.getCallbackArgument());
if (event.getContext() != null) {
prMsg.setBridgeContext(event.getContext());
}
// will not recover event id here
for (int i = 0; i < removeAllDataSize; i++) {
prMsg.addEntry(removeAllData[i]);
}
return prMsg;
}
/**
* Create RemoveAllPRMessages for primary buckets out of this op
*
* @return a HashMap contain RemoveAllPRMessages, key is bucket id
*/
public HashMap<Integer, RemoveAllPRMessage> createPRMessages() {
// getFilterRecipients(Collections.EMPTY_SET); // establish filter recipient routing information
HashMap<Integer, RemoveAllPRMessage> prMsgMap = new HashMap<>();
final EntryEventImpl event = getBaseEvent();
for (int i = 0; i < removeAllDataSize; i++) {
Integer bucketId = removeAllData[i].getBucketId();
RemoveAllPRMessage prMsg = prMsgMap.get(bucketId);
if (prMsg == null) {
prMsg = new RemoveAllPRMessage(bucketId, removeAllDataSize, false,
event.isPossibleDuplicate(), !event.isGenerateCallbacks(), event.getCallbackArgument());
prMsg
.setTransactionDistributed(event.getRegion().getCache().getTxManager().isDistributed());
// set dpao's context(original sender) into each PutAllMsg
// dpao's event's context could be null if it's P2P putAll in PR
if (event.getContext() != null) {
prMsg.setBridgeContext(event.getContext());
}
}
// Modify the event id, assign new thread id and new sequence id
// We have to set fake event id here, because we cannot derive old event id from baseId+idx as
// we
// did in DR's PutAllMessage.
removeAllData[i].setFakeEventID();
// we only save the reference in prMsg. No duplicate copy
prMsg.addEntry(removeAllData[i]);
prMsgMap.put(bucketId, prMsg);
}
return prMsgMap;
}
@Override
protected void initMessage(CacheOperationMessage msg, DirectReplyProcessor proc) {
super.initMessage(msg, proc);
RemoveAllMessage m = (RemoveAllMessage) msg;
// if concurrency checks are enabled and this is not a replicated
// region we need to see if any of the entries have no versions and,
// if so, cull them out and send a 1-hop message to a replicate that
// can generate a version for the operation
RegionAttributes attr = event.getRegion().getAttributes();
if (attr.getConcurrencyChecksEnabled() && !attr.getDataPolicy().withReplication()
&& attr.getScope() != Scope.GLOBAL) {
if (attr.getDataPolicy() == DataPolicy.EMPTY) {
// all entries are without version tags
boolean success = RemoteRemoveAllMessage.distribute((EntryEventImpl) event,
removeAllData, removeAllDataSize);
if (success) {
m.callbackArg = event.getCallbackArgument();
m.removeAllData = new RemoveAllEntryData[0];
m.removeAllDataSize = 0;
m.skipCallbacks = !event.isGenerateCallbacks();
return;
} else if (!getRegion().getGenerateVersionTag()) {
// Fix for #45934. We can't continue if we need versions and we failed
// to distribute versionless entries.
throw new PersistentReplicatesOfflineException();
}
} else {
// some entries may have Create ops - these will not have version tags
RemoveAllEntryData[] versionless = selectVersionlessEntries();
if (logger.isTraceEnabled()) {
logger.trace("Found these versionless entries: {}", Arrays.toString(versionless));
}
if (versionless.length > 0) {
boolean success = RemoteRemoveAllMessage.distribute((EntryEventImpl) event,
versionless, versionless.length);
if (success) {
versionless = null;
RemoveAllEntryData[] versioned = selectVersionedEntries();
if (logger.isTraceEnabled()) {
logger.trace("Found these remaining versioned entries: {}",
Arrays.toString(versioned));
}
m.callbackArg = event.getCallbackArgument();
m.removeAllData = versioned;
m.removeAllDataSize = versioned.length;
m.skipCallbacks = !event.isGenerateCallbacks();
return;
} else if (!getRegion().getGenerateVersionTag()) {
// Fix for #45934. We can't continue if we need versions and we failed
// to distribute versionless entries.
throw new PersistentReplicatesOfflineException();
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("All entries have versions, so using normal DPAO message");
}
}
}
}
m.callbackArg = event.getCallbackArgument();
m.removeAllData = removeAllData;
m.removeAllDataSize = removeAllDataSize;
m.skipCallbacks = !event.isGenerateCallbacks();
}
@Override
protected boolean shouldAck() {
// bug #45704 - RemotePutAllOp's DPAO in another server conflicts with lingering DPAO from same
// thread, so
// we require an ACK if concurrency checks are enabled to make sure that the previous op has
// finished first.
return super.shouldAck() || getRegion().getConcurrencyChecksEnabled();
}
private RemoveAllEntryData[] selectVersionlessEntries() {
int resultSize = removeAllData.length;
for (RemoveAllEntryData p : removeAllData) {
if (p == null || p.isInhibitDistribution()) {
resultSize--;
} else if (p.versionTag != null && p.versionTag.hasValidVersion()) {
resultSize--;
}
}
RemoveAllEntryData[] result = new RemoveAllEntryData[resultSize];
int ri = 0;
for (RemoveAllEntryData p : removeAllData) {
if (p == null || p.isInhibitDistribution()) {
continue; // skip blanks
} else if (p.versionTag != null && p.versionTag.hasValidVersion()) {
continue; // skip versioned
}
// what remains is versionless
result[ri++] = p;
}
return result;
}
private RemoveAllEntryData[] selectVersionedEntries() {
int resultSize = 0;
for (RemoveAllEntryData p : removeAllData) {
if (p == null || p.isInhibitDistribution()) {
continue; // skip blanks
} else if (p.versionTag != null && p.versionTag.hasValidVersion()) {
resultSize++;
}
}
RemoveAllEntryData[] result = new RemoveAllEntryData[resultSize];
int ri = 0;
for (RemoveAllEntryData p : removeAllData) {
if (p == null || p.isInhibitDistribution()) {
continue; // skip blanks
} else if (p.versionTag != null && p.versionTag.hasValidVersion()) {
result[ri++] = p;
}
}
return result;
}
/**
* version tags are gathered from local operations and remote operation responses. This method
* gathers all of them and stores them in the given list.
*
*/
protected void fillVersionedObjectList(VersionedObjectList list) {
for (RemoveAllEntryData entry : removeAllData) {
if (entry.versionTag != null) {
list.addKeyAndVersion(entry.key, entry.versionTag);
}
}
}
public static class RemoveAllMessage extends AbstractUpdateMessage // TODO extend
// CacheOperationMessage
// instead
{
protected RemoveAllEntryData[] removeAllData;
protected int removeAllDataSize;
protected transient ClientProxyMembershipID context;
protected boolean skipCallbacks;
protected EventID eventId = null;
protected static final short HAS_BRIDGE_CONTEXT = UNRESERVED_FLAGS_START;
protected static final short SKIP_CALLBACKS = (short) (HAS_BRIDGE_CONTEXT << 1);
/** test to see if this message holds any data */
public boolean isEmpty() {
return removeAllData.length == 0;
}
/**
* Note this this is a "dummy" event since this message contains a list of entries each one of
* which has its own event. The key thing needed in this event is the region. This is the event
* that gets passed to basicOperateOnRegion
*/
@Override
@Retained
protected InternalCacheEvent createEvent(DistributedRegion rgn) throws EntryNotFoundException {
// Gester: We have to specify eventId for the message of MAP
@Retained
EntryEventImpl event = EntryEventImpl.create(rgn, Operation.REMOVEALL_DESTROY, null /* key */,
null/* value */, callbackArg, true /* originRemote */, getSender());
if (context != null) {
event.context = context;
}
event.setPossibleDuplicate(possibleDuplicate);
event.setEventId(eventId);
return event;
}
@Override
public void appendFields(StringBuilder sb) {
super.appendFields(sb);
if (eventId != null) {
sb.append("; eventId=").append(eventId);
}
sb.append("; entries=").append(removeAllDataSize);
if (removeAllDataSize <= 20) {
// 20 is a size for test
sb.append("; entry values=").append(Arrays.toString(removeAllData));
}
}
/**
* Does the "remove" of one entry for a "removeAll" operation. Note it calls back to
* AbstractUpdateOperation.UpdateMessage#basicOperationOnRegion
*
* @param entry the entry being removed
* @param rgn the region the entry is removed from
*/
public void doEntryRemove(RemoveAllEntryData entry, DistributedRegion rgn) {
@Released
EntryEventImpl ev = RemoveAllMessage.createEntryEvent(entry, getSender(), context, rgn,
possibleDuplicate, needsRouting, callbackArg, true, skipCallbacks);
// rgn.getLogWriterI18n().info(String.format("%s", "RemoveAllMessage.doEntryRemove
// sender=" + getSender() +
// " event="+ev));
// we don't need to set old value here, because the msg is from remote. local old value will
// get from next step
try {
if (ev.getVersionTag() != null) {
checkVersionTag(rgn, ev.getVersionTag());
}
// TODO check all removeAll basicDestroy calls done on the farside and make sure
// "cacheWrite" is false
rgn.basicDestroy(ev, false, null);
} catch (EntryNotFoundException ignore) {
appliedOperation = true;
} catch (ConcurrentCacheModificationException e) {
dispatchElidedEvent(rgn, ev);
appliedOperation = false;
} finally {
if (ev.hasValidVersionTag() && !ev.getVersionTag().isRecorded()) {
if (rgn.getVersionVector() != null) {
rgn.getVersionVector().recordVersion(getSender(), ev.getVersionTag());
}
}
ev.release();
}
}
/**
* create an event for a RemoveAllEntryData element
*
* @return the event to be used in applying the element
*/
@Retained
public static EntryEventImpl createEntryEvent(RemoveAllEntryData entry,
InternalDistributedMember sender, ClientProxyMembershipID context, DistributedRegion rgn,
boolean possibleDuplicate, boolean needsRouting, Object callbackArg, boolean originRemote,
boolean skipCallbacks) {
final Object key = entry.getKey();
EventID evId = entry.getEventID();
@Retained
EntryEventImpl ev = EntryEventImpl.create(rgn, entry.getOp(), key, null/* value */,
callbackArg, originRemote, sender, !skipCallbacks, evId);
boolean returnedEv = false;
try {
if (context != null) {
ev.context = context;
}
ev.setPossibleDuplicate(possibleDuplicate);
ev.setVersionTag(entry.versionTag);
// if (needsRouting) {
// FilterProfile fp = rgn.getFilterProfile();
// if (fp != null) {
// FilterInfo fi = fp.getLocalFilterRouting(ev);
// ev.setLocalFilterInfo(fi);
// }
// }
if (entry.filterRouting != null) {
InternalDistributedMember id = rgn.getMyId();
ev.setLocalFilterInfo(entry.filterRouting.getFilterInfo(id));
}
/*
* Setting tailKey for the secondary bucket here. Tail key was update by the primary.
*/
ev.setTailKey(entry.getTailKey());
returnedEv = true;
return ev;
} finally {
if (!returnedEv) {
ev.release();
}
}
}
@Override
protected void basicOperateOnRegion(EntryEventImpl ev, final DistributedRegion rgn) {
for (int i = 0; i < removeAllDataSize; ++i) {
if (removeAllData[i].versionTag != null) {
checkVersionTag(rgn, removeAllData[i].versionTag);
}
}
rgn.syncBulkOp(() -> {
for (int i = 0; i < removeAllDataSize; ++i) {
if (logger.isTraceEnabled()) {
logger.trace("removeAll processing {} with {}", removeAllData[i],
removeAllData[i].versionTag);
}
removeAllData[i].setSender(sender);
doEntryRemove(removeAllData[i], rgn);
}
}, ev.getEventId());
}
@Override
public int getDSFID() {
return REMOVE_ALL_MESSAGE;
}
@Override
public void fromData(DataInput in,
DeserializationContext context) throws IOException, ClassNotFoundException {
super.fromData(in, context);
eventId = context.getDeserializer().readObject(in);
removeAllDataSize = (int) InternalDataSerializer.readUnsignedVL(in);
removeAllData = new RemoveAllEntryData[removeAllDataSize];
if (removeAllDataSize > 0) {
for (int i = 0; i < removeAllDataSize; i++) {
removeAllData[i] = new RemoveAllEntryData(in, eventId, i, context);
}
boolean hasTags = in.readBoolean();
if (hasTags) {
EntryVersionsList versionTags = EntryVersionsList.create(in);
for (int i = 0; i < removeAllDataSize; i++) {
removeAllData[i].versionTag = versionTags.get(i);
}
}
}
if ((flags & HAS_BRIDGE_CONTEXT) != 0) {
this.context = context.getDeserializer().readObject(in);
}
skipCallbacks = (flags & SKIP_CALLBACKS) != 0;
}
@Override
public void toData(DataOutput out,
SerializationContext context) throws IOException {
super.toData(out, context);
context.getSerializer().writeObject(eventId, out);
InternalDataSerializer.writeUnsignedVL(removeAllDataSize, out);
if (removeAllDataSize > 0) {
EntryVersionsList versionTags = new EntryVersionsList(removeAllDataSize);
boolean hasTags = false;
for (int i = 0; i < removeAllDataSize; i++) {
if (!hasTags && removeAllData[i].versionTag != null) {
hasTags = true;
}
VersionTag<?> tag = removeAllData[i].versionTag;
versionTags.add(tag);
removeAllData[i].versionTag = null;
removeAllData[i].serializeTo(out, context);
removeAllData[i].versionTag = tag;
}
out.writeBoolean(hasTags);
if (hasTags) {
InternalDataSerializer.invokeToData(versionTags, out);
}
}
if (this.context != null) {
context.getSerializer().writeObject(this.context, out);
}
}
@Override
protected short computeCompressedShort(short s) {
s = super.computeCompressedShort(s);
if (context != null) {
s |= HAS_BRIDGE_CONTEXT;
}
if (skipCallbacks) {
s |= SKIP_CALLBACKS;
}
return s;
}
public ClientProxyMembershipID getContext() {
return context;
}
public RemoveAllEntryData[] getRemoveAllEntryData() {
return removeAllData;
}
}
}
|
googleapis/google-cloud-java | 36,461 | java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/PairwiseSummarizationQualityInput.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/evaluation_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1;
/**
*
*
* <pre>
* Input for pairwise summarization quality metric.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput}
*/
public final class PairwiseSummarizationQualityInput extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput)
PairwiseSummarizationQualityInputOrBuilder {
private static final long serialVersionUID = 0L;
// Use PairwiseSummarizationQualityInput.newBuilder() to construct.
private PairwiseSummarizationQualityInput(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private PairwiseSummarizationQualityInput() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new PairwiseSummarizationQualityInput();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_PairwiseSummarizationQualityInput_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_PairwiseSummarizationQualityInput_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput.class,
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput.Builder.class);
}
private int bitField0_;
public static final int METRIC_SPEC_FIELD_NUMBER = 1;
private com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec metricSpec_;
/**
*
*
* <pre>
* Required. Spec for pairwise summarization quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec 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 pairwise summarization quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The metricSpec.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec getMetricSpec() {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec.getDefaultInstance()
: metricSpec_;
}
/**
*
*
* <pre>
* Required. Spec for pairwise summarization quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpecOrBuilder
getMetricSpecOrBuilder() {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec.getDefaultInstance()
: metricSpec_;
}
public static final int INSTANCE_FIELD_NUMBER = 2;
private com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance instance_;
/**
*
*
* <pre>
* Required. Pairwise summarization quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance 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. Pairwise summarization quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance getInstance() {
return instance_ == null
? com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance.getDefaultInstance()
: instance_;
}
/**
*
*
* <pre>
* Required. Pairwise summarization quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstanceOrBuilder
getInstanceOrBuilder() {
return instance_ == null
? com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance.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.v1.PairwiseSummarizationQualityInput)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput other =
(com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput) 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.v1.PairwiseSummarizationQualityInput parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput 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.PairwiseSummarizationQualityInput parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput 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.PairwiseSummarizationQualityInput parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput 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.PairwiseSummarizationQualityInput parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput 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.PairwiseSummarizationQualityInput parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput 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.PairwiseSummarizationQualityInput 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.PairwiseSummarizationQualityInput 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.PairwiseSummarizationQualityInput 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 pairwise summarization quality metric.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput)
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInputOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_PairwiseSummarizationQualityInput_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_PairwiseSummarizationQualityInput_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput.class,
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput.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.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_PairwiseSummarizationQualityInput_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput build() {
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput buildPartial() {
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput result =
new com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput 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.v1.PairwiseSummarizationQualityInput) {
return mergeFrom((com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput other) {
if (other
== com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput.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.v1.PairwiseSummarizationQualitySpec metricSpec_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec,
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec.Builder,
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpecOrBuilder>
metricSpecBuilder_;
/**
*
*
* <pre>
* Required. Spec for pairwise summarization quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec 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 pairwise summarization quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The metricSpec.
*/
public com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec getMetricSpec() {
if (metricSpecBuilder_ == null) {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec.getDefaultInstance()
: metricSpec_;
} else {
return metricSpecBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Spec for pairwise summarization quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setMetricSpec(
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec 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 pairwise summarization quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setMetricSpec(
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec.Builder builderForValue) {
if (metricSpecBuilder_ == null) {
metricSpec_ = builderForValue.build();
} else {
metricSpecBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Spec for pairwise summarization quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeMetricSpec(
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec value) {
if (metricSpecBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& metricSpec_ != null
&& metricSpec_
!= com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec
.getDefaultInstance()) {
getMetricSpecBuilder().mergeFrom(value);
} else {
metricSpec_ = value;
}
} else {
metricSpecBuilder_.mergeFrom(value);
}
if (metricSpec_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Spec for pairwise summarization quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec 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 pairwise summarization quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec.Builder
getMetricSpecBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getMetricSpecFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Spec for pairwise summarization quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpecOrBuilder
getMetricSpecOrBuilder() {
if (metricSpecBuilder_ != null) {
return metricSpecBuilder_.getMessageOrBuilder();
} else {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec.getDefaultInstance()
: metricSpec_;
}
}
/**
*
*
* <pre>
* Required. Spec for pairwise summarization quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec,
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec.Builder,
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpecOrBuilder>
getMetricSpecFieldBuilder() {
if (metricSpecBuilder_ == null) {
metricSpecBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec,
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpec.Builder,
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualitySpecOrBuilder>(
getMetricSpec(), getParentForChildren(), isClean());
metricSpec_ = null;
}
return metricSpecBuilder_;
}
private com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance instance_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance,
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance.Builder,
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstanceOrBuilder>
instanceBuilder_;
/**
*
*
* <pre>
* Required. Pairwise summarization quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the instance field is set.
*/
public boolean hasInstance() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. Pairwise summarization quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
public com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance getInstance() {
if (instanceBuilder_ == null) {
return instance_ == null
? com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance
.getDefaultInstance()
: instance_;
} else {
return instanceBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Pairwise summarization quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance value) {
if (instanceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
instance_ = value;
} else {
instanceBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Pairwise summarization quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance.Builder
builderForValue) {
if (instanceBuilder_ == null) {
instance_ = builderForValue.build();
} else {
instanceBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Pairwise summarization quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeInstance(
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance value) {
if (instanceBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& instance_ != null
&& instance_
!= com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance
.getDefaultInstance()) {
getInstanceBuilder().mergeFrom(value);
} else {
instance_ = value;
}
} else {
instanceBuilder_.mergeFrom(value);
}
if (instance_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Pairwise summarization quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance 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. Pairwise summarization quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance.Builder
getInstanceBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getInstanceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Pairwise summarization quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstanceOrBuilder
getInstanceOrBuilder() {
if (instanceBuilder_ != null) {
return instanceBuilder_.getMessageOrBuilder();
} else {
return instance_ == null
? com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance
.getDefaultInstance()
: instance_;
}
}
/**
*
*
* <pre>
* Required. Pairwise summarization quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance,
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance.Builder,
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstanceOrBuilder>
getInstanceFieldBuilder() {
if (instanceBuilder_ == null) {
instanceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance,
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstance.Builder,
com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInstanceOrBuilder>(
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.v1.PairwiseSummarizationQualityInput)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput)
private static final com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput();
}
public static com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<PairwiseSummarizationQualityInput> PARSER =
new com.google.protobuf.AbstractParser<PairwiseSummarizationQualityInput>() {
@java.lang.Override
public PairwiseSummarizationQualityInput 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<PairwiseSummarizationQualityInput> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<PairwiseSummarizationQualityInput> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.PairwiseSummarizationQualityInput
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,461 | java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/QuestionAnsweringCorrectnessInput.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/evaluation_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1;
/**
*
*
* <pre>
* Input for question answering correctness metric.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput}
*/
public final class QuestionAnsweringCorrectnessInput extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput)
QuestionAnsweringCorrectnessInputOrBuilder {
private static final long serialVersionUID = 0L;
// Use QuestionAnsweringCorrectnessInput.newBuilder() to construct.
private QuestionAnsweringCorrectnessInput(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private QuestionAnsweringCorrectnessInput() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new QuestionAnsweringCorrectnessInput();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_QuestionAnsweringCorrectnessInput_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_QuestionAnsweringCorrectnessInput_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput.class,
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput.Builder.class);
}
private int bitField0_;
public static final int METRIC_SPEC_FIELD_NUMBER = 1;
private com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec metricSpec_;
/**
*
*
* <pre>
* Required. Spec for question answering correctness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec 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 correctness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The metricSpec.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec getMetricSpec() {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec.getDefaultInstance()
: metricSpec_;
}
/**
*
*
* <pre>
* Required. Spec for question answering correctness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpecOrBuilder
getMetricSpecOrBuilder() {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec.getDefaultInstance()
: metricSpec_;
}
public static final int INSTANCE_FIELD_NUMBER = 2;
private com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance instance_;
/**
*
*
* <pre>
* Required. Question answering correctness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance 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 correctness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance getInstance() {
return instance_ == null
? com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance.getDefaultInstance()
: instance_;
}
/**
*
*
* <pre>
* Required. Question answering correctness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstanceOrBuilder
getInstanceOrBuilder() {
return instance_ == null
? com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance.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.v1.QuestionAnsweringCorrectnessInput)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput other =
(com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput) 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.v1.QuestionAnsweringCorrectnessInput parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput 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.QuestionAnsweringCorrectnessInput parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput 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.QuestionAnsweringCorrectnessInput parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput 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.QuestionAnsweringCorrectnessInput parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput 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.QuestionAnsweringCorrectnessInput parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput 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.QuestionAnsweringCorrectnessInput 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.QuestionAnsweringCorrectnessInput 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.QuestionAnsweringCorrectnessInput 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 correctness metric.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput)
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInputOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_QuestionAnsweringCorrectnessInput_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_QuestionAnsweringCorrectnessInput_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput.class,
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput.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.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_QuestionAnsweringCorrectnessInput_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput build() {
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput buildPartial() {
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput result =
new com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput 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.v1.QuestionAnsweringCorrectnessInput) {
return mergeFrom((com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput other) {
if (other
== com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput.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.v1.QuestionAnsweringCorrectnessSpec metricSpec_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec,
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec.Builder,
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpecOrBuilder>
metricSpecBuilder_;
/**
*
*
* <pre>
* Required. Spec for question answering correctness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec 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 correctness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The metricSpec.
*/
public com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec getMetricSpec() {
if (metricSpecBuilder_ == null) {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec.getDefaultInstance()
: metricSpec_;
} else {
return metricSpecBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Spec for question answering correctness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setMetricSpec(
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec 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 correctness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setMetricSpec(
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec.Builder builderForValue) {
if (metricSpecBuilder_ == null) {
metricSpec_ = builderForValue.build();
} else {
metricSpecBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Spec for question answering correctness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeMetricSpec(
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec value) {
if (metricSpecBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& metricSpec_ != null
&& metricSpec_
!= com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec
.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 correctness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec 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 correctness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec.Builder
getMetricSpecBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getMetricSpecFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Spec for question answering correctness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpecOrBuilder
getMetricSpecOrBuilder() {
if (metricSpecBuilder_ != null) {
return metricSpecBuilder_.getMessageOrBuilder();
} else {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec.getDefaultInstance()
: metricSpec_;
}
}
/**
*
*
* <pre>
* Required. Spec for question answering correctness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec,
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec.Builder,
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpecOrBuilder>
getMetricSpecFieldBuilder() {
if (metricSpecBuilder_ == null) {
metricSpecBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec,
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpec.Builder,
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessSpecOrBuilder>(
getMetricSpec(), getParentForChildren(), isClean());
metricSpec_ = null;
}
return metricSpecBuilder_;
}
private com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance instance_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance,
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance.Builder,
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstanceOrBuilder>
instanceBuilder_;
/**
*
*
* <pre>
* Required. Question answering correctness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance 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 correctness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
public com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance getInstance() {
if (instanceBuilder_ == null) {
return instance_ == null
? com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance
.getDefaultInstance()
: instance_;
} else {
return instanceBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Question answering correctness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance 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 correctness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance.Builder
builderForValue) {
if (instanceBuilder_ == null) {
instance_ = builderForValue.build();
} else {
instanceBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Question answering correctness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeInstance(
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance value) {
if (instanceBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& instance_ != null
&& instance_
!= com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance
.getDefaultInstance()) {
getInstanceBuilder().mergeFrom(value);
} else {
instance_ = value;
}
} else {
instanceBuilder_.mergeFrom(value);
}
if (instance_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Question answering correctness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance 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 correctness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance.Builder
getInstanceBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getInstanceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Question answering correctness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstanceOrBuilder
getInstanceOrBuilder() {
if (instanceBuilder_ != null) {
return instanceBuilder_.getMessageOrBuilder();
} else {
return instance_ == null
? com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance
.getDefaultInstance()
: instance_;
}
}
/**
*
*
* <pre>
* Required. Question answering correctness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance,
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance.Builder,
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstanceOrBuilder>
getInstanceFieldBuilder() {
if (instanceBuilder_ == null) {
instanceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance,
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstance.Builder,
com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInstanceOrBuilder>(
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.v1.QuestionAnsweringCorrectnessInput)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput)
private static final com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput();
}
public static com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<QuestionAnsweringCorrectnessInput> PARSER =
new com.google.protobuf.AbstractParser<QuestionAnsweringCorrectnessInput>() {
@java.lang.Override
public QuestionAnsweringCorrectnessInput 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<QuestionAnsweringCorrectnessInput> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<QuestionAnsweringCorrectnessInput> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.QuestionAnsweringCorrectnessInput
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,461 | java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/QuestionAnsweringHelpfulnessInput.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/evaluation_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1;
/**
*
*
* <pre>
* Input for question answering helpfulness metric.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput}
*/
public final class QuestionAnsweringHelpfulnessInput extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput)
QuestionAnsweringHelpfulnessInputOrBuilder {
private static final long serialVersionUID = 0L;
// Use QuestionAnsweringHelpfulnessInput.newBuilder() to construct.
private QuestionAnsweringHelpfulnessInput(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private QuestionAnsweringHelpfulnessInput() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new QuestionAnsweringHelpfulnessInput();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_QuestionAnsweringHelpfulnessInput_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_QuestionAnsweringHelpfulnessInput_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput.class,
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput.Builder.class);
}
private int bitField0_;
public static final int METRIC_SPEC_FIELD_NUMBER = 1;
private com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec metricSpec_;
/**
*
*
* <pre>
* Required. Spec for question answering helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec 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 helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The metricSpec.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec getMetricSpec() {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec.getDefaultInstance()
: metricSpec_;
}
/**
*
*
* <pre>
* Required. Spec for question answering helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpecOrBuilder
getMetricSpecOrBuilder() {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec.getDefaultInstance()
: metricSpec_;
}
public static final int INSTANCE_FIELD_NUMBER = 2;
private com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance instance_;
/**
*
*
* <pre>
* Required. Question answering helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance 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 helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance getInstance() {
return instance_ == null
? com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance.getDefaultInstance()
: instance_;
}
/**
*
*
* <pre>
* Required. Question answering helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstanceOrBuilder
getInstanceOrBuilder() {
return instance_ == null
? com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance.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.v1.QuestionAnsweringHelpfulnessInput)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput other =
(com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput) 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.v1.QuestionAnsweringHelpfulnessInput parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput 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.QuestionAnsweringHelpfulnessInput parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput 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.QuestionAnsweringHelpfulnessInput parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput 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.QuestionAnsweringHelpfulnessInput parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput 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.QuestionAnsweringHelpfulnessInput parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput 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.QuestionAnsweringHelpfulnessInput 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.QuestionAnsweringHelpfulnessInput 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.QuestionAnsweringHelpfulnessInput 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 helpfulness metric.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput)
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInputOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_QuestionAnsweringHelpfulnessInput_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_QuestionAnsweringHelpfulnessInput_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput.class,
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput.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.v1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1_QuestionAnsweringHelpfulnessInput_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput build() {
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput buildPartial() {
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput result =
new com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput 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.v1.QuestionAnsweringHelpfulnessInput) {
return mergeFrom((com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput other) {
if (other
== com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput.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.v1.QuestionAnsweringHelpfulnessSpec metricSpec_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec,
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec.Builder,
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpecOrBuilder>
metricSpecBuilder_;
/**
*
*
* <pre>
* Required. Spec for question answering helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec 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 helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The metricSpec.
*/
public com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec getMetricSpec() {
if (metricSpecBuilder_ == null) {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec.getDefaultInstance()
: metricSpec_;
} else {
return metricSpecBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Spec for question answering helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setMetricSpec(
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec 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 helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setMetricSpec(
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec.Builder builderForValue) {
if (metricSpecBuilder_ == null) {
metricSpec_ = builderForValue.build();
} else {
metricSpecBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Spec for question answering helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeMetricSpec(
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec value) {
if (metricSpecBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& metricSpec_ != null
&& metricSpec_
!= com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec
.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 helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec 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 helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec.Builder
getMetricSpecBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getMetricSpecFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Spec for question answering helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpecOrBuilder
getMetricSpecOrBuilder() {
if (metricSpecBuilder_ != null) {
return metricSpecBuilder_.getMessageOrBuilder();
} else {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec.getDefaultInstance()
: metricSpec_;
}
}
/**
*
*
* <pre>
* Required. Spec for question answering helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec,
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec.Builder,
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpecOrBuilder>
getMetricSpecFieldBuilder() {
if (metricSpecBuilder_ == null) {
metricSpecBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec,
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpec.Builder,
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessSpecOrBuilder>(
getMetricSpec(), getParentForChildren(), isClean());
metricSpec_ = null;
}
return metricSpecBuilder_;
}
private com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance instance_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance,
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance.Builder,
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstanceOrBuilder>
instanceBuilder_;
/**
*
*
* <pre>
* Required. Question answering helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance 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 helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
public com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance getInstance() {
if (instanceBuilder_ == null) {
return instance_ == null
? com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance
.getDefaultInstance()
: instance_;
} else {
return instanceBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Question answering helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance 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 helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance.Builder
builderForValue) {
if (instanceBuilder_ == null) {
instance_ = builderForValue.build();
} else {
instanceBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Question answering helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeInstance(
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance value) {
if (instanceBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& instance_ != null
&& instance_
!= com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance
.getDefaultInstance()) {
getInstanceBuilder().mergeFrom(value);
} else {
instance_ = value;
}
} else {
instanceBuilder_.mergeFrom(value);
}
if (instance_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Question answering helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance 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 helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance.Builder
getInstanceBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getInstanceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Question answering helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstanceOrBuilder
getInstanceOrBuilder() {
if (instanceBuilder_ != null) {
return instanceBuilder_.getMessageOrBuilder();
} else {
return instance_ == null
? com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance
.getDefaultInstance()
: instance_;
}
}
/**
*
*
* <pre>
* Required. Question answering helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance,
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance.Builder,
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstanceOrBuilder>
getInstanceFieldBuilder() {
if (instanceBuilder_ == null) {
instanceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance,
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstance.Builder,
com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInstanceOrBuilder>(
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.v1.QuestionAnsweringHelpfulnessInput)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput)
private static final com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput();
}
public static com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<QuestionAnsweringHelpfulnessInput> PARSER =
new com.google.protobuf.AbstractParser<QuestionAnsweringHelpfulnessInput>() {
@java.lang.Override
public QuestionAnsweringHelpfulnessInput 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<QuestionAnsweringHelpfulnessInput> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<QuestionAnsweringHelpfulnessInput> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.QuestionAnsweringHelpfulnessInput
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/phoenix | 36,451 | phoenix-core-client/src/main/java/org/apache/phoenix/query/QueryServices.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.phoenix.query;
import java.util.concurrent.ThreadPoolExecutor;
import net.jcip.annotations.Immutable;
import org.apache.phoenix.iterate.SpoolTooBigToDiskException;
import org.apache.phoenix.memory.MemoryManager;
import org.apache.phoenix.optimize.QueryOptimizer;
import org.apache.phoenix.util.ReadOnlyProps;
import org.apache.phoenix.util.SQLCloseable;
/**
* Interface to group together services needed during querying. The parameters that may be set in
* {@link org.apache.hadoop.conf.Configuration} are documented here:
* https://github.com/forcedotcom/phoenix/wiki/Tuning
* @since 0.1
*/
@Immutable
public interface QueryServices extends SQLCloseable {
public static final String KEEP_ALIVE_MS_ATTRIB = "phoenix.query.keepAliveMs";
public static final String THREAD_POOL_SIZE_ATTRIB = "phoenix.query.threadPoolSize";
public static final String QUEUE_SIZE_ATTRIB = "phoenix.query.queueSize";
public static final String THREAD_TIMEOUT_MS_ATTRIB = "phoenix.query.timeoutMs";
public static final String SERVER_SPOOL_THRESHOLD_BYTES_ATTRIB =
"phoenix.query.server.spoolThresholdBytes";
public static final String CLIENT_SPOOL_THRESHOLD_BYTES_ATTRIB =
"phoenix.query.client.spoolThresholdBytes";
public static final String CLIENT_ORDERBY_SPOOLING_ENABLED_ATTRIB =
"phoenix.query.client.orderBy.spooling.enabled";
public static final String CLIENT_JOIN_SPOOLING_ENABLED_ATTRIB =
"phoenix.query.client.join.spooling.enabled";
public static final String SERVER_ORDERBY_SPOOLING_ENABLED_ATTRIB =
"phoenix.query.server.orderBy.spooling.enabled";
@Deprecated
public static final String HBASE_CLIENT_KEYTAB = "hbase.myclient.keytab";
@Deprecated
public static final String HBASE_CLIENT_PRINCIPAL = "hbase.myclient.principal";
String QUERY_SERVICES_NAME = "phoenix.query.services.name";
public static final String SPOOL_DIRECTORY = "phoenix.spool.directory";
public static final String AUTO_COMMIT_ATTRIB = "phoenix.connection.autoCommit";
// consistency configuration setting
public static final String CONSISTENCY_ATTRIB = "phoenix.connection.consistency";
public static final String SCHEMA_ATTRIB = "phoenix.connection.schema";
public static final String IS_NAMESPACE_MAPPING_ENABLED =
"phoenix.schema.isNamespaceMappingEnabled";
public static final String IS_SYSTEM_TABLE_MAPPED_TO_NAMESPACE =
"phoenix.schema.mapSystemTablesToNamespace";
// joni byte regex engine setting
public static final String USE_BYTE_BASED_REGEX_ATTRIB = "phoenix.regex.byteBased";
public static final String DRIVER_SHUTDOWN_TIMEOUT_MS = "phoenix.shutdown.timeoutMs";
public static final String CLIENT_INDEX_ASYNC_THRESHOLD = "phoenix.index.async.threshold";
/**
* max size to spool the the result into ${java.io.tmpdir}/ResultSpoolerXXX.bin if
* QueryServices#SPOOL_THRESHOLD_BYTES_ATTRIB is reached.
* <p>
* default is unlimited(-1)
* <p>
* if the threshold is reached, a {@link SpoolTooBigToDiskException } will be thrown
*/
public static final String MAX_SPOOL_TO_DISK_BYTES_ATTRIB = "phoenix.query.maxSpoolToDiskBytes";
/**
* Number of records to read per chunk when streaming records of a basic scan.
*/
public static final String SCAN_RESULT_CHUNK_SIZE = "phoenix.query.scanResultChunkSize";
public static final String MAX_MEMORY_PERC_ATTRIB = "phoenix.query.maxGlobalMemoryPercentage";
public static final String MAX_TENANT_MEMORY_PERC_ATTRIB =
"phoenix.query.maxTenantMemoryPercentage";
public static final String MAX_SERVER_CACHE_SIZE_ATTRIB = "phoenix.query.maxServerCacheBytes";
public static final String APPLY_TIME_ZONE_DISPLACMENT_ATTRIB =
"phoenix.query.applyTimeZoneDisplacement";
public static final String DATE_FORMAT_TIMEZONE_ATTRIB = "phoenix.query.dateFormatTimeZone";
public static final String DATE_FORMAT_ATTRIB = "phoenix.query.dateFormat";
public static final String TIME_FORMAT_ATTRIB = "phoenix.query.timeFormat";
public static final String TIMESTAMP_FORMAT_ATTRIB = "phoenix.query.timestampFormat";
public static final String NUMBER_FORMAT_ATTRIB = "phoenix.query.numberFormat";
public static final String CALL_QUEUE_ROUND_ROBIN_ATTRIB = "ipc.server.callqueue.roundrobin";
public static final String SCAN_CACHE_SIZE_ATTRIB = "hbase.client.scanner.caching";
public static final String MAX_MUTATION_SIZE_ATTRIB = "phoenix.mutate.maxSize";
public static final String MAX_MUTATION_SIZE_BYTES_ATTRIB = "phoenix.mutate.maxSizeBytes";
public static final String HBASE_CLIENT_KEYVALUE_MAXSIZE = "hbase.client.keyvalue.maxsize";
public static final String MUTATE_BATCH_SIZE_ATTRIB = "phoenix.mutate.batchSize";
public static final String MUTATE_BATCH_SIZE_BYTES_ATTRIB = "phoenix.mutate.batchSizeBytes";
public static final String MAX_SERVER_CACHE_TIME_TO_LIVE_MS_ATTRIB =
"phoenix.coprocessor.maxServerCacheTimeToLiveMs";
public static final String MAX_SERVER_CACHE_PERSISTENCE_TIME_TO_LIVE_MS_ATTRIB =
"phoenix.coprocessor.maxServerCachePersistenceTimeToLiveMs";
@Deprecated // Use FORCE_ROW_KEY_ORDER instead.
public static final String ROW_KEY_ORDER_SALTED_TABLE_ATTRIB =
"phoenix.query.rowKeyOrderSaltedTable";
public static final String USE_INDEXES_ATTRIB = "phoenix.query.useIndexes";
@Deprecated // use the IMMUTABLE keyword while creating the table
public static final String IMMUTABLE_ROWS_ATTRIB = "phoenix.mutate.immutableRows";
public static final String INDEX_MUTATE_BATCH_SIZE_THRESHOLD_ATTRIB =
"phoenix.index.mutableBatchSizeThreshold";
public static final String DROP_METADATA_ATTRIB = "phoenix.schema.dropMetaData";
public static final String GROUPBY_SPILLABLE_ATTRIB = "phoenix.groupby.spillable";
public static final String GROUPBY_SPILL_FILES_ATTRIB = "phoenix.groupby.spillFiles";
public static final String GROUPBY_MAX_CACHE_SIZE_ATTRIB = "phoenix.groupby.maxCacheSize";
public static final String GROUPBY_ESTIMATED_DISTINCT_VALUES_ATTRIB =
"phoenix.groupby.estimatedDistinctValues";
public static final String AGGREGATE_CHUNK_SIZE_INCREASE_ATTRIB =
"phoenix.aggregate.chunk_size_increase";
public static final String CALL_QUEUE_PRODUCER_ATTRIB_NAME = "CALL_QUEUE_PRODUCER";
public static final String MASTER_INFO_PORT_ATTRIB = "hbase.master.info.port";
public static final String REGIONSERVER_INFO_PORT_ATTRIB = "hbase.regionserver.info.port";
public static final String HBASE_CLIENT_SCANNER_TIMEOUT_ATTRIB =
"hbase.client.scanner.timeout.period";
public static final String RPC_TIMEOUT_ATTRIB = "hbase.rpc.timeout";
public static final String DYNAMIC_JARS_DIR_KEY = "hbase.dynamic.jars.dir";
@Deprecated // Use HConstants directly
public static final String ZOOKEEPER_QUORUM_ATTRIB = "hbase.zookeeper.quorum";
@Deprecated // Use HConstants directly
public static final String ZOOKEEPER_PORT_ATTRIB = "hbase.zookeeper.property.clientPort";
@Deprecated // Use HConstants directly
public static final String ZOOKEEPER_ROOT_NODE_ATTRIB = "zookeeper.znode.parent";
public static final String DISTINCT_VALUE_COMPRESS_THRESHOLD_ATTRIB =
"phoenix.distinct.value.compress.threshold";
public static final String SEQUENCE_CACHE_SIZE_ATTRIB = "phoenix.sequence.cacheSize";
public static final String MAX_SERVER_METADATA_CACHE_TIME_TO_LIVE_MS_ATTRIB =
"phoenix.coprocessor.maxMetaDataCacheTimeToLiveMs";
public static final String MAX_SERVER_METADATA_CACHE_SIZE_ATTRIB =
"phoenix.coprocessor.maxMetaDataCacheSize";
public static final String MAX_CLIENT_METADATA_CACHE_SIZE_ATTRIB =
"phoenix.client.maxMetaDataCacheSize";
public static final String HA_GROUP_NAME_ATTRIB = "phoenix.ha.group";
public static final String AUTO_UPGRADE_WHITELIST_ATTRIB = "phoenix.client.autoUpgradeWhiteList";
// Mainly for testing to force spilling
public static final String MAX_MEMORY_SIZE_ATTRIB = "phoenix.query.maxGlobalMemorySize";
// The following config settings is to deal with SYSTEM.CATALOG moves(PHOENIX-916) among region
// servers
public static final String CLOCK_SKEW_INTERVAL_ATTRIB = "phoenix.clock.skew.interval";
// A master switch if to enable auto rebuild an index which failed to be updated previously
public static final String INDEX_FAILURE_HANDLING_REBUILD_ATTRIB =
"phoenix.index.failure.handling.rebuild";
public static final String INDEX_FAILURE_HANDLING_REBUILD_PERIOD =
"phoenix.index.failure.handling.rebuild.period";
public static final String INDEX_REBUILD_QUERY_TIMEOUT_ATTRIB =
"phoenix.index.rebuild.query.timeout";
public static final String INDEX_REBUILD_RPC_TIMEOUT_ATTRIB = "phoenix.index.rebuild.rpc.timeout";
public static final String INDEX_REBUILD_CLIENT_SCANNER_TIMEOUT_ATTRIB =
"phoenix.index.rebuild.client.scanner.timeout";
public static final String INDEX_REBUILD_RPC_RETRIES_COUNTER =
"phoenix.index.rebuild.rpc.retries.counter";
public static final String INDEX_REBUILD_RPC_RETRY_PAUSE_TIME =
"phoenix.index.rebuild.rpc.retry.pause";
// Time interval to check if there is an index needs to be rebuild
public static final String INDEX_FAILURE_HANDLING_REBUILD_INTERVAL_ATTRIB =
"phoenix.index.failure.handling.rebuild.interval";
public static final String INDEX_REBUILD_TASK_INITIAL_DELAY =
"phoenix.index.rebuild.task.initial.delay";
public static final String START_TRUNCATE_TASK_DELAY = "phoenix.start.truncate.task.delay";
public static final String INDEX_FAILURE_HANDLING_REBUILD_NUMBER_OF_BATCHES_PER_TABLE =
"phoenix.index.rebuild.batch.perTable";
// If index disable timestamp is older than this threshold, then index rebuild task won't attempt
// to rebuild it
public static final String INDEX_REBUILD_DISABLE_TIMESTAMP_THRESHOLD =
"phoenix.index.rebuild.disabletimestamp.threshold";
// threshold number of ms an index has been in PENDING_DISABLE, beyond which we consider it
// disabled
public static final String INDEX_PENDING_DISABLE_THRESHOLD =
"phoenix.index.pending.disable.threshold";
// Block writes to data table when index write fails
public static final String INDEX_FAILURE_BLOCK_WRITE = "phoenix.index.failure.block.write";
public static final String INDEX_FAILURE_DISABLE_INDEX = "phoenix.index.failure.disable.index";
public static final String INDEX_FAILURE_THROW_EXCEPTION_ATTRIB =
"phoenix.index.failure.throw.exception";
public static final String INDEX_FAILURE_KILL_SERVER =
"phoenix.index.failure.unhandled.killserver";
public static final String INDEX_CREATE_DEFAULT_STATE = "phoenix.index.create.default.state";
// Index will be partially re-built from index disable time stamp - following overlap time
@Deprecated
public static final String INDEX_FAILURE_HANDLING_REBUILD_OVERLAP_TIME_ATTRIB =
"phoenix.index.failure.handling.rebuild.overlap.time";
public static final String INDEX_FAILURE_HANDLING_REBUILD_OVERLAP_BACKWARD_TIME_ATTRIB =
"phoenix.index.failure.handling.rebuild.overlap.backward.time";
public static final String INDEX_FAILURE_HANDLING_REBUILD_OVERLAP_FORWARD_TIME_ATTRIB =
"phoenix.index.failure.handling.rebuild.overlap.forward.time";
public static final String INDEX_PRIOIRTY_ATTRIB = "phoenix.index.rpc.priority";
public static final String METADATA_PRIOIRTY_ATTRIB = "phoenix.metadata.rpc.priority";
public static final String SERVER_SIDE_PRIOIRTY_ATTRIB = "phoenix.serverside.rpc.priority";
String INVALIDATE_METADATA_CACHE_PRIORITY_ATTRIB =
"phoenix.invalidate.metadata.cache.rpc.priority";
public static final String ALLOW_LOCAL_INDEX_ATTRIB = "phoenix.index.allowLocalIndex";
// Retries when doing server side writes to SYSTEM.CATALOG
public static final String METADATA_WRITE_RETRIES_NUMBER = "phoenix.metadata.rpc.retries.number";
public static final String METADATA_WRITE_RETRY_PAUSE = "phoenix.metadata.rpc.pause";
// Config parameters for for configuring tracing
public static final String TRACING_FREQ_ATTRIB = "phoenix.trace.frequency";
public static final String TRACING_PAGE_SIZE_ATTRIB = "phoenix.trace.read.pagesize";
public static final String TRACING_PROBABILITY_THRESHOLD_ATTRIB =
"phoenix.trace.probability.threshold";
public static final String TRACING_STATS_TABLE_NAME_ATTRIB = "phoenix.trace.statsTableName";
public static final String TRACING_CUSTOM_ANNOTATION_ATTRIB_PREFIX =
"phoenix.trace.custom.annotation.";
public static final String TRACING_ENABLED = "phoenix.trace.enabled";
public static final String TRACING_BATCH_SIZE = "phoenix.trace.batchSize";
public static final String TRACING_THREAD_POOL_SIZE = "phoenix.trace.threadPoolSize";
public static final String TRACING_TRACE_BUFFER_SIZE = "phoenix.trace.traceBufferSize";
public static final String USE_REVERSE_SCAN_ATTRIB = "phoenix.query.useReverseScan";
// Config parameters for stats collection
public static final String STATS_UPDATE_FREQ_MS_ATTRIB = "phoenix.stats.updateFrequency";
public static final String MIN_STATS_UPDATE_FREQ_MS_ATTRIB = "phoenix.stats.minUpdateFrequency";
public static final String STATS_GUIDEPOST_WIDTH_BYTES_ATTRIB = "phoenix.stats.guidepost.width";
public static final String STATS_GUIDEPOST_PER_REGION_ATTRIB =
"phoenix.stats.guidepost.per.region";
public static final String STATS_USE_CURRENT_TIME_ATTRIB = "phoenix.stats.useCurrentTime";
public static final String RUN_UPDATE_STATS_ASYNC = "phoenix.update.stats.command.async";
public static final String STATS_SERVER_POOL_SIZE = "phoenix.stats.pool.size";
public static final String COMMIT_STATS_ASYNC = "phoenix.stats.commit.async";
// Maximum size in bytes taken up by cached table stats in the client
public static final String STATS_MAX_CACHE_SIZE = "phoenix.stats.cache.maxSize";
// The size of the thread pool used for refreshing cached table stats in stats client cache
public static final String STATS_CACHE_THREAD_POOL_SIZE = "phoenix.stats.cache.threadPoolSize";
public static final String LOG_SALT_BUCKETS_ATTRIB = "phoenix.log.saltBuckets";
public static final String SEQUENCE_SALT_BUCKETS_ATTRIB = "phoenix.sequence.saltBuckets";
public static final String COPROCESSOR_PRIORITY_ATTRIB = "phoenix.coprocessor.priority";
public static final String EXPLAIN_CHUNK_COUNT_ATTRIB = "phoenix.explain.displayChunkCount";
public static final String EXPLAIN_ROW_COUNT_ATTRIB = "phoenix.explain.displayRowCount";
public static final String ALLOW_ONLINE_TABLE_SCHEMA_UPDATE = "hbase.online.schema.update.enable";
public static final String NUM_RETRIES_FOR_SCHEMA_UPDATE_CHECK = "phoenix.schema.change.retries";
public static final String DELAY_FOR_SCHEMA_UPDATE_CHECK = "phoenix.schema.change.delay";
public static final String DEFAULT_STORE_NULLS_ATTRIB = "phoenix.table.default.store.nulls";
public static final String DEFAULT_TABLE_ISTRANSACTIONAL_ATTRIB =
"phoenix.table.istransactional.default";
public static final String DEFAULT_TRANSACTION_PROVIDER_ATTRIB =
"phoenix.table.transaction.provider.default";
public static final String GLOBAL_METRICS_ENABLED = "phoenix.query.global.metrics.enabled";
public static final String TABLE_LEVEL_METRICS_ENABLED =
"phoenix.monitoring.tableMetrics.enabled";
public static final String METRIC_PUBLISHER_ENABLED =
"phoenix.monitoring.metricsPublisher.enabled";
public static final String METRIC_PUBLISHER_CLASS_NAME =
"phoenix.monitoring.metricProvider.className";
public static final String ALLOWED_LIST_FOR_TABLE_LEVEL_METRICS =
"phoenix.monitoring.allowedTableNames.list";
// Tag Name to determine the Phoenix Client Type
public static final String CLIENT_METRICS_TAG = "phoenix.client.metrics.tag";
// Transaction related configs
public static final String TRANSACTIONS_ENABLED = "phoenix.transactions.enabled";
// Controls whether or not uncommitted data is automatically sent to HBase
// at the end of a statement execution when transaction state is passed through.
public static final String AUTO_FLUSH_ATTRIB = "phoenix.transactions.autoFlush";
// rpc queue configs
public static final String INDEX_HANDLER_COUNT_ATTRIB = "phoenix.rpc.index.handler.count";
public static final String METADATA_HANDLER_COUNT_ATTRIB = "phoenix.rpc.metadata.handler.count";
public static final String SERVER_SIDE_HANDLER_COUNT_ATTRIB =
"phoenix.rpc.serverside.handler.count";
String INVALIDATE_CACHE_HANDLER_COUNT_ATTRIB = "phoenix.rpc.invalidate.cache.handler.count";
public static final String FORCE_ROW_KEY_ORDER_ATTRIB = "phoenix.query.force.rowkeyorder";
public static final String ALLOW_USER_DEFINED_FUNCTIONS_ATTRIB =
"phoenix.functions.allowUserDefinedFunctions";
public static final String COLLECT_REQUEST_LEVEL_METRICS =
"phoenix.query.request.metrics.enabled";
public static final String ALLOW_VIEWS_ADD_NEW_CF_BASE_TABLE =
"phoenix.view.allowNewColumnFamily";
public static final String RETURN_SEQUENCE_VALUES_ATTRIB = "phoenix.sequence.returnValues";
public static final String EXTRA_JDBC_ARGUMENTS_ATTRIB = "phoenix.jdbc.extra.arguments";
public static final String MAX_VERSIONS_TRANSACTIONAL_ATTRIB = "phoenix.transactions.maxVersions";
// metadata configs
public static final String DEFAULT_SYSTEM_KEEP_DELETED_CELLS_ATTRIB =
"phoenix.system.default.keep.deleted.cells";
public static final String DEFAULT_SYSTEM_MAX_VERSIONS_ATTRIB =
"phoenix.system.default.max.versions";
public static final String RENEW_LEASE_ENABLED = "phoenix.scanner.lease.renew.enabled";
public static final String RUN_RENEW_LEASE_FREQUENCY_INTERVAL_MILLISECONDS =
"phoenix.scanner.lease.renew.interval";
public static final String RENEW_LEASE_THRESHOLD_MILLISECONDS = "phoenix.scanner.lease.threshold";
public static final String RENEW_LEASE_THREAD_POOL_SIZE = "phoenix.scanner.lease.pool.size";
public static final String HCONNECTION_POOL_CORE_SIZE = "hbase.hconnection.threads.core";
public static final String HCONNECTION_POOL_MAX_SIZE = "hbase.hconnection.threads.max";
public static final String HTABLE_MAX_THREADS = "hbase.htable.threads.max";
// time to wait before running second index population upsert select (so that any pending batches
// of rows on region server are also written to index)
public static final String INDEX_POPULATION_SLEEP_TIME = "phoenix.index.population.wait.time";
public static final String LOCAL_INDEX_CLIENT_UPGRADE_ATTRIB = "phoenix.client.localIndexUpgrade";
public static final String LIMITED_QUERY_SERIAL_THRESHOLD =
"phoenix.limited.query.serial.threshold";
// currently BASE64 and ASCII is supported
public static final String UPLOAD_BINARY_DATA_TYPE_ENCODING =
"phoenix.upload.binaryDataType.encoding";
// Toggle for server-written updates to SYSTEM.CATALOG
public static final String PHOENIX_ACLS_ENABLED = "phoenix.acls.enabled";
public static final String INDEX_ASYNC_BUILD_ENABLED = "phoenix.index.async.build.enabled";
public static final String MAX_INDEXES_PER_TABLE = "phoenix.index.maxIndexesPerTable";
public static final String CLIENT_CACHE_ENCODING = "phoenix.table.client.cache.encoding";
public static final String AUTO_UPGRADE_ENABLED = "phoenix.autoupgrade.enabled";
public static final String CLIENT_CONNECTION_CACHE_MAX_DURATION_MILLISECONDS =
"phoenix.client.connection.max.duration";
// max number of connections from a single client to a single cluster. 0 is unlimited.
public static final String CLIENT_CONNECTION_MAX_ALLOWED_CONNECTIONS =
"phoenix.client.connection.max.allowed.connections";
// max number of connections from a single client to a single cluster. 0 is unlimited.
public static final String INTERNAL_CONNECTION_MAX_ALLOWED_CONNECTIONS =
"phoenix.internal.connection.max.allowed.connections";
public static final String CONNECTION_ACTIVITY_LOGGING_ENABLED =
"phoenix.connection.activity.logging.enabled";
String CONNECTION_EXPLAIN_PLAN_LOGGING_ENABLED =
"phoenix.connection.activity.logging.explain.plan.enabled";
public static final String CONNECTION_ACTIVITY_LOGGING_INTERVAL =
"phoenix.connection.activity.logging.interval";
public static final String DEFAULT_COLUMN_ENCODED_BYTES_ATRRIB =
"phoenix.default.column.encoded.bytes.attrib";
public static final String DEFAULT_IMMUTABLE_STORAGE_SCHEME_ATTRIB =
"phoenix.default.immutable.storage.scheme";
public static final String DEFAULT_MULTITENANT_IMMUTABLE_STORAGE_SCHEME_ATTRIB =
"phoenix.default.multitenant.immutable.storage.scheme";
public static final String STATS_COLLECTION_ENABLED = "phoenix.stats.collection.enabled";
public static final String USE_STATS_FOR_PARALLELIZATION = "phoenix.use.stats.parallelization";
// whether to enable server side RS -> RS calls for upsert select statements
public static final String ENABLE_SERVER_UPSERT_SELECT =
"phoenix.client.enable.server.upsert.select";
public static final String PROPERTY_POLICY_PROVIDER_ENABLED =
"phoenix.property.policy.provider.enabled";
// whether to trigger mutations on the server at all (UPSERT/DELETE or DELETE FROM)
public static final String ENABLE_SERVER_SIDE_DELETE_MUTATIONS =
"phoenix.client.enable.server.delete.mutations";
public static final String ENABLE_SERVER_SIDE_UPSERT_MUTATIONS =
"phoenix.client.enable.server.upsert.mutations";
// Update Cache Frequency default config attribute
public static final String DEFAULT_UPDATE_CACHE_FREQUENCY_ATRRIB =
"phoenix.default.update.cache.frequency";
// Update Cache Frequency for indexes in PENDING_DISABLE state
public static final String UPDATE_CACHE_FREQUENCY_FOR_PENDING_DISABLED_INDEX =
"phoenix.update.cache.frequency.pending.disable.index";
// whether to validate last ddl timestamps during client operations
public static final String LAST_DDL_TIMESTAMP_VALIDATION_ENABLED =
"phoenix.ddl.timestamp.validation.enabled";
// Whether to enable cost-based-decision in the query optimizer
public static final String COST_BASED_OPTIMIZER_ENABLED = "phoenix.costbased.optimizer.enabled";
public static final String SMALL_SCAN_THRESHOLD_ATTRIB = "phoenix.query.smallScanThreshold";
public static final String WILDCARD_QUERY_DYNAMIC_COLS_ATTRIB =
"phoenix.query.wildcard.dynamicColumns";
public static final String LOG_LEVEL = "phoenix.log.level";
public static final String AUDIT_LOG_LEVEL = "phoenix.audit.log.level";
public static final String LOG_BUFFER_SIZE = "phoenix.log.buffer.size";
public static final String LOG_BUFFER_WAIT_STRATEGY = "phoenix.log.wait.strategy";
public static final String LOG_SAMPLE_RATE = "phoenix.log.sample.rate";
public static final String LOG_HANDLER_COUNT = "phoenix.log.handler.count";
public static final String SYSTEM_CATALOG_SPLITTABLE = "phoenix.system.catalog.splittable";
// The parameters defined for handling task stored in table SYSTEM.TASK
// The time interval between periodic scans of table SYSTEM.TASK
public static final String TASK_HANDLING_INTERVAL_MS_ATTRIB = "phoenix.task.handling.interval.ms";
// The maximum time for a task to stay in table SYSTEM.TASK
public static final String TASK_HANDLING_MAX_INTERVAL_MS_ATTRIB =
"phoenix.task.handling.maxInterval.ms";
// The initial delay before the first task from table SYSTEM.TASK is handled
public static final String TASK_HANDLING_INITIAL_DELAY_MS_ATTRIB =
"phoenix.task.handling.initial.delay.ms";
// The minimum age of an unverified global index row to be eligible for deletion
public static final String GLOBAL_INDEX_ROW_AGE_THRESHOLD_TO_DELETE_MS_ATTRIB =
"phoenix.global.index.row.age.threshold.to.delete.ms";
// Enable the IndexRegionObserver coprocessor
public static final String INDEX_REGION_OBSERVER_ENABLED_ATTRIB =
"phoenix.index.region.observer.enabled";
// Enable the IndexRegionObserver coprocessor for immutable tables
String SERVER_SIDE_IMMUTABLE_INDEXES_ENABLED_ATTRIB =
"phoenix.server.side.immutable.indexes.enabled";
// Whether IndexRegionObserver/GlobalIndexChecker is enabled for all tables
public static final String INDEX_REGION_OBSERVER_ENABLED_ALL_TABLES_ATTRIB =
"phoenix.index.region.observer.enabled.all.tables";
// Enable Phoenix server paging
public static final String PHOENIX_SERVER_PAGING_ENABLED_ATTRIB = "phoenix.server.paging.enabled";
// Enable support for long view index(default is false)
public static final String LONG_VIEW_INDEX_ENABLED_ATTRIB = "phoenix.index.longViewIndex.enabled";
// The number of index rows to be rebuild in one RPC call
public static final String INDEX_REBUILD_PAGE_SIZE_IN_ROWS =
"phoenix.index.rebuild_page_size_in_rows";
// The number of index rows to be scanned in one RPC call
String INDEX_PAGE_SIZE_IN_ROWS = "phoenix.index.page_size_in_rows";
// The time limit on the amount of work to be done in one RPC call
public static final String PHOENIX_SERVER_PAGE_SIZE_MS = "phoenix.server.page.size.ms";
// TODO : Deprecate instead use PHOENIX_COMPACTION_ENABLED
public static final String PHOENIX_TABLE_TTL_ENABLED = "phoenix.table.ttl.enabled";
// Phoenix TTL/Compaction implemented by CompactionScanner and TTLRegionScanner is enabled
public static final String PHOENIX_COMPACTION_ENABLED = "phoenix.compaction.enabled";
// Copied here to avoid dependency on hbase-server
public static final String WAL_EDIT_CODEC_ATTRIB = "hbase.regionserver.wal.codec";
// Property to know whether TTL at View Level is enabled
public static final String PHOENIX_VIEW_TTL_ENABLED = "phoenix.view.ttl.enabled";
public static final String PHOENIX_VIEW_TTL_TENANT_VIEWS_PER_SCAN_LIMIT =
"phoenix.view.ttl.tenant_views_per_scan.limit";
// Block mutations based on cluster role record
public static final String CLUSTER_ROLE_BASED_MUTATION_BLOCK_ENABLED =
"phoenix.cluster.role.based.mutation.block.enabled";
// Enable Thread Pool Creation in CQSI to be used for HBase Client.
String CQSI_THREAD_POOL_ENABLED = "phoenix.cqsi.thread.pool.enabled";
// CQSI Thread Pool Related Configuration.
String CQSI_THREAD_POOL_KEEP_ALIVE_SECONDS = "phoenix.cqsi.thread.pool.keepalive.seconds";
String CQSI_THREAD_POOL_CORE_POOL_SIZE = "phoenix.cqsi.thread.pool.core.size";
String CQSI_THREAD_POOL_MAX_THREADS = "phoenix.cqsi.thread.pool.max.threads";
String CQSI_THREAD_POOL_MAX_QUEUE = "phoenix.cqsi.thread.pool.max.queue";
// Enables
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html#allowCoreThreadTimeOut-boolean-
String CQSI_THREAD_POOL_ALLOW_CORE_THREAD_TIMEOUT =
"phoenix.cqsi.thread.pool.allow.core.thread.timeout";
// Before 4.15 when we created a view we included the parent table column metadata in the view
// metadata. After PHOENIX-3534 we allow SYSTEM.CATALOG to split and no longer store the parent
// table column metadata along with the child view metadata. When we resolve a child view, we
// resolve its ancestors and include their columns.
// Also, before 4.15 when we added a column to a base table we would have to propagate the
// column metadata to all its child views. After PHOENIX-3534 we no longer propagate metadata
// changes from a parent to its children (we just resolve its ancestors and include their columns)
//
// The following config is used to continue writing the parent table column metadata while
// creating a view and also prevent metadata changes to a parent table/view that needs to be
// propagated to its children. This is done to allow rollback of the splittable SYSTEM.CATALOG
// feature
//
// By default this config is false meaning that rolling back the upgrade is not possible
// If this config is true and you want to rollback the upgrade be sure to run the sql commands in
// UpgradeUtil.addParentToChildLink which will recreate the PARENT->CHILD links in SYSTEM.CATALOG.
// This is needed
// as from 4.15 onwards the PARENT->CHILD links are stored in a separate SYSTEM.CHILD_LINK table.
public static final String ALLOW_SPLITTABLE_SYSTEM_CATALOG_ROLLBACK =
"phoenix.allow.system.catalog.rollback";
// Phoenix parameter used to indicate what implementation is used for providing the client
// stats guide post cache.
// QueryServicesOptions.DEFAULT_GUIDE_POSTS_CACHE_FACTORY_CLASS is used if this is not provided
public static final String GUIDE_POSTS_CACHE_FACTORY_CLASS =
"phoenix.guide.posts.cache.factory.class";
public static final String PENDING_MUTATIONS_DDL_THROW_ATTRIB =
"phoenix.pending.mutations.before.ddl.throw";
// The range of bins for latency metrics for histogram.
public static final String PHOENIX_HISTOGRAM_LATENCY_RANGES = "phoenix.histogram.latency.ranges";
// The range of bins for size metrics for histogram.
public static final String PHOENIX_HISTOGRAM_SIZE_RANGES = "phoenix.histogram.size.ranges";
// Connection Query Service Metrics Configs
String CONNECTION_QUERY_SERVICE_METRICS_ENABLED = "phoenix.conn.query.service.metrics.enabled";
String CONNECTION_QUERY_SERVICE_METRICS_PUBLISHER_CLASSNAME =
"phoenix.monitoring.connection.query.service.metricProvider.className";
String CONNECTION_QUERY_SERVICE_METRICS_PUBLISHER_ENABLED =
"phoenix.conn.query.service.metricsPublisher.enabled";
// The range of bins for Connection Query Service Metrics of histogram.
String CONNECTION_QUERY_SERVICE_HISTOGRAM_SIZE_RANGES =
"phoenix.conn.query.service.histogram.size.ranges";
// CDC TTL mutation retry configuration
String CDC_TTL_MUTATION_MAX_RETRIES = "phoenix.cdc.ttl.mutation.max.retries";
// CDC TTL mutation batch size configuration
String CDC_TTL_MUTATION_BATCH_SIZE = "phoenix.cdc.ttl.mutation.batch.size";
// CDC TTL shared cache expiration time in seconds
String CDC_TTL_SHARED_CACHE_EXPIRY_SECONDS = "phoenix.cdc.ttl.shared.cache.expiry.seconds";
// This config is used to move (copy and delete) the child links from the SYSTEM.CATALOG to
// SYSTEM.CHILD_LINK table.
// As opposed to a copy and async (out of band) delete.
public static final String MOVE_CHILD_LINKS_DURING_UPGRADE_ENABLED =
"phoenix.move.child_link.during.upgrade";
String SYSTEM_CATALOG_INDEXES_ENABLED = "phoenix.system.catalog.indexes.enabled";
/**
* Parameter to indicate the source of operation attribute. It can include metadata about the
* customer, service, etc.
*/
String SOURCE_OPERATION_ATTRIB = "phoenix.source.operation";
// The max point keys that can be generated for large in list clause
public static final String MAX_IN_LIST_SKIP_SCAN_SIZE = "phoenix.max.inList.skipScan.size";
/**
* Parameter to skip the system tables existence check to avoid unnecessary calls to Region server
* holding the SYSTEM.CATALOG table in batch oriented jobs.
*/
String SKIP_SYSTEM_TABLES_EXISTENCE_CHECK = "phoenix.skip.system.tables.existence.check";
/**
* Parameter to skip the minimum version check for system table upgrades
*/
String SKIP_UPGRADE_BLOCK_CHECK = "phoenix.skip.upgrade.block.check";
/**
* Config key to represent max region locations to be displayed as part of the Explain plan
* output.
*/
String MAX_REGION_LOCATIONS_SIZE_EXPLAIN_PLAN = "phoenix.max.region.locations.size.explain.plan";
/**
* Parameter to disable the server merges for hinted uncovered indexes
*/
String SERVER_MERGE_FOR_UNCOVERED_INDEX = "phoenix.query.global.server.merge.enable";
String PHOENIX_METADATA_CACHE_INVALIDATION_TIMEOUT_MS =
"phoenix.metadata.cache.invalidation.timeoutMs";
// Default to 10 seconds.
long PHOENIX_METADATA_CACHE_INVALIDATION_TIMEOUT_MS_DEFAULT = 10 * 1000;
String PHOENIX_METADATA_INVALIDATE_CACHE_ENABLED = "phoenix.metadata.invalidate.cache.enabled";
String PHOENIX_METADATA_CACHE_INVALIDATION_THREAD_POOL_SIZE =
"phoenix.metadata.cache.invalidation.threadPool.size";
/**
* Param to determine whether client can disable validation to figure out if any of the descendent
* views extend primary key of their parents. Since this is a bit of expensive call, we can opt in
* to disable it. By default, this check will always be performed while creating index
* (PHOENIX-7067) on any table or view. This config can be used for disabling other subtree
* validation purpose as well.
*/
String DISABLE_VIEW_SUBTREE_VALIDATION = "phoenix.disable.view.subtree.validation";
boolean DEFAULT_DISABLE_VIEW_SUBTREE_VALIDATION = false;
/**
* Param to enable updatable view restriction that only mark view as updatable if rows cannot
* overlap with other updatable views.
*/
String PHOENIX_UPDATABLE_VIEW_RESTRICTION_ENABLED = "phoenix.updatable.view.restriction.enabled";
boolean DEFAULT_PHOENIX_UPDATABLE_VIEW_RESTRICTION_ENABLED = false;
/**
* Only used by tests: parameter to determine num of regionservers to be created by
* MiniHBaseCluster.
*/
String TESTS_MINI_CLUSTER_NUM_REGION_SERVERS = "phoenix.tests.minicluster.numregionservers";
String TESTS_MINI_CLUSTER_NUM_MASTERS = "phoenix.tests.minicluster.nummasters";
/**
* Config to inject any processing after the client retrieves dummy result from the server.
*/
String PHOENIX_POST_DUMMY_PROCESS = "phoenix.scanning.result.post.dummy.process";
/**
* Config to inject any processing after the client retrieves valid result from the server.
*/
String PHOENIX_POST_VALID_PROCESS = "phoenix.scanning.result.post.valid.process";
/**
* New start rowkey to be used by paging region scanner for the scan.
*/
String PHOENIX_PAGING_NEW_SCAN_START_ROWKEY = "phoenix.paging.start.newscan.startrow";
/**
* New start rowkey to be included by paging region scanner for the scan. The value of the
* attribute is expected to be boolean.
*/
String PHOENIX_PAGING_NEW_SCAN_START_ROWKEY_INCLUDE =
"phoenix.paging.start.newscan.startrow.include";
/**
* Num of retries while retrieving the region location details for the given table.
*/
String PHOENIX_GET_REGIONS_RETRIES = "phoenix.get.table.regions.retries";
int DEFAULT_PHOENIX_GET_REGIONS_RETRIES = 10;
String PHOENIX_GET_METADATA_READ_LOCK_ENABLED = "phoenix.get.metadata.read.lock.enabled";
/**
* If server side metadata cache is empty, take Phoenix writeLock for the given row and make sure
* we can acquire the writeLock within the configurable duration.
*/
String PHOENIX_METADATA_CACHE_UPDATE_ROWLOCK_TIMEOUT = "phoenix.metadata.update.rowlock.timeout";
long DEFAULT_PHOENIX_METADATA_CACHE_UPDATE_ROWLOCK_TIMEOUT = 60000;
String PHOENIX_STREAMS_GET_TABLE_REGIONS_TIMEOUT = "phoenix.streams.get.table.regions.timeout";
String CQSI_THREAD_POOL_METRICS_ENABLED = "phoenix.cqsi.thread.pool.metrics.enabled";
String PHOENIX_CDC_STREAM_PARTITION_EXPIRY_MIN_AGE_MS =
"phoenix.cdc.stream.partition.expiry.min.age.ms";
String PHOENIX_UNCOVERED_INDEX_MAX_POOL_SIZE = "phoenix.uncovered.index.threads.max";
String PHOENIX_UNCOVERED_INDEX_KEEP_ALIVE_TIME_SEC =
"phoenix.uncovered.index.threads.keepalive.sec";
String USE_BLOOMFILTER_FOR_MULTIKEY_POINTLOOKUP = "phoenix.bloomfilter.multikey.pointlookup";
/**
* Get executor service used for parallel scans
*/
public ThreadPoolExecutor getExecutor();
/**
* Get the memory manager used to track memory usage
*/
public MemoryManager getMemoryManager();
/**
* Get the properties from the HBase configuration in a read-only structure that avoids any
* synchronization
*/
public ReadOnlyProps getProps();
/**
* Get query optimizer used to choose the best query plan
*/
public QueryOptimizer getOptimizer();
}
|
googleapis/google-api-java-client-services | 36,412 | clients/google-api-services-cloudbuild/v1alpha1/1.28.0/com/google/api/services/cloudbuild/v1alpha1/CloudBuild.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.cloudbuild.v1alpha1;
/**
* Service definition for CloudBuild (v1alpha1).
*
* <p>
* Creates and manages builds on Google Cloud Platform.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://cloud.google.com/cloud-build/docs/" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link CloudBuildRequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class CloudBuild 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 Cloud Build 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://cloudbuild.googleapis.com/";
/**
* The default encoded service path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_SERVICE_PATH = "";
/**
* The default encoded batch path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.23
*/
public static final String DEFAULT_BATCH_PATH = "batch";
/**
* The default encoded base URL of the service. This is determined when the library is generated
* and normally should not be changed.
*/
public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH;
/**
* Constructor.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public CloudBuild(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
*/
CloudBuild(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 Projects collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code CloudBuild cloudbuild = new CloudBuild(...);}
* {@code CloudBuild.Projects.List request = cloudbuild.projects().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Projects projects() {
return new Projects();
}
/**
* The "projects" collection of methods.
*/
public class Projects {
/**
* An accessor for creating requests from the WorkerPools collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code CloudBuild cloudbuild = new CloudBuild(...);}
* {@code CloudBuild.WorkerPools.List request = cloudbuild.workerPools().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public WorkerPools workerPools() {
return new WorkerPools();
}
/**
* The "workerPools" collection of methods.
*/
public class WorkerPools {
/**
* Creates a `WorkerPool` to run the builds, and returns the new worker pool.
*
* This API is experimental.
*
* Create a request for the method "workerPools.create".
*
* This request holds the parameters needed by the cloudbuild server. After setting any optional
* parameters, call the {@link Create#execute()} method to invoke the remote operation.
*
* @param parent ID of the parent project.
* @param content the {@link com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool}
* @return the request
*/
public Create create(java.lang.String parent, com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool content) throws java.io.IOException {
Create result = new Create(parent, content);
initialize(result);
return result;
}
public class Create extends CloudBuildRequest<com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool> {
private static final String REST_PATH = "v1alpha1/{+parent}/workerPools";
private final java.util.regex.Pattern PARENT_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+$");
/**
* Creates a `WorkerPool` to run the builds, and returns the new worker pool.
*
* This API is experimental.
*
* Create a request for the method "workerPools.create".
*
* This request holds the parameters needed by the the cloudbuild server. After setting any
* optional parameters, call the {@link Create#execute()} method to invoke the remote operation.
* <p> {@link
* Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param parent ID of the parent project.
* @param content the {@link com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool}
* @since 1.13
*/
protected Create(java.lang.String parent, com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool content) {
super(CloudBuild.this, "POST", REST_PATH, content, com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool.class);
this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+$");
}
}
@Override
public Create set$Xgafv(java.lang.String $Xgafv) {
return (Create) super.set$Xgafv($Xgafv);
}
@Override
public Create setAccessToken(java.lang.String accessToken) {
return (Create) super.setAccessToken(accessToken);
}
@Override
public Create setAlt(java.lang.String alt) {
return (Create) super.setAlt(alt);
}
@Override
public Create setCallback(java.lang.String callback) {
return (Create) super.setCallback(callback);
}
@Override
public Create setFields(java.lang.String fields) {
return (Create) super.setFields(fields);
}
@Override
public Create setKey(java.lang.String key) {
return (Create) super.setKey(key);
}
@Override
public Create setOauthToken(java.lang.String oauthToken) {
return (Create) super.setOauthToken(oauthToken);
}
@Override
public Create setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Create) super.setPrettyPrint(prettyPrint);
}
@Override
public Create setQuotaUser(java.lang.String quotaUser) {
return (Create) super.setQuotaUser(quotaUser);
}
@Override
public Create setUploadType(java.lang.String uploadType) {
return (Create) super.setUploadType(uploadType);
}
@Override
public Create setUploadProtocol(java.lang.String uploadProtocol) {
return (Create) super.setUploadProtocol(uploadProtocol);
}
/** ID of the parent project. */
@com.google.api.client.util.Key
private java.lang.String parent;
/** ID of the parent project.
*/
public java.lang.String getParent() {
return parent;
}
/** ID of the parent project. */
public Create setParent(java.lang.String parent) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+$");
}
this.parent = parent;
return this;
}
@Override
public Create set(String parameterName, Object value) {
return (Create) super.set(parameterName, value);
}
}
/**
* Deletes a `WorkerPool` by its project ID and WorkerPool name.
*
* This API is experimental.
*
* Create a request for the method "workerPools.delete".
*
* This request holds the parameters needed by the cloudbuild server. After setting any optional
* parameters, call the {@link Delete#execute()} method to invoke the remote operation.
*
* @param name The field will contain name of the resource requested, for example:
"projects/project-1/workerPools
* /workerpool-name"
* @return the request
*/
public Delete delete(java.lang.String name) throws java.io.IOException {
Delete result = new Delete(name);
initialize(result);
return result;
}
public class Delete extends CloudBuildRequest<com.google.api.services.cloudbuild.v1alpha1.model.Empty> {
private static final String REST_PATH = "v1alpha1/{+name}";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/workerPools/[^/]+$");
/**
* Deletes a `WorkerPool` by its project ID and WorkerPool name.
*
* This API is experimental.
*
* Create a request for the method "workerPools.delete".
*
* This request holds the parameters needed by the the cloudbuild server. After setting any
* optional parameters, call the {@link Delete#execute()} method to invoke the remote operation.
* <p> {@link
* Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The field will contain name of the resource requested, for example:
"projects/project-1/workerPools
* /workerpool-name"
* @since 1.13
*/
protected Delete(java.lang.String name) {
super(CloudBuild.this, "DELETE", REST_PATH, null, com.google.api.services.cloudbuild.v1alpha1.model.Empty.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/workerPools/[^/]+$");
}
}
@Override
public Delete set$Xgafv(java.lang.String $Xgafv) {
return (Delete) super.set$Xgafv($Xgafv);
}
@Override
public Delete setAccessToken(java.lang.String accessToken) {
return (Delete) super.setAccessToken(accessToken);
}
@Override
public Delete setAlt(java.lang.String alt) {
return (Delete) super.setAlt(alt);
}
@Override
public Delete setCallback(java.lang.String callback) {
return (Delete) super.setCallback(callback);
}
@Override
public Delete setFields(java.lang.String fields) {
return (Delete) super.setFields(fields);
}
@Override
public Delete setKey(java.lang.String key) {
return (Delete) super.setKey(key);
}
@Override
public Delete setOauthToken(java.lang.String oauthToken) {
return (Delete) super.setOauthToken(oauthToken);
}
@Override
public Delete setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Delete) super.setPrettyPrint(prettyPrint);
}
@Override
public Delete setQuotaUser(java.lang.String quotaUser) {
return (Delete) super.setQuotaUser(quotaUser);
}
@Override
public Delete setUploadType(java.lang.String uploadType) {
return (Delete) super.setUploadType(uploadType);
}
@Override
public Delete setUploadProtocol(java.lang.String uploadProtocol) {
return (Delete) super.setUploadProtocol(uploadProtocol);
}
/**
* The field will contain name of the resource requested, for example:
* "projects/project-1/workerPools/workerpool-name"
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The field will contain name of the resource requested, for example: "projects/project-1/workerPools
/workerpool-name"
*/
public java.lang.String getName() {
return name;
}
/**
* The field will contain name of the resource requested, for example:
* "projects/project-1/workerPools/workerpool-name"
*/
public Delete setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/workerPools/[^/]+$");
}
this.name = name;
return this;
}
@Override
public Delete set(String parameterName, Object value) {
return (Delete) super.set(parameterName, value);
}
}
/**
* Returns information about a `WorkerPool`.
*
* This API is experimental.
*
* Create a request for the method "workerPools.get".
*
* This request holds the parameters needed by the cloudbuild server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param name The field will contain name of the resource requested, for example:
"projects/project-1/workerPools
* /workerpool-name"
* @return the request
*/
public Get get(java.lang.String name) throws java.io.IOException {
Get result = new Get(name);
initialize(result);
return result;
}
public class Get extends CloudBuildRequest<com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool> {
private static final String REST_PATH = "v1alpha1/{+name}";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/workerPools/[^/]+$");
/**
* Returns information about a `WorkerPool`.
*
* This API is experimental.
*
* Create a request for the method "workerPools.get".
*
* This request holds the parameters needed by the the cloudbuild server. After setting any
* optional parameters, call the {@link Get#execute()} method to invoke the remote operation. <p>
* {@link Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The field will contain name of the resource requested, for example:
"projects/project-1/workerPools
* /workerpool-name"
* @since 1.13
*/
protected Get(java.lang.String name) {
super(CloudBuild.this, "GET", REST_PATH, null, com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/workerPools/[^/]+$");
}
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public Get set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@Override
public Get setFields(java.lang.String fields) {
return (Get) super.setFields(fields);
}
@Override
public Get setKey(java.lang.String key) {
return (Get) super.setKey(key);
}
@Override
public Get setOauthToken(java.lang.String oauthToken) {
return (Get) super.setOauthToken(oauthToken);
}
@Override
public Get setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Get) super.setPrettyPrint(prettyPrint);
}
@Override
public Get setQuotaUser(java.lang.String quotaUser) {
return (Get) super.setQuotaUser(quotaUser);
}
@Override
public Get setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
/**
* The field will contain name of the resource requested, for example:
* "projects/project-1/workerPools/workerpool-name"
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The field will contain name of the resource requested, for example: "projects/project-1/workerPools
/workerpool-name"
*/
public java.lang.String getName() {
return name;
}
/**
* The field will contain name of the resource requested, for example:
* "projects/project-1/workerPools/workerpool-name"
*/
public Get setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/workerPools/[^/]+$");
}
this.name = name;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
/**
* List project's `WorkerPool`s.
*
* This API is experimental.
*
* Create a request for the method "workerPools.list".
*
* This request holds the parameters needed by the cloudbuild server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param parent ID of the parent project.
* @return the request
*/
public List list(java.lang.String parent) throws java.io.IOException {
List result = new List(parent);
initialize(result);
return result;
}
public class List extends CloudBuildRequest<com.google.api.services.cloudbuild.v1alpha1.model.ListWorkerPoolsResponse> {
private static final String REST_PATH = "v1alpha1/{+parent}/workerPools";
private final java.util.regex.Pattern PARENT_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+$");
/**
* List project's `WorkerPool`s.
*
* This API is experimental.
*
* Create a request for the method "workerPools.list".
*
* This request holds the parameters needed by the the cloudbuild 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 parent ID of the parent project.
* @since 1.13
*/
protected List(java.lang.String parent) {
super(CloudBuild.this, "GET", REST_PATH, null, com.google.api.services.cloudbuild.v1alpha1.model.ListWorkerPoolsResponse.class);
this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+$");
}
}
@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 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 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);
}
/** ID of the parent project. */
@com.google.api.client.util.Key
private java.lang.String parent;
/** ID of the parent project.
*/
public java.lang.String getParent() {
return parent;
}
/** ID of the parent project. */
public List setParent(java.lang.String parent) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+$");
}
this.parent = parent;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
/**
* Update a `WorkerPool`.
*
* This API is experimental.
*
* Create a request for the method "workerPools.patch".
*
* This request holds the parameters needed by the cloudbuild server. After setting any optional
* parameters, call the {@link Patch#execute()} method to invoke the remote operation.
*
* @param name The field will contain name of the resource requested, for example:
"projects/project-1/workerPools
* /workerpool-name"
* @param content the {@link com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool}
* @return the request
*/
public Patch patch(java.lang.String name, com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool content) throws java.io.IOException {
Patch result = new Patch(name, content);
initialize(result);
return result;
}
public class Patch extends CloudBuildRequest<com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool> {
private static final String REST_PATH = "v1alpha1/{+name}";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/workerPools/[^/]+$");
/**
* Update a `WorkerPool`.
*
* This API is experimental.
*
* Create a request for the method "workerPools.patch".
*
* This request holds the parameters needed by the the cloudbuild server. After setting any
* optional parameters, call the {@link Patch#execute()} method to invoke the remote operation.
* <p> {@link
* Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The field will contain name of the resource requested, for example:
"projects/project-1/workerPools
* /workerpool-name"
* @param content the {@link com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool}
* @since 1.13
*/
protected Patch(java.lang.String name, com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool content) {
super(CloudBuild.this, "PATCH", REST_PATH, content, com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/workerPools/[^/]+$");
}
}
@Override
public Patch set$Xgafv(java.lang.String $Xgafv) {
return (Patch) super.set$Xgafv($Xgafv);
}
@Override
public Patch setAccessToken(java.lang.String accessToken) {
return (Patch) super.setAccessToken(accessToken);
}
@Override
public Patch setAlt(java.lang.String alt) {
return (Patch) super.setAlt(alt);
}
@Override
public Patch setCallback(java.lang.String callback) {
return (Patch) super.setCallback(callback);
}
@Override
public Patch setFields(java.lang.String fields) {
return (Patch) super.setFields(fields);
}
@Override
public Patch setKey(java.lang.String key) {
return (Patch) super.setKey(key);
}
@Override
public Patch setOauthToken(java.lang.String oauthToken) {
return (Patch) super.setOauthToken(oauthToken);
}
@Override
public Patch setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Patch) super.setPrettyPrint(prettyPrint);
}
@Override
public Patch setQuotaUser(java.lang.String quotaUser) {
return (Patch) super.setQuotaUser(quotaUser);
}
@Override
public Patch setUploadType(java.lang.String uploadType) {
return (Patch) super.setUploadType(uploadType);
}
@Override
public Patch setUploadProtocol(java.lang.String uploadProtocol) {
return (Patch) super.setUploadProtocol(uploadProtocol);
}
/**
* The field will contain name of the resource requested, for example:
* "projects/project-1/workerPools/workerpool-name"
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The field will contain name of the resource requested, for example: "projects/project-1/workerPools
/workerpool-name"
*/
public java.lang.String getName() {
return name;
}
/**
* The field will contain name of the resource requested, for example:
* "projects/project-1/workerPools/workerpool-name"
*/
public Patch setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/workerPools/[^/]+$");
}
this.name = name;
return this;
}
@Override
public Patch set(String parameterName, Object value) {
return (Patch) super.set(parameterName, value);
}
}
}
}
/**
* Builder for {@link CloudBuild}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.3.0
*/
public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
super(
transport,
jsonFactory,
DEFAULT_ROOT_URL,
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
setBatchPath(DEFAULT_BATCH_PATH);
}
/** Builds a new instance of {@link CloudBuild}. */
@Override
public CloudBuild build() {
return new CloudBuild(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 CloudBuildRequestInitializer}.
*
* @since 1.12
*/
public Builder setCloudBuildRequestInitializer(
CloudBuildRequestInitializer cloudbuildRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(cloudbuildRequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
}
}
|
googleapis/google-api-java-client-services | 36,412 | clients/google-api-services-cloudbuild/v1alpha1/1.29.2/com/google/api/services/cloudbuild/v1alpha1/CloudBuild.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.cloudbuild.v1alpha1;
/**
* Service definition for CloudBuild (v1alpha1).
*
* <p>
* Creates and manages builds on Google Cloud Platform.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://cloud.google.com/cloud-build/docs/" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link CloudBuildRequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class CloudBuild 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 Cloud Build 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://cloudbuild.googleapis.com/";
/**
* The default encoded service path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_SERVICE_PATH = "";
/**
* The default encoded batch path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.23
*/
public static final String DEFAULT_BATCH_PATH = "batch";
/**
* The default encoded base URL of the service. This is determined when the library is generated
* and normally should not be changed.
*/
public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH;
/**
* Constructor.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public CloudBuild(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
*/
CloudBuild(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 Projects collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code CloudBuild cloudbuild = new CloudBuild(...);}
* {@code CloudBuild.Projects.List request = cloudbuild.projects().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Projects projects() {
return new Projects();
}
/**
* The "projects" collection of methods.
*/
public class Projects {
/**
* An accessor for creating requests from the WorkerPools collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code CloudBuild cloudbuild = new CloudBuild(...);}
* {@code CloudBuild.WorkerPools.List request = cloudbuild.workerPools().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public WorkerPools workerPools() {
return new WorkerPools();
}
/**
* The "workerPools" collection of methods.
*/
public class WorkerPools {
/**
* Creates a `WorkerPool` to run the builds, and returns the new worker pool.
*
* This API is experimental.
*
* Create a request for the method "workerPools.create".
*
* This request holds the parameters needed by the cloudbuild server. After setting any optional
* parameters, call the {@link Create#execute()} method to invoke the remote operation.
*
* @param parent ID of the parent project.
* @param content the {@link com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool}
* @return the request
*/
public Create create(java.lang.String parent, com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool content) throws java.io.IOException {
Create result = new Create(parent, content);
initialize(result);
return result;
}
public class Create extends CloudBuildRequest<com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool> {
private static final String REST_PATH = "v1alpha1/{+parent}/workerPools";
private final java.util.regex.Pattern PARENT_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+$");
/**
* Creates a `WorkerPool` to run the builds, and returns the new worker pool.
*
* This API is experimental.
*
* Create a request for the method "workerPools.create".
*
* This request holds the parameters needed by the the cloudbuild server. After setting any
* optional parameters, call the {@link Create#execute()} method to invoke the remote operation.
* <p> {@link
* Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param parent ID of the parent project.
* @param content the {@link com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool}
* @since 1.13
*/
protected Create(java.lang.String parent, com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool content) {
super(CloudBuild.this, "POST", REST_PATH, content, com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool.class);
this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+$");
}
}
@Override
public Create set$Xgafv(java.lang.String $Xgafv) {
return (Create) super.set$Xgafv($Xgafv);
}
@Override
public Create setAccessToken(java.lang.String accessToken) {
return (Create) super.setAccessToken(accessToken);
}
@Override
public Create setAlt(java.lang.String alt) {
return (Create) super.setAlt(alt);
}
@Override
public Create setCallback(java.lang.String callback) {
return (Create) super.setCallback(callback);
}
@Override
public Create setFields(java.lang.String fields) {
return (Create) super.setFields(fields);
}
@Override
public Create setKey(java.lang.String key) {
return (Create) super.setKey(key);
}
@Override
public Create setOauthToken(java.lang.String oauthToken) {
return (Create) super.setOauthToken(oauthToken);
}
@Override
public Create setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Create) super.setPrettyPrint(prettyPrint);
}
@Override
public Create setQuotaUser(java.lang.String quotaUser) {
return (Create) super.setQuotaUser(quotaUser);
}
@Override
public Create setUploadType(java.lang.String uploadType) {
return (Create) super.setUploadType(uploadType);
}
@Override
public Create setUploadProtocol(java.lang.String uploadProtocol) {
return (Create) super.setUploadProtocol(uploadProtocol);
}
/** ID of the parent project. */
@com.google.api.client.util.Key
private java.lang.String parent;
/** ID of the parent project.
*/
public java.lang.String getParent() {
return parent;
}
/** ID of the parent project. */
public Create setParent(java.lang.String parent) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+$");
}
this.parent = parent;
return this;
}
@Override
public Create set(String parameterName, Object value) {
return (Create) super.set(parameterName, value);
}
}
/**
* Deletes a `WorkerPool` by its project ID and WorkerPool name.
*
* This API is experimental.
*
* Create a request for the method "workerPools.delete".
*
* This request holds the parameters needed by the cloudbuild server. After setting any optional
* parameters, call the {@link Delete#execute()} method to invoke the remote operation.
*
* @param name The field will contain name of the resource requested, for example:
"projects/project-1/workerPools
* /workerpool-name"
* @return the request
*/
public Delete delete(java.lang.String name) throws java.io.IOException {
Delete result = new Delete(name);
initialize(result);
return result;
}
public class Delete extends CloudBuildRequest<com.google.api.services.cloudbuild.v1alpha1.model.Empty> {
private static final String REST_PATH = "v1alpha1/{+name}";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/workerPools/[^/]+$");
/**
* Deletes a `WorkerPool` by its project ID and WorkerPool name.
*
* This API is experimental.
*
* Create a request for the method "workerPools.delete".
*
* This request holds the parameters needed by the the cloudbuild server. After setting any
* optional parameters, call the {@link Delete#execute()} method to invoke the remote operation.
* <p> {@link
* Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The field will contain name of the resource requested, for example:
"projects/project-1/workerPools
* /workerpool-name"
* @since 1.13
*/
protected Delete(java.lang.String name) {
super(CloudBuild.this, "DELETE", REST_PATH, null, com.google.api.services.cloudbuild.v1alpha1.model.Empty.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/workerPools/[^/]+$");
}
}
@Override
public Delete set$Xgafv(java.lang.String $Xgafv) {
return (Delete) super.set$Xgafv($Xgafv);
}
@Override
public Delete setAccessToken(java.lang.String accessToken) {
return (Delete) super.setAccessToken(accessToken);
}
@Override
public Delete setAlt(java.lang.String alt) {
return (Delete) super.setAlt(alt);
}
@Override
public Delete setCallback(java.lang.String callback) {
return (Delete) super.setCallback(callback);
}
@Override
public Delete setFields(java.lang.String fields) {
return (Delete) super.setFields(fields);
}
@Override
public Delete setKey(java.lang.String key) {
return (Delete) super.setKey(key);
}
@Override
public Delete setOauthToken(java.lang.String oauthToken) {
return (Delete) super.setOauthToken(oauthToken);
}
@Override
public Delete setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Delete) super.setPrettyPrint(prettyPrint);
}
@Override
public Delete setQuotaUser(java.lang.String quotaUser) {
return (Delete) super.setQuotaUser(quotaUser);
}
@Override
public Delete setUploadType(java.lang.String uploadType) {
return (Delete) super.setUploadType(uploadType);
}
@Override
public Delete setUploadProtocol(java.lang.String uploadProtocol) {
return (Delete) super.setUploadProtocol(uploadProtocol);
}
/**
* The field will contain name of the resource requested, for example:
* "projects/project-1/workerPools/workerpool-name"
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The field will contain name of the resource requested, for example: "projects/project-1/workerPools
/workerpool-name"
*/
public java.lang.String getName() {
return name;
}
/**
* The field will contain name of the resource requested, for example:
* "projects/project-1/workerPools/workerpool-name"
*/
public Delete setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/workerPools/[^/]+$");
}
this.name = name;
return this;
}
@Override
public Delete set(String parameterName, Object value) {
return (Delete) super.set(parameterName, value);
}
}
/**
* Returns information about a `WorkerPool`.
*
* This API is experimental.
*
* Create a request for the method "workerPools.get".
*
* This request holds the parameters needed by the cloudbuild server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param name The field will contain name of the resource requested, for example:
"projects/project-1/workerPools
* /workerpool-name"
* @return the request
*/
public Get get(java.lang.String name) throws java.io.IOException {
Get result = new Get(name);
initialize(result);
return result;
}
public class Get extends CloudBuildRequest<com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool> {
private static final String REST_PATH = "v1alpha1/{+name}";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/workerPools/[^/]+$");
/**
* Returns information about a `WorkerPool`.
*
* This API is experimental.
*
* Create a request for the method "workerPools.get".
*
* This request holds the parameters needed by the the cloudbuild server. After setting any
* optional parameters, call the {@link Get#execute()} method to invoke the remote operation. <p>
* {@link Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The field will contain name of the resource requested, for example:
"projects/project-1/workerPools
* /workerpool-name"
* @since 1.13
*/
protected Get(java.lang.String name) {
super(CloudBuild.this, "GET", REST_PATH, null, com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/workerPools/[^/]+$");
}
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public Get set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@Override
public Get setFields(java.lang.String fields) {
return (Get) super.setFields(fields);
}
@Override
public Get setKey(java.lang.String key) {
return (Get) super.setKey(key);
}
@Override
public Get setOauthToken(java.lang.String oauthToken) {
return (Get) super.setOauthToken(oauthToken);
}
@Override
public Get setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Get) super.setPrettyPrint(prettyPrint);
}
@Override
public Get setQuotaUser(java.lang.String quotaUser) {
return (Get) super.setQuotaUser(quotaUser);
}
@Override
public Get setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
/**
* The field will contain name of the resource requested, for example:
* "projects/project-1/workerPools/workerpool-name"
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The field will contain name of the resource requested, for example: "projects/project-1/workerPools
/workerpool-name"
*/
public java.lang.String getName() {
return name;
}
/**
* The field will contain name of the resource requested, for example:
* "projects/project-1/workerPools/workerpool-name"
*/
public Get setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/workerPools/[^/]+$");
}
this.name = name;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
/**
* List project's `WorkerPool`s.
*
* This API is experimental.
*
* Create a request for the method "workerPools.list".
*
* This request holds the parameters needed by the cloudbuild server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param parent ID of the parent project.
* @return the request
*/
public List list(java.lang.String parent) throws java.io.IOException {
List result = new List(parent);
initialize(result);
return result;
}
public class List extends CloudBuildRequest<com.google.api.services.cloudbuild.v1alpha1.model.ListWorkerPoolsResponse> {
private static final String REST_PATH = "v1alpha1/{+parent}/workerPools";
private final java.util.regex.Pattern PARENT_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+$");
/**
* List project's `WorkerPool`s.
*
* This API is experimental.
*
* Create a request for the method "workerPools.list".
*
* This request holds the parameters needed by the the cloudbuild 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 parent ID of the parent project.
* @since 1.13
*/
protected List(java.lang.String parent) {
super(CloudBuild.this, "GET", REST_PATH, null, com.google.api.services.cloudbuild.v1alpha1.model.ListWorkerPoolsResponse.class);
this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+$");
}
}
@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 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 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);
}
/** ID of the parent project. */
@com.google.api.client.util.Key
private java.lang.String parent;
/** ID of the parent project.
*/
public java.lang.String getParent() {
return parent;
}
/** ID of the parent project. */
public List setParent(java.lang.String parent) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(),
"Parameter parent must conform to the pattern " +
"^projects/[^/]+$");
}
this.parent = parent;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
/**
* Update a `WorkerPool`.
*
* This API is experimental.
*
* Create a request for the method "workerPools.patch".
*
* This request holds the parameters needed by the cloudbuild server. After setting any optional
* parameters, call the {@link Patch#execute()} method to invoke the remote operation.
*
* @param name The field will contain name of the resource requested, for example:
"projects/project-1/workerPools
* /workerpool-name"
* @param content the {@link com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool}
* @return the request
*/
public Patch patch(java.lang.String name, com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool content) throws java.io.IOException {
Patch result = new Patch(name, content);
initialize(result);
return result;
}
public class Patch extends CloudBuildRequest<com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool> {
private static final String REST_PATH = "v1alpha1/{+name}";
private final java.util.regex.Pattern NAME_PATTERN =
java.util.regex.Pattern.compile("^projects/[^/]+/workerPools/[^/]+$");
/**
* Update a `WorkerPool`.
*
* This API is experimental.
*
* Create a request for the method "workerPools.patch".
*
* This request holds the parameters needed by the the cloudbuild server. After setting any
* optional parameters, call the {@link Patch#execute()} method to invoke the remote operation.
* <p> {@link
* Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param name The field will contain name of the resource requested, for example:
"projects/project-1/workerPools
* /workerpool-name"
* @param content the {@link com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool}
* @since 1.13
*/
protected Patch(java.lang.String name, com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool content) {
super(CloudBuild.this, "PATCH", REST_PATH, content, com.google.api.services.cloudbuild.v1alpha1.model.WorkerPool.class);
this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/workerPools/[^/]+$");
}
}
@Override
public Patch set$Xgafv(java.lang.String $Xgafv) {
return (Patch) super.set$Xgafv($Xgafv);
}
@Override
public Patch setAccessToken(java.lang.String accessToken) {
return (Patch) super.setAccessToken(accessToken);
}
@Override
public Patch setAlt(java.lang.String alt) {
return (Patch) super.setAlt(alt);
}
@Override
public Patch setCallback(java.lang.String callback) {
return (Patch) super.setCallback(callback);
}
@Override
public Patch setFields(java.lang.String fields) {
return (Patch) super.setFields(fields);
}
@Override
public Patch setKey(java.lang.String key) {
return (Patch) super.setKey(key);
}
@Override
public Patch setOauthToken(java.lang.String oauthToken) {
return (Patch) super.setOauthToken(oauthToken);
}
@Override
public Patch setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Patch) super.setPrettyPrint(prettyPrint);
}
@Override
public Patch setQuotaUser(java.lang.String quotaUser) {
return (Patch) super.setQuotaUser(quotaUser);
}
@Override
public Patch setUploadType(java.lang.String uploadType) {
return (Patch) super.setUploadType(uploadType);
}
@Override
public Patch setUploadProtocol(java.lang.String uploadProtocol) {
return (Patch) super.setUploadProtocol(uploadProtocol);
}
/**
* The field will contain name of the resource requested, for example:
* "projects/project-1/workerPools/workerpool-name"
*/
@com.google.api.client.util.Key
private java.lang.String name;
/** The field will contain name of the resource requested, for example: "projects/project-1/workerPools
/workerpool-name"
*/
public java.lang.String getName() {
return name;
}
/**
* The field will contain name of the resource requested, for example:
* "projects/project-1/workerPools/workerpool-name"
*/
public Patch setName(java.lang.String name) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(),
"Parameter name must conform to the pattern " +
"^projects/[^/]+/workerPools/[^/]+$");
}
this.name = name;
return this;
}
@Override
public Patch set(String parameterName, Object value) {
return (Patch) super.set(parameterName, value);
}
}
}
}
/**
* Builder for {@link CloudBuild}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.3.0
*/
public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
super(
transport,
jsonFactory,
DEFAULT_ROOT_URL,
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
setBatchPath(DEFAULT_BATCH_PATH);
}
/** Builds a new instance of {@link CloudBuild}. */
@Override
public CloudBuild build() {
return new CloudBuild(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 CloudBuildRequestInitializer}.
*
* @since 1.12
*/
public Builder setCloudBuildRequestInitializer(
CloudBuildRequestInitializer cloudbuildRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(cloudbuildRequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
}
}
|
googleapis/google-cloud-java | 36,456 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/SummarizationHelpfulnessInput.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 summarization helpfulness metric.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput}
*/
public final class SummarizationHelpfulnessInput extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput)
SummarizationHelpfulnessInputOrBuilder {
private static final long serialVersionUID = 0L;
// Use SummarizationHelpfulnessInput.newBuilder() to construct.
private SummarizationHelpfulnessInput(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SummarizationHelpfulnessInput() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new SummarizationHelpfulnessInput();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_SummarizationHelpfulnessInput_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_SummarizationHelpfulnessInput_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput.class,
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput.Builder.class);
}
private int bitField0_;
public static final int METRIC_SPEC_FIELD_NUMBER = 1;
private com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec metricSpec_;
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec 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 summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The metricSpec.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec getMetricSpec() {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec.getDefaultInstance()
: metricSpec_;
}
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpecOrBuilder
getMetricSpecOrBuilder() {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec.getDefaultInstance()
: metricSpec_;
}
public static final int INSTANCE_FIELD_NUMBER = 2;
private com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance instance_;
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance 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. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance getInstance() {
return instance_ == null
? com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance.getDefaultInstance()
: instance_;
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstanceOrBuilder
getInstanceOrBuilder() {
return instance_ == null
? com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance.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.SummarizationHelpfulnessInput)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput other =
(com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput) 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.SummarizationHelpfulnessInput parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput 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.SummarizationHelpfulnessInput parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput 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.SummarizationHelpfulnessInput parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput 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.SummarizationHelpfulnessInput parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput 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.SummarizationHelpfulnessInput
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput
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.SummarizationHelpfulnessInput 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.SummarizationHelpfulnessInput 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.SummarizationHelpfulnessInput 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 summarization helpfulness metric.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput)
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInputOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_SummarizationHelpfulnessInput_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_SummarizationHelpfulnessInput_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput.class,
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput.Builder.class);
}
// Construct using
// com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput.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_SummarizationHelpfulnessInput_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput build() {
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput buildPartial() {
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput result =
new com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput 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.SummarizationHelpfulnessInput) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput other) {
if (other
== com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput.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.SummarizationHelpfulnessSpec metricSpec_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec,
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec.Builder,
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpecOrBuilder>
metricSpecBuilder_;
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec 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 summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The metricSpec.
*/
public com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec getMetricSpec() {
if (metricSpecBuilder_ == null) {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec.getDefaultInstance()
: metricSpec_;
} else {
return metricSpecBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setMetricSpec(
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec 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 summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setMetricSpec(
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec.Builder builderForValue) {
if (metricSpecBuilder_ == null) {
metricSpec_ = builderForValue.build();
} else {
metricSpecBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeMetricSpec(
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec value) {
if (metricSpecBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& metricSpec_ != null
&& metricSpec_
!= com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec
.getDefaultInstance()) {
getMetricSpecBuilder().mergeFrom(value);
} else {
metricSpec_ = value;
}
} else {
metricSpecBuilder_.mergeFrom(value);
}
if (metricSpec_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec 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 summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec.Builder
getMetricSpecBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getMetricSpecFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpecOrBuilder
getMetricSpecOrBuilder() {
if (metricSpecBuilder_ != null) {
return metricSpecBuilder_.getMessageOrBuilder();
} else {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec.getDefaultInstance()
: metricSpec_;
}
}
/**
*
*
* <pre>
* Required. Spec for summarization helpfulness score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec,
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec.Builder,
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpecOrBuilder>
getMetricSpecFieldBuilder() {
if (metricSpecBuilder_ == null) {
metricSpecBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec,
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpec.Builder,
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessSpecOrBuilder>(
getMetricSpec(), getParentForChildren(), isClean());
metricSpec_ = null;
}
return metricSpecBuilder_;
}
private com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance instance_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance,
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance.Builder,
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstanceOrBuilder>
instanceBuilder_;
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the instance field is set.
*/
public boolean hasInstance() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
public com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance getInstance() {
if (instanceBuilder_ == null) {
return instance_ == null
? com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance
.getDefaultInstance()
: instance_;
} else {
return instanceBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance value) {
if (instanceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
instance_ = value;
} else {
instanceBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance.Builder
builderForValue) {
if (instanceBuilder_ == null) {
instance_ = builderForValue.build();
} else {
instanceBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeInstance(
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance value) {
if (instanceBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& instance_ != null
&& instance_
!= com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance
.getDefaultInstance()) {
getInstanceBuilder().mergeFrom(value);
} else {
instance_ = value;
}
} else {
instanceBuilder_.mergeFrom(value);
}
if (instance_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance 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. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance.Builder
getInstanceBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getInstanceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstanceOrBuilder
getInstanceOrBuilder() {
if (instanceBuilder_ != null) {
return instanceBuilder_.getMessageOrBuilder();
} else {
return instance_ == null
? com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance
.getDefaultInstance()
: instance_;
}
}
/**
*
*
* <pre>
* Required. Summarization helpfulness instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance,
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance.Builder,
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstanceOrBuilder>
getInstanceFieldBuilder() {
if (instanceBuilder_ == null) {
instanceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance,
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstance.Builder,
com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInstanceOrBuilder>(
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.SummarizationHelpfulnessInput)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput)
private static final com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput();
}
public static com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SummarizationHelpfulnessInput> PARSER =
new com.google.protobuf.AbstractParser<SummarizationHelpfulnessInput>() {
@java.lang.Override
public SummarizationHelpfulnessInput 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<SummarizationHelpfulnessInput> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SummarizationHelpfulnessInput> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SummarizationHelpfulnessInput
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-api-java-client-services | 36,499 | clients/google-api-services-dfareporting/v2.8/1.26.0/com/google/api/services/dfareporting/model/Ad.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.dfareporting.model;
/**
* Contains properties of a Campaign Manager ad.
*
* <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 DCM/DFA Reporting And Trafficking 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 Ad extends com.google.api.client.json.GenericJson {
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long accountId;
/**
* Whether this ad is active. When true, archived must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean active;
/**
* Advertiser ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long advertiserId;
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue advertiserIdDimensionValue;
/**
* Whether this ad is archived. When true, active must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean archived;
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long audienceSegmentId;
/**
* Campaign ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long campaignId;
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue campaignIdDimensionValue;
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrl clickThroughUrl;
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties;
/**
* Comments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String comments;
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String compatibility;
/**
* Information about the creation of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo createInfo;
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<CreativeGroupAssignment> creativeGroupAssignments;
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CreativeRotation creativeRotation;
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DayPartTargeting dayPartTargeting;
/**
* Default click-through event tag properties for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties;
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DeliverySchedule deliverySchedule;
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean dynamicClickTracker;
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime endTime;
/**
* Event tag overrides for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<EventTagOverride> eventTagOverrides;
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GeoTargeting geoTargeting;
/**
* ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long id;
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue idDimensionValue;
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private KeyValueTargetingExpression keyValueTargetingExpression;
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LanguageTargeting languageTargeting;
/**
* Information about the most recent modification of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo lastModifiedInfo;
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Placement assignments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<PlacementAssignment> placementAssignments;
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ListTargetingExpression remarketingListExpression;
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Size size;
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslCompliant;
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslRequired;
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime startTime;
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long subaccountId;
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long targetingTemplateId;
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TechnologyTargeting technologyTargeting;
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String type;
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getAccountId() {
return accountId;
}
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @param accountId accountId or {@code null} for none
*/
public Ad setAccountId(java.lang.Long accountId) {
this.accountId = accountId;
return this;
}
/**
* Whether this ad is active. When true, archived must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getActive() {
return active;
}
/**
* Whether this ad is active. When true, archived must be false.
* @param active active or {@code null} for none
*/
public Ad setActive(java.lang.Boolean active) {
this.active = active;
return this;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getAdvertiserId() {
return advertiserId;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @param advertiserId advertiserId or {@code null} for none
*/
public Ad setAdvertiserId(java.lang.Long advertiserId) {
this.advertiserId = advertiserId;
return this;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getAdvertiserIdDimensionValue() {
return advertiserIdDimensionValue;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @param advertiserIdDimensionValue advertiserIdDimensionValue or {@code null} for none
*/
public Ad setAdvertiserIdDimensionValue(DimensionValue advertiserIdDimensionValue) {
this.advertiserIdDimensionValue = advertiserIdDimensionValue;
return this;
}
/**
* Whether this ad is archived. When true, active must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getArchived() {
return archived;
}
/**
* Whether this ad is archived. When true, active must be false.
* @param archived archived or {@code null} for none
*/
public Ad setArchived(java.lang.Boolean archived) {
this.archived = archived;
return this;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getAudienceSegmentId() {
return audienceSegmentId;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @param audienceSegmentId audienceSegmentId or {@code null} for none
*/
public Ad setAudienceSegmentId(java.lang.Long audienceSegmentId) {
this.audienceSegmentId = audienceSegmentId;
return this;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getCampaignId() {
return campaignId;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @param campaignId campaignId or {@code null} for none
*/
public Ad setCampaignId(java.lang.Long campaignId) {
this.campaignId = campaignId;
return this;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getCampaignIdDimensionValue() {
return campaignIdDimensionValue;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @param campaignIdDimensionValue campaignIdDimensionValue or {@code null} for none
*/
public Ad setCampaignIdDimensionValue(DimensionValue campaignIdDimensionValue) {
this.campaignIdDimensionValue = campaignIdDimensionValue;
return this;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @return value or {@code null} for none
*/
public ClickThroughUrl getClickThroughUrl() {
return clickThroughUrl;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @param clickThroughUrl clickThroughUrl or {@code null} for none
*/
public Ad setClickThroughUrl(ClickThroughUrl clickThroughUrl) {
this.clickThroughUrl = clickThroughUrl;
return this;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @return value or {@code null} for none
*/
public ClickThroughUrlSuffixProperties getClickThroughUrlSuffixProperties() {
return clickThroughUrlSuffixProperties;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @param clickThroughUrlSuffixProperties clickThroughUrlSuffixProperties or {@code null} for none
*/
public Ad setClickThroughUrlSuffixProperties(ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties) {
this.clickThroughUrlSuffixProperties = clickThroughUrlSuffixProperties;
return this;
}
/**
* Comments for this ad.
* @return value or {@code null} for none
*/
public java.lang.String getComments() {
return comments;
}
/**
* Comments for this ad.
* @param comments comments or {@code null} for none
*/
public Ad setComments(java.lang.String comments) {
this.comments = comments;
return this;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @return value or {@code null} for none
*/
public java.lang.String getCompatibility() {
return compatibility;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @param compatibility compatibility or {@code null} for none
*/
public Ad setCompatibility(java.lang.String compatibility) {
this.compatibility = compatibility;
return this;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getCreateInfo() {
return createInfo;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @param createInfo createInfo or {@code null} for none
*/
public Ad setCreateInfo(LastModifiedInfo createInfo) {
this.createInfo = createInfo;
return this;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @return value or {@code null} for none
*/
public java.util.List<CreativeGroupAssignment> getCreativeGroupAssignments() {
return creativeGroupAssignments;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @param creativeGroupAssignments creativeGroupAssignments or {@code null} for none
*/
public Ad setCreativeGroupAssignments(java.util.List<CreativeGroupAssignment> creativeGroupAssignments) {
this.creativeGroupAssignments = creativeGroupAssignments;
return this;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @return value or {@code null} for none
*/
public CreativeRotation getCreativeRotation() {
return creativeRotation;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @param creativeRotation creativeRotation or {@code null} for none
*/
public Ad setCreativeRotation(CreativeRotation creativeRotation) {
this.creativeRotation = creativeRotation;
return this;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DayPartTargeting getDayPartTargeting() {
return dayPartTargeting;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param dayPartTargeting dayPartTargeting or {@code null} for none
*/
public Ad setDayPartTargeting(DayPartTargeting dayPartTargeting) {
this.dayPartTargeting = dayPartTargeting;
return this;
}
/**
* Default click-through event tag properties for this ad.
* @return value or {@code null} for none
*/
public DefaultClickThroughEventTagProperties getDefaultClickThroughEventTagProperties() {
return defaultClickThroughEventTagProperties;
}
/**
* Default click-through event tag properties for this ad.
* @param defaultClickThroughEventTagProperties defaultClickThroughEventTagProperties or {@code null} for none
*/
public Ad setDefaultClickThroughEventTagProperties(DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties) {
this.defaultClickThroughEventTagProperties = defaultClickThroughEventTagProperties;
return this;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DeliverySchedule getDeliverySchedule() {
return deliverySchedule;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @param deliverySchedule deliverySchedule or {@code null} for none
*/
public Ad setDeliverySchedule(DeliverySchedule deliverySchedule) {
this.deliverySchedule = deliverySchedule;
return this;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDynamicClickTracker() {
return dynamicClickTracker;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @param dynamicClickTracker dynamicClickTracker or {@code null} for none
*/
public Ad setDynamicClickTracker(java.lang.Boolean dynamicClickTracker) {
this.dynamicClickTracker = dynamicClickTracker;
return this;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getEndTime() {
return endTime;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @param endTime endTime or {@code null} for none
*/
public Ad setEndTime(com.google.api.client.util.DateTime endTime) {
this.endTime = endTime;
return this;
}
/**
* Event tag overrides for this ad.
* @return value or {@code null} for none
*/
public java.util.List<EventTagOverride> getEventTagOverrides() {
return eventTagOverrides;
}
/**
* Event tag overrides for this ad.
* @param eventTagOverrides eventTagOverrides or {@code null} for none
*/
public Ad setEventTagOverrides(java.util.List<EventTagOverride> eventTagOverrides) {
this.eventTagOverrides = eventTagOverrides;
return this;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public GeoTargeting getGeoTargeting() {
return geoTargeting;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param geoTargeting geoTargeting or {@code null} for none
*/
public Ad setGeoTargeting(GeoTargeting geoTargeting) {
this.geoTargeting = geoTargeting;
return this;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public java.lang.Long getId() {
return id;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @param id id or {@code null} for none
*/
public Ad setId(java.lang.Long id) {
this.id = id;
return this;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getIdDimensionValue() {
return idDimensionValue;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @param idDimensionValue idDimensionValue or {@code null} for none
*/
public Ad setIdDimensionValue(DimensionValue idDimensionValue) {
this.idDimensionValue = idDimensionValue;
return this;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public KeyValueTargetingExpression getKeyValueTargetingExpression() {
return keyValueTargetingExpression;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param keyValueTargetingExpression keyValueTargetingExpression or {@code null} for none
*/
public Ad setKeyValueTargetingExpression(KeyValueTargetingExpression keyValueTargetingExpression) {
this.keyValueTargetingExpression = keyValueTargetingExpression;
return this;
}
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* @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 "dfareporting#ad".
* @param kind kind or {@code null} for none
*/
public Ad setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public LanguageTargeting getLanguageTargeting() {
return languageTargeting;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param languageTargeting languageTargeting or {@code null} for none
*/
public Ad setLanguageTargeting(LanguageTargeting languageTargeting) {
this.languageTargeting = languageTargeting;
return this;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getLastModifiedInfo() {
return lastModifiedInfo;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @param lastModifiedInfo lastModifiedInfo or {@code null} for none
*/
public Ad setLastModifiedInfo(LastModifiedInfo lastModifiedInfo) {
this.lastModifiedInfo = lastModifiedInfo;
return this;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @param name name or {@code null} for none
*/
public Ad setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Placement assignments for this ad.
* @return value or {@code null} for none
*/
public java.util.List<PlacementAssignment> getPlacementAssignments() {
return placementAssignments;
}
/**
* Placement assignments for this ad.
* @param placementAssignments placementAssignments or {@code null} for none
*/
public Ad setPlacementAssignments(java.util.List<PlacementAssignment> placementAssignments) {
this.placementAssignments = placementAssignments;
return this;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public ListTargetingExpression getRemarketingListExpression() {
return remarketingListExpression;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param remarketingListExpression remarketingListExpression or {@code null} for none
*/
public Ad setRemarketingListExpression(ListTargetingExpression remarketingListExpression) {
this.remarketingListExpression = remarketingListExpression;
return this;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @return value or {@code null} for none
*/
public Size getSize() {
return size;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @param size size or {@code null} for none
*/
public Ad setSize(Size size) {
this.size = size;
return this;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslCompliant() {
return sslCompliant;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @param sslCompliant sslCompliant or {@code null} for none
*/
public Ad setSslCompliant(java.lang.Boolean sslCompliant) {
this.sslCompliant = sslCompliant;
return this;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslRequired() {
return sslRequired;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @param sslRequired sslRequired or {@code null} for none
*/
public Ad setSslRequired(java.lang.Boolean sslRequired) {
this.sslRequired = sslRequired;
return this;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getStartTime() {
return startTime;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @param startTime startTime or {@code null} for none
*/
public Ad setStartTime(com.google.api.client.util.DateTime startTime) {
this.startTime = startTime;
return this;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getSubaccountId() {
return subaccountId;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @param subaccountId subaccountId or {@code null} for none
*/
public Ad setSubaccountId(java.lang.Long subaccountId) {
this.subaccountId = subaccountId;
return this;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getTargetingTemplateId() {
return targetingTemplateId;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @param targetingTemplateId targetingTemplateId or {@code null} for none
*/
public Ad setTargetingTemplateId(java.lang.Long targetingTemplateId) {
this.targetingTemplateId = targetingTemplateId;
return this;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public TechnologyTargeting getTechnologyTargeting() {
return technologyTargeting;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param technologyTargeting technologyTargeting or {@code null} for none
*/
public Ad setTechnologyTargeting(TechnologyTargeting technologyTargeting) {
this.technologyTargeting = technologyTargeting;
return this;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @return value or {@code null} for none
*/
public java.lang.String getType() {
return type;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @param type type or {@code null} for none
*/
public Ad setType(java.lang.String type) {
this.type = type;
return this;
}
@Override
public Ad set(String fieldName, Object value) {
return (Ad) super.set(fieldName, value);
}
@Override
public Ad clone() {
return (Ad) super.clone();
}
}
|
googleapis/google-api-java-client-services | 36,499 | clients/google-api-services-dfareporting/v3.0/1.26.0/com/google/api/services/dfareporting/model/Ad.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.dfareporting.model;
/**
* Contains properties of a Campaign Manager ad.
*
* <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 DCM/DFA Reporting And Trafficking 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 Ad extends com.google.api.client.json.GenericJson {
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long accountId;
/**
* Whether this ad is active. When true, archived must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean active;
/**
* Advertiser ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long advertiserId;
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue advertiserIdDimensionValue;
/**
* Whether this ad is archived. When true, active must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean archived;
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long audienceSegmentId;
/**
* Campaign ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long campaignId;
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue campaignIdDimensionValue;
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrl clickThroughUrl;
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties;
/**
* Comments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String comments;
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String compatibility;
/**
* Information about the creation of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo createInfo;
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<CreativeGroupAssignment> creativeGroupAssignments;
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CreativeRotation creativeRotation;
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DayPartTargeting dayPartTargeting;
/**
* Default click-through event tag properties for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties;
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DeliverySchedule deliverySchedule;
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean dynamicClickTracker;
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime endTime;
/**
* Event tag overrides for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<EventTagOverride> eventTagOverrides;
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GeoTargeting geoTargeting;
/**
* ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long id;
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue idDimensionValue;
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private KeyValueTargetingExpression keyValueTargetingExpression;
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LanguageTargeting languageTargeting;
/**
* Information about the most recent modification of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo lastModifiedInfo;
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Placement assignments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<PlacementAssignment> placementAssignments;
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ListTargetingExpression remarketingListExpression;
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Size size;
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslCompliant;
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslRequired;
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime startTime;
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long subaccountId;
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long targetingTemplateId;
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TechnologyTargeting technologyTargeting;
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String type;
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getAccountId() {
return accountId;
}
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @param accountId accountId or {@code null} for none
*/
public Ad setAccountId(java.lang.Long accountId) {
this.accountId = accountId;
return this;
}
/**
* Whether this ad is active. When true, archived must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getActive() {
return active;
}
/**
* Whether this ad is active. When true, archived must be false.
* @param active active or {@code null} for none
*/
public Ad setActive(java.lang.Boolean active) {
this.active = active;
return this;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getAdvertiserId() {
return advertiserId;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @param advertiserId advertiserId or {@code null} for none
*/
public Ad setAdvertiserId(java.lang.Long advertiserId) {
this.advertiserId = advertiserId;
return this;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getAdvertiserIdDimensionValue() {
return advertiserIdDimensionValue;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @param advertiserIdDimensionValue advertiserIdDimensionValue or {@code null} for none
*/
public Ad setAdvertiserIdDimensionValue(DimensionValue advertiserIdDimensionValue) {
this.advertiserIdDimensionValue = advertiserIdDimensionValue;
return this;
}
/**
* Whether this ad is archived. When true, active must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getArchived() {
return archived;
}
/**
* Whether this ad is archived. When true, active must be false.
* @param archived archived or {@code null} for none
*/
public Ad setArchived(java.lang.Boolean archived) {
this.archived = archived;
return this;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getAudienceSegmentId() {
return audienceSegmentId;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @param audienceSegmentId audienceSegmentId or {@code null} for none
*/
public Ad setAudienceSegmentId(java.lang.Long audienceSegmentId) {
this.audienceSegmentId = audienceSegmentId;
return this;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getCampaignId() {
return campaignId;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @param campaignId campaignId or {@code null} for none
*/
public Ad setCampaignId(java.lang.Long campaignId) {
this.campaignId = campaignId;
return this;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getCampaignIdDimensionValue() {
return campaignIdDimensionValue;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @param campaignIdDimensionValue campaignIdDimensionValue or {@code null} for none
*/
public Ad setCampaignIdDimensionValue(DimensionValue campaignIdDimensionValue) {
this.campaignIdDimensionValue = campaignIdDimensionValue;
return this;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @return value or {@code null} for none
*/
public ClickThroughUrl getClickThroughUrl() {
return clickThroughUrl;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @param clickThroughUrl clickThroughUrl or {@code null} for none
*/
public Ad setClickThroughUrl(ClickThroughUrl clickThroughUrl) {
this.clickThroughUrl = clickThroughUrl;
return this;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @return value or {@code null} for none
*/
public ClickThroughUrlSuffixProperties getClickThroughUrlSuffixProperties() {
return clickThroughUrlSuffixProperties;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @param clickThroughUrlSuffixProperties clickThroughUrlSuffixProperties or {@code null} for none
*/
public Ad setClickThroughUrlSuffixProperties(ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties) {
this.clickThroughUrlSuffixProperties = clickThroughUrlSuffixProperties;
return this;
}
/**
* Comments for this ad.
* @return value or {@code null} for none
*/
public java.lang.String getComments() {
return comments;
}
/**
* Comments for this ad.
* @param comments comments or {@code null} for none
*/
public Ad setComments(java.lang.String comments) {
this.comments = comments;
return this;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @return value or {@code null} for none
*/
public java.lang.String getCompatibility() {
return compatibility;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @param compatibility compatibility or {@code null} for none
*/
public Ad setCompatibility(java.lang.String compatibility) {
this.compatibility = compatibility;
return this;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getCreateInfo() {
return createInfo;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @param createInfo createInfo or {@code null} for none
*/
public Ad setCreateInfo(LastModifiedInfo createInfo) {
this.createInfo = createInfo;
return this;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @return value or {@code null} for none
*/
public java.util.List<CreativeGroupAssignment> getCreativeGroupAssignments() {
return creativeGroupAssignments;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @param creativeGroupAssignments creativeGroupAssignments or {@code null} for none
*/
public Ad setCreativeGroupAssignments(java.util.List<CreativeGroupAssignment> creativeGroupAssignments) {
this.creativeGroupAssignments = creativeGroupAssignments;
return this;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @return value or {@code null} for none
*/
public CreativeRotation getCreativeRotation() {
return creativeRotation;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @param creativeRotation creativeRotation or {@code null} for none
*/
public Ad setCreativeRotation(CreativeRotation creativeRotation) {
this.creativeRotation = creativeRotation;
return this;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DayPartTargeting getDayPartTargeting() {
return dayPartTargeting;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param dayPartTargeting dayPartTargeting or {@code null} for none
*/
public Ad setDayPartTargeting(DayPartTargeting dayPartTargeting) {
this.dayPartTargeting = dayPartTargeting;
return this;
}
/**
* Default click-through event tag properties for this ad.
* @return value or {@code null} for none
*/
public DefaultClickThroughEventTagProperties getDefaultClickThroughEventTagProperties() {
return defaultClickThroughEventTagProperties;
}
/**
* Default click-through event tag properties for this ad.
* @param defaultClickThroughEventTagProperties defaultClickThroughEventTagProperties or {@code null} for none
*/
public Ad setDefaultClickThroughEventTagProperties(DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties) {
this.defaultClickThroughEventTagProperties = defaultClickThroughEventTagProperties;
return this;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DeliverySchedule getDeliverySchedule() {
return deliverySchedule;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @param deliverySchedule deliverySchedule or {@code null} for none
*/
public Ad setDeliverySchedule(DeliverySchedule deliverySchedule) {
this.deliverySchedule = deliverySchedule;
return this;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDynamicClickTracker() {
return dynamicClickTracker;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @param dynamicClickTracker dynamicClickTracker or {@code null} for none
*/
public Ad setDynamicClickTracker(java.lang.Boolean dynamicClickTracker) {
this.dynamicClickTracker = dynamicClickTracker;
return this;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getEndTime() {
return endTime;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @param endTime endTime or {@code null} for none
*/
public Ad setEndTime(com.google.api.client.util.DateTime endTime) {
this.endTime = endTime;
return this;
}
/**
* Event tag overrides for this ad.
* @return value or {@code null} for none
*/
public java.util.List<EventTagOverride> getEventTagOverrides() {
return eventTagOverrides;
}
/**
* Event tag overrides for this ad.
* @param eventTagOverrides eventTagOverrides or {@code null} for none
*/
public Ad setEventTagOverrides(java.util.List<EventTagOverride> eventTagOverrides) {
this.eventTagOverrides = eventTagOverrides;
return this;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public GeoTargeting getGeoTargeting() {
return geoTargeting;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param geoTargeting geoTargeting or {@code null} for none
*/
public Ad setGeoTargeting(GeoTargeting geoTargeting) {
this.geoTargeting = geoTargeting;
return this;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public java.lang.Long getId() {
return id;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @param id id or {@code null} for none
*/
public Ad setId(java.lang.Long id) {
this.id = id;
return this;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getIdDimensionValue() {
return idDimensionValue;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @param idDimensionValue idDimensionValue or {@code null} for none
*/
public Ad setIdDimensionValue(DimensionValue idDimensionValue) {
this.idDimensionValue = idDimensionValue;
return this;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public KeyValueTargetingExpression getKeyValueTargetingExpression() {
return keyValueTargetingExpression;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param keyValueTargetingExpression keyValueTargetingExpression or {@code null} for none
*/
public Ad setKeyValueTargetingExpression(KeyValueTargetingExpression keyValueTargetingExpression) {
this.keyValueTargetingExpression = keyValueTargetingExpression;
return this;
}
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* @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 "dfareporting#ad".
* @param kind kind or {@code null} for none
*/
public Ad setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public LanguageTargeting getLanguageTargeting() {
return languageTargeting;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param languageTargeting languageTargeting or {@code null} for none
*/
public Ad setLanguageTargeting(LanguageTargeting languageTargeting) {
this.languageTargeting = languageTargeting;
return this;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getLastModifiedInfo() {
return lastModifiedInfo;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @param lastModifiedInfo lastModifiedInfo or {@code null} for none
*/
public Ad setLastModifiedInfo(LastModifiedInfo lastModifiedInfo) {
this.lastModifiedInfo = lastModifiedInfo;
return this;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @param name name or {@code null} for none
*/
public Ad setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Placement assignments for this ad.
* @return value or {@code null} for none
*/
public java.util.List<PlacementAssignment> getPlacementAssignments() {
return placementAssignments;
}
/**
* Placement assignments for this ad.
* @param placementAssignments placementAssignments or {@code null} for none
*/
public Ad setPlacementAssignments(java.util.List<PlacementAssignment> placementAssignments) {
this.placementAssignments = placementAssignments;
return this;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public ListTargetingExpression getRemarketingListExpression() {
return remarketingListExpression;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param remarketingListExpression remarketingListExpression or {@code null} for none
*/
public Ad setRemarketingListExpression(ListTargetingExpression remarketingListExpression) {
this.remarketingListExpression = remarketingListExpression;
return this;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @return value or {@code null} for none
*/
public Size getSize() {
return size;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @param size size or {@code null} for none
*/
public Ad setSize(Size size) {
this.size = size;
return this;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslCompliant() {
return sslCompliant;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @param sslCompliant sslCompliant or {@code null} for none
*/
public Ad setSslCompliant(java.lang.Boolean sslCompliant) {
this.sslCompliant = sslCompliant;
return this;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslRequired() {
return sslRequired;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @param sslRequired sslRequired or {@code null} for none
*/
public Ad setSslRequired(java.lang.Boolean sslRequired) {
this.sslRequired = sslRequired;
return this;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getStartTime() {
return startTime;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @param startTime startTime or {@code null} for none
*/
public Ad setStartTime(com.google.api.client.util.DateTime startTime) {
this.startTime = startTime;
return this;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getSubaccountId() {
return subaccountId;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @param subaccountId subaccountId or {@code null} for none
*/
public Ad setSubaccountId(java.lang.Long subaccountId) {
this.subaccountId = subaccountId;
return this;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getTargetingTemplateId() {
return targetingTemplateId;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @param targetingTemplateId targetingTemplateId or {@code null} for none
*/
public Ad setTargetingTemplateId(java.lang.Long targetingTemplateId) {
this.targetingTemplateId = targetingTemplateId;
return this;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public TechnologyTargeting getTechnologyTargeting() {
return technologyTargeting;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param technologyTargeting technologyTargeting or {@code null} for none
*/
public Ad setTechnologyTargeting(TechnologyTargeting technologyTargeting) {
this.technologyTargeting = technologyTargeting;
return this;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @return value or {@code null} for none
*/
public java.lang.String getType() {
return type;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @param type type or {@code null} for none
*/
public Ad setType(java.lang.String type) {
this.type = type;
return this;
}
@Override
public Ad set(String fieldName, Object value) {
return (Ad) super.set(fieldName, value);
}
@Override
public Ad clone() {
return (Ad) super.clone();
}
}
|
googleapis/google-api-java-client-services | 36,499 | clients/google-api-services-dfareporting/v3.0/1.27.0/com/google/api/services/dfareporting/model/Ad.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.dfareporting.model;
/**
* Contains properties of a Campaign Manager ad.
*
* <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 DCM/DFA Reporting And Trafficking 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 Ad extends com.google.api.client.json.GenericJson {
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long accountId;
/**
* Whether this ad is active. When true, archived must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean active;
/**
* Advertiser ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long advertiserId;
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue advertiserIdDimensionValue;
/**
* Whether this ad is archived. When true, active must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean archived;
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long audienceSegmentId;
/**
* Campaign ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long campaignId;
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue campaignIdDimensionValue;
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrl clickThroughUrl;
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties;
/**
* Comments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String comments;
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String compatibility;
/**
* Information about the creation of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo createInfo;
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<CreativeGroupAssignment> creativeGroupAssignments;
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CreativeRotation creativeRotation;
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DayPartTargeting dayPartTargeting;
/**
* Default click-through event tag properties for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties;
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DeliverySchedule deliverySchedule;
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean dynamicClickTracker;
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime endTime;
/**
* Event tag overrides for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<EventTagOverride> eventTagOverrides;
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GeoTargeting geoTargeting;
/**
* ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long id;
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue idDimensionValue;
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private KeyValueTargetingExpression keyValueTargetingExpression;
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LanguageTargeting languageTargeting;
/**
* Information about the most recent modification of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo lastModifiedInfo;
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Placement assignments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<PlacementAssignment> placementAssignments;
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ListTargetingExpression remarketingListExpression;
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Size size;
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslCompliant;
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslRequired;
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime startTime;
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long subaccountId;
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long targetingTemplateId;
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TechnologyTargeting technologyTargeting;
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String type;
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getAccountId() {
return accountId;
}
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @param accountId accountId or {@code null} for none
*/
public Ad setAccountId(java.lang.Long accountId) {
this.accountId = accountId;
return this;
}
/**
* Whether this ad is active. When true, archived must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getActive() {
return active;
}
/**
* Whether this ad is active. When true, archived must be false.
* @param active active or {@code null} for none
*/
public Ad setActive(java.lang.Boolean active) {
this.active = active;
return this;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getAdvertiserId() {
return advertiserId;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @param advertiserId advertiserId or {@code null} for none
*/
public Ad setAdvertiserId(java.lang.Long advertiserId) {
this.advertiserId = advertiserId;
return this;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getAdvertiserIdDimensionValue() {
return advertiserIdDimensionValue;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @param advertiserIdDimensionValue advertiserIdDimensionValue or {@code null} for none
*/
public Ad setAdvertiserIdDimensionValue(DimensionValue advertiserIdDimensionValue) {
this.advertiserIdDimensionValue = advertiserIdDimensionValue;
return this;
}
/**
* Whether this ad is archived. When true, active must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getArchived() {
return archived;
}
/**
* Whether this ad is archived. When true, active must be false.
* @param archived archived or {@code null} for none
*/
public Ad setArchived(java.lang.Boolean archived) {
this.archived = archived;
return this;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getAudienceSegmentId() {
return audienceSegmentId;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @param audienceSegmentId audienceSegmentId or {@code null} for none
*/
public Ad setAudienceSegmentId(java.lang.Long audienceSegmentId) {
this.audienceSegmentId = audienceSegmentId;
return this;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getCampaignId() {
return campaignId;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @param campaignId campaignId or {@code null} for none
*/
public Ad setCampaignId(java.lang.Long campaignId) {
this.campaignId = campaignId;
return this;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getCampaignIdDimensionValue() {
return campaignIdDimensionValue;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @param campaignIdDimensionValue campaignIdDimensionValue or {@code null} for none
*/
public Ad setCampaignIdDimensionValue(DimensionValue campaignIdDimensionValue) {
this.campaignIdDimensionValue = campaignIdDimensionValue;
return this;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @return value or {@code null} for none
*/
public ClickThroughUrl getClickThroughUrl() {
return clickThroughUrl;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @param clickThroughUrl clickThroughUrl or {@code null} for none
*/
public Ad setClickThroughUrl(ClickThroughUrl clickThroughUrl) {
this.clickThroughUrl = clickThroughUrl;
return this;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @return value or {@code null} for none
*/
public ClickThroughUrlSuffixProperties getClickThroughUrlSuffixProperties() {
return clickThroughUrlSuffixProperties;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @param clickThroughUrlSuffixProperties clickThroughUrlSuffixProperties or {@code null} for none
*/
public Ad setClickThroughUrlSuffixProperties(ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties) {
this.clickThroughUrlSuffixProperties = clickThroughUrlSuffixProperties;
return this;
}
/**
* Comments for this ad.
* @return value or {@code null} for none
*/
public java.lang.String getComments() {
return comments;
}
/**
* Comments for this ad.
* @param comments comments or {@code null} for none
*/
public Ad setComments(java.lang.String comments) {
this.comments = comments;
return this;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @return value or {@code null} for none
*/
public java.lang.String getCompatibility() {
return compatibility;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @param compatibility compatibility or {@code null} for none
*/
public Ad setCompatibility(java.lang.String compatibility) {
this.compatibility = compatibility;
return this;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getCreateInfo() {
return createInfo;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @param createInfo createInfo or {@code null} for none
*/
public Ad setCreateInfo(LastModifiedInfo createInfo) {
this.createInfo = createInfo;
return this;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @return value or {@code null} for none
*/
public java.util.List<CreativeGroupAssignment> getCreativeGroupAssignments() {
return creativeGroupAssignments;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @param creativeGroupAssignments creativeGroupAssignments or {@code null} for none
*/
public Ad setCreativeGroupAssignments(java.util.List<CreativeGroupAssignment> creativeGroupAssignments) {
this.creativeGroupAssignments = creativeGroupAssignments;
return this;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @return value or {@code null} for none
*/
public CreativeRotation getCreativeRotation() {
return creativeRotation;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @param creativeRotation creativeRotation or {@code null} for none
*/
public Ad setCreativeRotation(CreativeRotation creativeRotation) {
this.creativeRotation = creativeRotation;
return this;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DayPartTargeting getDayPartTargeting() {
return dayPartTargeting;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param dayPartTargeting dayPartTargeting or {@code null} for none
*/
public Ad setDayPartTargeting(DayPartTargeting dayPartTargeting) {
this.dayPartTargeting = dayPartTargeting;
return this;
}
/**
* Default click-through event tag properties for this ad.
* @return value or {@code null} for none
*/
public DefaultClickThroughEventTagProperties getDefaultClickThroughEventTagProperties() {
return defaultClickThroughEventTagProperties;
}
/**
* Default click-through event tag properties for this ad.
* @param defaultClickThroughEventTagProperties defaultClickThroughEventTagProperties or {@code null} for none
*/
public Ad setDefaultClickThroughEventTagProperties(DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties) {
this.defaultClickThroughEventTagProperties = defaultClickThroughEventTagProperties;
return this;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DeliverySchedule getDeliverySchedule() {
return deliverySchedule;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @param deliverySchedule deliverySchedule or {@code null} for none
*/
public Ad setDeliverySchedule(DeliverySchedule deliverySchedule) {
this.deliverySchedule = deliverySchedule;
return this;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDynamicClickTracker() {
return dynamicClickTracker;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @param dynamicClickTracker dynamicClickTracker or {@code null} for none
*/
public Ad setDynamicClickTracker(java.lang.Boolean dynamicClickTracker) {
this.dynamicClickTracker = dynamicClickTracker;
return this;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getEndTime() {
return endTime;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @param endTime endTime or {@code null} for none
*/
public Ad setEndTime(com.google.api.client.util.DateTime endTime) {
this.endTime = endTime;
return this;
}
/**
* Event tag overrides for this ad.
* @return value or {@code null} for none
*/
public java.util.List<EventTagOverride> getEventTagOverrides() {
return eventTagOverrides;
}
/**
* Event tag overrides for this ad.
* @param eventTagOverrides eventTagOverrides or {@code null} for none
*/
public Ad setEventTagOverrides(java.util.List<EventTagOverride> eventTagOverrides) {
this.eventTagOverrides = eventTagOverrides;
return this;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public GeoTargeting getGeoTargeting() {
return geoTargeting;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param geoTargeting geoTargeting or {@code null} for none
*/
public Ad setGeoTargeting(GeoTargeting geoTargeting) {
this.geoTargeting = geoTargeting;
return this;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public java.lang.Long getId() {
return id;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @param id id or {@code null} for none
*/
public Ad setId(java.lang.Long id) {
this.id = id;
return this;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getIdDimensionValue() {
return idDimensionValue;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @param idDimensionValue idDimensionValue or {@code null} for none
*/
public Ad setIdDimensionValue(DimensionValue idDimensionValue) {
this.idDimensionValue = idDimensionValue;
return this;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public KeyValueTargetingExpression getKeyValueTargetingExpression() {
return keyValueTargetingExpression;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param keyValueTargetingExpression keyValueTargetingExpression or {@code null} for none
*/
public Ad setKeyValueTargetingExpression(KeyValueTargetingExpression keyValueTargetingExpression) {
this.keyValueTargetingExpression = keyValueTargetingExpression;
return this;
}
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* @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 "dfareporting#ad".
* @param kind kind or {@code null} for none
*/
public Ad setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public LanguageTargeting getLanguageTargeting() {
return languageTargeting;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param languageTargeting languageTargeting or {@code null} for none
*/
public Ad setLanguageTargeting(LanguageTargeting languageTargeting) {
this.languageTargeting = languageTargeting;
return this;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getLastModifiedInfo() {
return lastModifiedInfo;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @param lastModifiedInfo lastModifiedInfo or {@code null} for none
*/
public Ad setLastModifiedInfo(LastModifiedInfo lastModifiedInfo) {
this.lastModifiedInfo = lastModifiedInfo;
return this;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @param name name or {@code null} for none
*/
public Ad setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Placement assignments for this ad.
* @return value or {@code null} for none
*/
public java.util.List<PlacementAssignment> getPlacementAssignments() {
return placementAssignments;
}
/**
* Placement assignments for this ad.
* @param placementAssignments placementAssignments or {@code null} for none
*/
public Ad setPlacementAssignments(java.util.List<PlacementAssignment> placementAssignments) {
this.placementAssignments = placementAssignments;
return this;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public ListTargetingExpression getRemarketingListExpression() {
return remarketingListExpression;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param remarketingListExpression remarketingListExpression or {@code null} for none
*/
public Ad setRemarketingListExpression(ListTargetingExpression remarketingListExpression) {
this.remarketingListExpression = remarketingListExpression;
return this;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @return value or {@code null} for none
*/
public Size getSize() {
return size;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @param size size or {@code null} for none
*/
public Ad setSize(Size size) {
this.size = size;
return this;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslCompliant() {
return sslCompliant;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @param sslCompliant sslCompliant or {@code null} for none
*/
public Ad setSslCompliant(java.lang.Boolean sslCompliant) {
this.sslCompliant = sslCompliant;
return this;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslRequired() {
return sslRequired;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @param sslRequired sslRequired or {@code null} for none
*/
public Ad setSslRequired(java.lang.Boolean sslRequired) {
this.sslRequired = sslRequired;
return this;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getStartTime() {
return startTime;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @param startTime startTime or {@code null} for none
*/
public Ad setStartTime(com.google.api.client.util.DateTime startTime) {
this.startTime = startTime;
return this;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getSubaccountId() {
return subaccountId;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @param subaccountId subaccountId or {@code null} for none
*/
public Ad setSubaccountId(java.lang.Long subaccountId) {
this.subaccountId = subaccountId;
return this;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getTargetingTemplateId() {
return targetingTemplateId;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @param targetingTemplateId targetingTemplateId or {@code null} for none
*/
public Ad setTargetingTemplateId(java.lang.Long targetingTemplateId) {
this.targetingTemplateId = targetingTemplateId;
return this;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public TechnologyTargeting getTechnologyTargeting() {
return technologyTargeting;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param technologyTargeting technologyTargeting or {@code null} for none
*/
public Ad setTechnologyTargeting(TechnologyTargeting technologyTargeting) {
this.technologyTargeting = technologyTargeting;
return this;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @return value or {@code null} for none
*/
public java.lang.String getType() {
return type;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @param type type or {@code null} for none
*/
public Ad setType(java.lang.String type) {
this.type = type;
return this;
}
@Override
public Ad set(String fieldName, Object value) {
return (Ad) super.set(fieldName, value);
}
@Override
public Ad clone() {
return (Ad) super.clone();
}
}
|
googleapis/google-api-java-client-services | 36,499 | clients/google-api-services-dfareporting/v3.3/1.26.0/com/google/api/services/dfareporting/model/Ad.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.dfareporting.model;
/**
* Contains properties of a Campaign Manager ad.
*
* <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 DCM/DFA Reporting And Trafficking 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 Ad extends com.google.api.client.json.GenericJson {
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long accountId;
/**
* Whether this ad is active. When true, archived must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean active;
/**
* Advertiser ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long advertiserId;
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue advertiserIdDimensionValue;
/**
* Whether this ad is archived. When true, active must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean archived;
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long audienceSegmentId;
/**
* Campaign ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long campaignId;
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue campaignIdDimensionValue;
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrl clickThroughUrl;
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties;
/**
* Comments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String comments;
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String compatibility;
/**
* Information about the creation of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo createInfo;
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<CreativeGroupAssignment> creativeGroupAssignments;
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CreativeRotation creativeRotation;
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DayPartTargeting dayPartTargeting;
/**
* Default click-through event tag properties for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties;
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DeliverySchedule deliverySchedule;
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean dynamicClickTracker;
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime endTime;
/**
* Event tag overrides for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<EventTagOverride> eventTagOverrides;
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GeoTargeting geoTargeting;
/**
* ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long id;
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue idDimensionValue;
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private KeyValueTargetingExpression keyValueTargetingExpression;
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LanguageTargeting languageTargeting;
/**
* Information about the most recent modification of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo lastModifiedInfo;
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Placement assignments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<PlacementAssignment> placementAssignments;
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ListTargetingExpression remarketingListExpression;
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Size size;
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslCompliant;
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslRequired;
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime startTime;
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long subaccountId;
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long targetingTemplateId;
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TechnologyTargeting technologyTargeting;
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String type;
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getAccountId() {
return accountId;
}
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @param accountId accountId or {@code null} for none
*/
public Ad setAccountId(java.lang.Long accountId) {
this.accountId = accountId;
return this;
}
/**
* Whether this ad is active. When true, archived must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getActive() {
return active;
}
/**
* Whether this ad is active. When true, archived must be false.
* @param active active or {@code null} for none
*/
public Ad setActive(java.lang.Boolean active) {
this.active = active;
return this;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getAdvertiserId() {
return advertiserId;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @param advertiserId advertiserId or {@code null} for none
*/
public Ad setAdvertiserId(java.lang.Long advertiserId) {
this.advertiserId = advertiserId;
return this;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getAdvertiserIdDimensionValue() {
return advertiserIdDimensionValue;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @param advertiserIdDimensionValue advertiserIdDimensionValue or {@code null} for none
*/
public Ad setAdvertiserIdDimensionValue(DimensionValue advertiserIdDimensionValue) {
this.advertiserIdDimensionValue = advertiserIdDimensionValue;
return this;
}
/**
* Whether this ad is archived. When true, active must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getArchived() {
return archived;
}
/**
* Whether this ad is archived. When true, active must be false.
* @param archived archived or {@code null} for none
*/
public Ad setArchived(java.lang.Boolean archived) {
this.archived = archived;
return this;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getAudienceSegmentId() {
return audienceSegmentId;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @param audienceSegmentId audienceSegmentId or {@code null} for none
*/
public Ad setAudienceSegmentId(java.lang.Long audienceSegmentId) {
this.audienceSegmentId = audienceSegmentId;
return this;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getCampaignId() {
return campaignId;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @param campaignId campaignId or {@code null} for none
*/
public Ad setCampaignId(java.lang.Long campaignId) {
this.campaignId = campaignId;
return this;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getCampaignIdDimensionValue() {
return campaignIdDimensionValue;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @param campaignIdDimensionValue campaignIdDimensionValue or {@code null} for none
*/
public Ad setCampaignIdDimensionValue(DimensionValue campaignIdDimensionValue) {
this.campaignIdDimensionValue = campaignIdDimensionValue;
return this;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @return value or {@code null} for none
*/
public ClickThroughUrl getClickThroughUrl() {
return clickThroughUrl;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @param clickThroughUrl clickThroughUrl or {@code null} for none
*/
public Ad setClickThroughUrl(ClickThroughUrl clickThroughUrl) {
this.clickThroughUrl = clickThroughUrl;
return this;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @return value or {@code null} for none
*/
public ClickThroughUrlSuffixProperties getClickThroughUrlSuffixProperties() {
return clickThroughUrlSuffixProperties;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @param clickThroughUrlSuffixProperties clickThroughUrlSuffixProperties or {@code null} for none
*/
public Ad setClickThroughUrlSuffixProperties(ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties) {
this.clickThroughUrlSuffixProperties = clickThroughUrlSuffixProperties;
return this;
}
/**
* Comments for this ad.
* @return value or {@code null} for none
*/
public java.lang.String getComments() {
return comments;
}
/**
* Comments for this ad.
* @param comments comments or {@code null} for none
*/
public Ad setComments(java.lang.String comments) {
this.comments = comments;
return this;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @return value or {@code null} for none
*/
public java.lang.String getCompatibility() {
return compatibility;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @param compatibility compatibility or {@code null} for none
*/
public Ad setCompatibility(java.lang.String compatibility) {
this.compatibility = compatibility;
return this;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getCreateInfo() {
return createInfo;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @param createInfo createInfo or {@code null} for none
*/
public Ad setCreateInfo(LastModifiedInfo createInfo) {
this.createInfo = createInfo;
return this;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @return value or {@code null} for none
*/
public java.util.List<CreativeGroupAssignment> getCreativeGroupAssignments() {
return creativeGroupAssignments;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @param creativeGroupAssignments creativeGroupAssignments or {@code null} for none
*/
public Ad setCreativeGroupAssignments(java.util.List<CreativeGroupAssignment> creativeGroupAssignments) {
this.creativeGroupAssignments = creativeGroupAssignments;
return this;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @return value or {@code null} for none
*/
public CreativeRotation getCreativeRotation() {
return creativeRotation;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @param creativeRotation creativeRotation or {@code null} for none
*/
public Ad setCreativeRotation(CreativeRotation creativeRotation) {
this.creativeRotation = creativeRotation;
return this;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DayPartTargeting getDayPartTargeting() {
return dayPartTargeting;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param dayPartTargeting dayPartTargeting or {@code null} for none
*/
public Ad setDayPartTargeting(DayPartTargeting dayPartTargeting) {
this.dayPartTargeting = dayPartTargeting;
return this;
}
/**
* Default click-through event tag properties for this ad.
* @return value or {@code null} for none
*/
public DefaultClickThroughEventTagProperties getDefaultClickThroughEventTagProperties() {
return defaultClickThroughEventTagProperties;
}
/**
* Default click-through event tag properties for this ad.
* @param defaultClickThroughEventTagProperties defaultClickThroughEventTagProperties or {@code null} for none
*/
public Ad setDefaultClickThroughEventTagProperties(DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties) {
this.defaultClickThroughEventTagProperties = defaultClickThroughEventTagProperties;
return this;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DeliverySchedule getDeliverySchedule() {
return deliverySchedule;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @param deliverySchedule deliverySchedule or {@code null} for none
*/
public Ad setDeliverySchedule(DeliverySchedule deliverySchedule) {
this.deliverySchedule = deliverySchedule;
return this;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDynamicClickTracker() {
return dynamicClickTracker;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @param dynamicClickTracker dynamicClickTracker or {@code null} for none
*/
public Ad setDynamicClickTracker(java.lang.Boolean dynamicClickTracker) {
this.dynamicClickTracker = dynamicClickTracker;
return this;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getEndTime() {
return endTime;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @param endTime endTime or {@code null} for none
*/
public Ad setEndTime(com.google.api.client.util.DateTime endTime) {
this.endTime = endTime;
return this;
}
/**
* Event tag overrides for this ad.
* @return value or {@code null} for none
*/
public java.util.List<EventTagOverride> getEventTagOverrides() {
return eventTagOverrides;
}
/**
* Event tag overrides for this ad.
* @param eventTagOverrides eventTagOverrides or {@code null} for none
*/
public Ad setEventTagOverrides(java.util.List<EventTagOverride> eventTagOverrides) {
this.eventTagOverrides = eventTagOverrides;
return this;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public GeoTargeting getGeoTargeting() {
return geoTargeting;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param geoTargeting geoTargeting or {@code null} for none
*/
public Ad setGeoTargeting(GeoTargeting geoTargeting) {
this.geoTargeting = geoTargeting;
return this;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public java.lang.Long getId() {
return id;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @param id id or {@code null} for none
*/
public Ad setId(java.lang.Long id) {
this.id = id;
return this;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getIdDimensionValue() {
return idDimensionValue;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @param idDimensionValue idDimensionValue or {@code null} for none
*/
public Ad setIdDimensionValue(DimensionValue idDimensionValue) {
this.idDimensionValue = idDimensionValue;
return this;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public KeyValueTargetingExpression getKeyValueTargetingExpression() {
return keyValueTargetingExpression;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param keyValueTargetingExpression keyValueTargetingExpression or {@code null} for none
*/
public Ad setKeyValueTargetingExpression(KeyValueTargetingExpression keyValueTargetingExpression) {
this.keyValueTargetingExpression = keyValueTargetingExpression;
return this;
}
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* @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 "dfareporting#ad".
* @param kind kind or {@code null} for none
*/
public Ad setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public LanguageTargeting getLanguageTargeting() {
return languageTargeting;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param languageTargeting languageTargeting or {@code null} for none
*/
public Ad setLanguageTargeting(LanguageTargeting languageTargeting) {
this.languageTargeting = languageTargeting;
return this;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getLastModifiedInfo() {
return lastModifiedInfo;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @param lastModifiedInfo lastModifiedInfo or {@code null} for none
*/
public Ad setLastModifiedInfo(LastModifiedInfo lastModifiedInfo) {
this.lastModifiedInfo = lastModifiedInfo;
return this;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @param name name or {@code null} for none
*/
public Ad setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Placement assignments for this ad.
* @return value or {@code null} for none
*/
public java.util.List<PlacementAssignment> getPlacementAssignments() {
return placementAssignments;
}
/**
* Placement assignments for this ad.
* @param placementAssignments placementAssignments or {@code null} for none
*/
public Ad setPlacementAssignments(java.util.List<PlacementAssignment> placementAssignments) {
this.placementAssignments = placementAssignments;
return this;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public ListTargetingExpression getRemarketingListExpression() {
return remarketingListExpression;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param remarketingListExpression remarketingListExpression or {@code null} for none
*/
public Ad setRemarketingListExpression(ListTargetingExpression remarketingListExpression) {
this.remarketingListExpression = remarketingListExpression;
return this;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @return value or {@code null} for none
*/
public Size getSize() {
return size;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @param size size or {@code null} for none
*/
public Ad setSize(Size size) {
this.size = size;
return this;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslCompliant() {
return sslCompliant;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @param sslCompliant sslCompliant or {@code null} for none
*/
public Ad setSslCompliant(java.lang.Boolean sslCompliant) {
this.sslCompliant = sslCompliant;
return this;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslRequired() {
return sslRequired;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @param sslRequired sslRequired or {@code null} for none
*/
public Ad setSslRequired(java.lang.Boolean sslRequired) {
this.sslRequired = sslRequired;
return this;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getStartTime() {
return startTime;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @param startTime startTime or {@code null} for none
*/
public Ad setStartTime(com.google.api.client.util.DateTime startTime) {
this.startTime = startTime;
return this;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getSubaccountId() {
return subaccountId;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @param subaccountId subaccountId or {@code null} for none
*/
public Ad setSubaccountId(java.lang.Long subaccountId) {
this.subaccountId = subaccountId;
return this;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getTargetingTemplateId() {
return targetingTemplateId;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @param targetingTemplateId targetingTemplateId or {@code null} for none
*/
public Ad setTargetingTemplateId(java.lang.Long targetingTemplateId) {
this.targetingTemplateId = targetingTemplateId;
return this;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public TechnologyTargeting getTechnologyTargeting() {
return technologyTargeting;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param technologyTargeting technologyTargeting or {@code null} for none
*/
public Ad setTechnologyTargeting(TechnologyTargeting technologyTargeting) {
this.technologyTargeting = technologyTargeting;
return this;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @return value or {@code null} for none
*/
public java.lang.String getType() {
return type;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @param type type or {@code null} for none
*/
public Ad setType(java.lang.String type) {
this.type = type;
return this;
}
@Override
public Ad set(String fieldName, Object value) {
return (Ad) super.set(fieldName, value);
}
@Override
public Ad clone() {
return (Ad) super.clone();
}
}
|
googleapis/google-api-java-client-services | 36,499 | clients/google-api-services-dfareporting/v3.3/1.27.0/com/google/api/services/dfareporting/model/Ad.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.dfareporting.model;
/**
* Contains properties of a Campaign Manager ad.
*
* <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 DCM/DFA Reporting And Trafficking 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 Ad extends com.google.api.client.json.GenericJson {
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long accountId;
/**
* Whether this ad is active. When true, archived must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean active;
/**
* Advertiser ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long advertiserId;
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue advertiserIdDimensionValue;
/**
* Whether this ad is archived. When true, active must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean archived;
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long audienceSegmentId;
/**
* Campaign ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long campaignId;
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue campaignIdDimensionValue;
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrl clickThroughUrl;
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties;
/**
* Comments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String comments;
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String compatibility;
/**
* Information about the creation of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo createInfo;
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<CreativeGroupAssignment> creativeGroupAssignments;
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CreativeRotation creativeRotation;
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DayPartTargeting dayPartTargeting;
/**
* Default click-through event tag properties for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties;
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DeliverySchedule deliverySchedule;
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean dynamicClickTracker;
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime endTime;
/**
* Event tag overrides for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<EventTagOverride> eventTagOverrides;
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GeoTargeting geoTargeting;
/**
* ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long id;
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue idDimensionValue;
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private KeyValueTargetingExpression keyValueTargetingExpression;
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LanguageTargeting languageTargeting;
/**
* Information about the most recent modification of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo lastModifiedInfo;
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Placement assignments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<PlacementAssignment> placementAssignments;
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ListTargetingExpression remarketingListExpression;
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Size size;
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslCompliant;
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslRequired;
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime startTime;
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long subaccountId;
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long targetingTemplateId;
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TechnologyTargeting technologyTargeting;
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String type;
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getAccountId() {
return accountId;
}
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @param accountId accountId or {@code null} for none
*/
public Ad setAccountId(java.lang.Long accountId) {
this.accountId = accountId;
return this;
}
/**
* Whether this ad is active. When true, archived must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getActive() {
return active;
}
/**
* Whether this ad is active. When true, archived must be false.
* @param active active or {@code null} for none
*/
public Ad setActive(java.lang.Boolean active) {
this.active = active;
return this;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getAdvertiserId() {
return advertiserId;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @param advertiserId advertiserId or {@code null} for none
*/
public Ad setAdvertiserId(java.lang.Long advertiserId) {
this.advertiserId = advertiserId;
return this;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getAdvertiserIdDimensionValue() {
return advertiserIdDimensionValue;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @param advertiserIdDimensionValue advertiserIdDimensionValue or {@code null} for none
*/
public Ad setAdvertiserIdDimensionValue(DimensionValue advertiserIdDimensionValue) {
this.advertiserIdDimensionValue = advertiserIdDimensionValue;
return this;
}
/**
* Whether this ad is archived. When true, active must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getArchived() {
return archived;
}
/**
* Whether this ad is archived. When true, active must be false.
* @param archived archived or {@code null} for none
*/
public Ad setArchived(java.lang.Boolean archived) {
this.archived = archived;
return this;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getAudienceSegmentId() {
return audienceSegmentId;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @param audienceSegmentId audienceSegmentId or {@code null} for none
*/
public Ad setAudienceSegmentId(java.lang.Long audienceSegmentId) {
this.audienceSegmentId = audienceSegmentId;
return this;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getCampaignId() {
return campaignId;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @param campaignId campaignId or {@code null} for none
*/
public Ad setCampaignId(java.lang.Long campaignId) {
this.campaignId = campaignId;
return this;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getCampaignIdDimensionValue() {
return campaignIdDimensionValue;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @param campaignIdDimensionValue campaignIdDimensionValue or {@code null} for none
*/
public Ad setCampaignIdDimensionValue(DimensionValue campaignIdDimensionValue) {
this.campaignIdDimensionValue = campaignIdDimensionValue;
return this;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @return value or {@code null} for none
*/
public ClickThroughUrl getClickThroughUrl() {
return clickThroughUrl;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @param clickThroughUrl clickThroughUrl or {@code null} for none
*/
public Ad setClickThroughUrl(ClickThroughUrl clickThroughUrl) {
this.clickThroughUrl = clickThroughUrl;
return this;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @return value or {@code null} for none
*/
public ClickThroughUrlSuffixProperties getClickThroughUrlSuffixProperties() {
return clickThroughUrlSuffixProperties;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @param clickThroughUrlSuffixProperties clickThroughUrlSuffixProperties or {@code null} for none
*/
public Ad setClickThroughUrlSuffixProperties(ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties) {
this.clickThroughUrlSuffixProperties = clickThroughUrlSuffixProperties;
return this;
}
/**
* Comments for this ad.
* @return value or {@code null} for none
*/
public java.lang.String getComments() {
return comments;
}
/**
* Comments for this ad.
* @param comments comments or {@code null} for none
*/
public Ad setComments(java.lang.String comments) {
this.comments = comments;
return this;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @return value or {@code null} for none
*/
public java.lang.String getCompatibility() {
return compatibility;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @param compatibility compatibility or {@code null} for none
*/
public Ad setCompatibility(java.lang.String compatibility) {
this.compatibility = compatibility;
return this;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getCreateInfo() {
return createInfo;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @param createInfo createInfo or {@code null} for none
*/
public Ad setCreateInfo(LastModifiedInfo createInfo) {
this.createInfo = createInfo;
return this;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @return value or {@code null} for none
*/
public java.util.List<CreativeGroupAssignment> getCreativeGroupAssignments() {
return creativeGroupAssignments;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @param creativeGroupAssignments creativeGroupAssignments or {@code null} for none
*/
public Ad setCreativeGroupAssignments(java.util.List<CreativeGroupAssignment> creativeGroupAssignments) {
this.creativeGroupAssignments = creativeGroupAssignments;
return this;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @return value or {@code null} for none
*/
public CreativeRotation getCreativeRotation() {
return creativeRotation;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @param creativeRotation creativeRotation or {@code null} for none
*/
public Ad setCreativeRotation(CreativeRotation creativeRotation) {
this.creativeRotation = creativeRotation;
return this;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DayPartTargeting getDayPartTargeting() {
return dayPartTargeting;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param dayPartTargeting dayPartTargeting or {@code null} for none
*/
public Ad setDayPartTargeting(DayPartTargeting dayPartTargeting) {
this.dayPartTargeting = dayPartTargeting;
return this;
}
/**
* Default click-through event tag properties for this ad.
* @return value or {@code null} for none
*/
public DefaultClickThroughEventTagProperties getDefaultClickThroughEventTagProperties() {
return defaultClickThroughEventTagProperties;
}
/**
* Default click-through event tag properties for this ad.
* @param defaultClickThroughEventTagProperties defaultClickThroughEventTagProperties or {@code null} for none
*/
public Ad setDefaultClickThroughEventTagProperties(DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties) {
this.defaultClickThroughEventTagProperties = defaultClickThroughEventTagProperties;
return this;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DeliverySchedule getDeliverySchedule() {
return deliverySchedule;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @param deliverySchedule deliverySchedule or {@code null} for none
*/
public Ad setDeliverySchedule(DeliverySchedule deliverySchedule) {
this.deliverySchedule = deliverySchedule;
return this;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDynamicClickTracker() {
return dynamicClickTracker;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @param dynamicClickTracker dynamicClickTracker or {@code null} for none
*/
public Ad setDynamicClickTracker(java.lang.Boolean dynamicClickTracker) {
this.dynamicClickTracker = dynamicClickTracker;
return this;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getEndTime() {
return endTime;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @param endTime endTime or {@code null} for none
*/
public Ad setEndTime(com.google.api.client.util.DateTime endTime) {
this.endTime = endTime;
return this;
}
/**
* Event tag overrides for this ad.
* @return value or {@code null} for none
*/
public java.util.List<EventTagOverride> getEventTagOverrides() {
return eventTagOverrides;
}
/**
* Event tag overrides for this ad.
* @param eventTagOverrides eventTagOverrides or {@code null} for none
*/
public Ad setEventTagOverrides(java.util.List<EventTagOverride> eventTagOverrides) {
this.eventTagOverrides = eventTagOverrides;
return this;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public GeoTargeting getGeoTargeting() {
return geoTargeting;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param geoTargeting geoTargeting or {@code null} for none
*/
public Ad setGeoTargeting(GeoTargeting geoTargeting) {
this.geoTargeting = geoTargeting;
return this;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public java.lang.Long getId() {
return id;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @param id id or {@code null} for none
*/
public Ad setId(java.lang.Long id) {
this.id = id;
return this;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getIdDimensionValue() {
return idDimensionValue;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @param idDimensionValue idDimensionValue or {@code null} for none
*/
public Ad setIdDimensionValue(DimensionValue idDimensionValue) {
this.idDimensionValue = idDimensionValue;
return this;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public KeyValueTargetingExpression getKeyValueTargetingExpression() {
return keyValueTargetingExpression;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param keyValueTargetingExpression keyValueTargetingExpression or {@code null} for none
*/
public Ad setKeyValueTargetingExpression(KeyValueTargetingExpression keyValueTargetingExpression) {
this.keyValueTargetingExpression = keyValueTargetingExpression;
return this;
}
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* @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 "dfareporting#ad".
* @param kind kind or {@code null} for none
*/
public Ad setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public LanguageTargeting getLanguageTargeting() {
return languageTargeting;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param languageTargeting languageTargeting or {@code null} for none
*/
public Ad setLanguageTargeting(LanguageTargeting languageTargeting) {
this.languageTargeting = languageTargeting;
return this;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getLastModifiedInfo() {
return lastModifiedInfo;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @param lastModifiedInfo lastModifiedInfo or {@code null} for none
*/
public Ad setLastModifiedInfo(LastModifiedInfo lastModifiedInfo) {
this.lastModifiedInfo = lastModifiedInfo;
return this;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @param name name or {@code null} for none
*/
public Ad setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Placement assignments for this ad.
* @return value or {@code null} for none
*/
public java.util.List<PlacementAssignment> getPlacementAssignments() {
return placementAssignments;
}
/**
* Placement assignments for this ad.
* @param placementAssignments placementAssignments or {@code null} for none
*/
public Ad setPlacementAssignments(java.util.List<PlacementAssignment> placementAssignments) {
this.placementAssignments = placementAssignments;
return this;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public ListTargetingExpression getRemarketingListExpression() {
return remarketingListExpression;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param remarketingListExpression remarketingListExpression or {@code null} for none
*/
public Ad setRemarketingListExpression(ListTargetingExpression remarketingListExpression) {
this.remarketingListExpression = remarketingListExpression;
return this;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @return value or {@code null} for none
*/
public Size getSize() {
return size;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @param size size or {@code null} for none
*/
public Ad setSize(Size size) {
this.size = size;
return this;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslCompliant() {
return sslCompliant;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @param sslCompliant sslCompliant or {@code null} for none
*/
public Ad setSslCompliant(java.lang.Boolean sslCompliant) {
this.sslCompliant = sslCompliant;
return this;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslRequired() {
return sslRequired;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @param sslRequired sslRequired or {@code null} for none
*/
public Ad setSslRequired(java.lang.Boolean sslRequired) {
this.sslRequired = sslRequired;
return this;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getStartTime() {
return startTime;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @param startTime startTime or {@code null} for none
*/
public Ad setStartTime(com.google.api.client.util.DateTime startTime) {
this.startTime = startTime;
return this;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getSubaccountId() {
return subaccountId;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @param subaccountId subaccountId or {@code null} for none
*/
public Ad setSubaccountId(java.lang.Long subaccountId) {
this.subaccountId = subaccountId;
return this;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getTargetingTemplateId() {
return targetingTemplateId;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @param targetingTemplateId targetingTemplateId or {@code null} for none
*/
public Ad setTargetingTemplateId(java.lang.Long targetingTemplateId) {
this.targetingTemplateId = targetingTemplateId;
return this;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public TechnologyTargeting getTechnologyTargeting() {
return technologyTargeting;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param technologyTargeting technologyTargeting or {@code null} for none
*/
public Ad setTechnologyTargeting(TechnologyTargeting technologyTargeting) {
this.technologyTargeting = technologyTargeting;
return this;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @return value or {@code null} for none
*/
public java.lang.String getType() {
return type;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @param type type or {@code null} for none
*/
public Ad setType(java.lang.String type) {
this.type = type;
return this;
}
@Override
public Ad set(String fieldName, Object value) {
return (Ad) super.set(fieldName, value);
}
@Override
public Ad clone() {
return (Ad) super.clone();
}
}
|
googleapis/google-api-java-client-services | 36,499 | clients/google-api-services-dfareporting/v3.3/1.28.0/com/google/api/services/dfareporting/model/Ad.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.dfareporting.model;
/**
* Contains properties of a Campaign Manager ad.
*
* <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 DCM/DFA Reporting And Trafficking 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 Ad extends com.google.api.client.json.GenericJson {
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long accountId;
/**
* Whether this ad is active. When true, archived must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean active;
/**
* Advertiser ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long advertiserId;
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue advertiserIdDimensionValue;
/**
* Whether this ad is archived. When true, active must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean archived;
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long audienceSegmentId;
/**
* Campaign ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long campaignId;
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue campaignIdDimensionValue;
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrl clickThroughUrl;
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties;
/**
* Comments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String comments;
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String compatibility;
/**
* Information about the creation of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo createInfo;
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<CreativeGroupAssignment> creativeGroupAssignments;
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CreativeRotation creativeRotation;
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DayPartTargeting dayPartTargeting;
/**
* Default click-through event tag properties for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties;
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DeliverySchedule deliverySchedule;
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean dynamicClickTracker;
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime endTime;
/**
* Event tag overrides for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<EventTagOverride> eventTagOverrides;
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GeoTargeting geoTargeting;
/**
* ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long id;
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue idDimensionValue;
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private KeyValueTargetingExpression keyValueTargetingExpression;
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LanguageTargeting languageTargeting;
/**
* Information about the most recent modification of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo lastModifiedInfo;
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Placement assignments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<PlacementAssignment> placementAssignments;
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ListTargetingExpression remarketingListExpression;
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Size size;
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslCompliant;
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslRequired;
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime startTime;
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long subaccountId;
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long targetingTemplateId;
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TechnologyTargeting technologyTargeting;
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String type;
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getAccountId() {
return accountId;
}
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @param accountId accountId or {@code null} for none
*/
public Ad setAccountId(java.lang.Long accountId) {
this.accountId = accountId;
return this;
}
/**
* Whether this ad is active. When true, archived must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getActive() {
return active;
}
/**
* Whether this ad is active. When true, archived must be false.
* @param active active or {@code null} for none
*/
public Ad setActive(java.lang.Boolean active) {
this.active = active;
return this;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getAdvertiserId() {
return advertiserId;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @param advertiserId advertiserId or {@code null} for none
*/
public Ad setAdvertiserId(java.lang.Long advertiserId) {
this.advertiserId = advertiserId;
return this;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getAdvertiserIdDimensionValue() {
return advertiserIdDimensionValue;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @param advertiserIdDimensionValue advertiserIdDimensionValue or {@code null} for none
*/
public Ad setAdvertiserIdDimensionValue(DimensionValue advertiserIdDimensionValue) {
this.advertiserIdDimensionValue = advertiserIdDimensionValue;
return this;
}
/**
* Whether this ad is archived. When true, active must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getArchived() {
return archived;
}
/**
* Whether this ad is archived. When true, active must be false.
* @param archived archived or {@code null} for none
*/
public Ad setArchived(java.lang.Boolean archived) {
this.archived = archived;
return this;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getAudienceSegmentId() {
return audienceSegmentId;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @param audienceSegmentId audienceSegmentId or {@code null} for none
*/
public Ad setAudienceSegmentId(java.lang.Long audienceSegmentId) {
this.audienceSegmentId = audienceSegmentId;
return this;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getCampaignId() {
return campaignId;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @param campaignId campaignId or {@code null} for none
*/
public Ad setCampaignId(java.lang.Long campaignId) {
this.campaignId = campaignId;
return this;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getCampaignIdDimensionValue() {
return campaignIdDimensionValue;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @param campaignIdDimensionValue campaignIdDimensionValue or {@code null} for none
*/
public Ad setCampaignIdDimensionValue(DimensionValue campaignIdDimensionValue) {
this.campaignIdDimensionValue = campaignIdDimensionValue;
return this;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @return value or {@code null} for none
*/
public ClickThroughUrl getClickThroughUrl() {
return clickThroughUrl;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @param clickThroughUrl clickThroughUrl or {@code null} for none
*/
public Ad setClickThroughUrl(ClickThroughUrl clickThroughUrl) {
this.clickThroughUrl = clickThroughUrl;
return this;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @return value or {@code null} for none
*/
public ClickThroughUrlSuffixProperties getClickThroughUrlSuffixProperties() {
return clickThroughUrlSuffixProperties;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @param clickThroughUrlSuffixProperties clickThroughUrlSuffixProperties or {@code null} for none
*/
public Ad setClickThroughUrlSuffixProperties(ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties) {
this.clickThroughUrlSuffixProperties = clickThroughUrlSuffixProperties;
return this;
}
/**
* Comments for this ad.
* @return value or {@code null} for none
*/
public java.lang.String getComments() {
return comments;
}
/**
* Comments for this ad.
* @param comments comments or {@code null} for none
*/
public Ad setComments(java.lang.String comments) {
this.comments = comments;
return this;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @return value or {@code null} for none
*/
public java.lang.String getCompatibility() {
return compatibility;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @param compatibility compatibility or {@code null} for none
*/
public Ad setCompatibility(java.lang.String compatibility) {
this.compatibility = compatibility;
return this;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getCreateInfo() {
return createInfo;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @param createInfo createInfo or {@code null} for none
*/
public Ad setCreateInfo(LastModifiedInfo createInfo) {
this.createInfo = createInfo;
return this;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @return value or {@code null} for none
*/
public java.util.List<CreativeGroupAssignment> getCreativeGroupAssignments() {
return creativeGroupAssignments;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @param creativeGroupAssignments creativeGroupAssignments or {@code null} for none
*/
public Ad setCreativeGroupAssignments(java.util.List<CreativeGroupAssignment> creativeGroupAssignments) {
this.creativeGroupAssignments = creativeGroupAssignments;
return this;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @return value or {@code null} for none
*/
public CreativeRotation getCreativeRotation() {
return creativeRotation;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @param creativeRotation creativeRotation or {@code null} for none
*/
public Ad setCreativeRotation(CreativeRotation creativeRotation) {
this.creativeRotation = creativeRotation;
return this;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DayPartTargeting getDayPartTargeting() {
return dayPartTargeting;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param dayPartTargeting dayPartTargeting or {@code null} for none
*/
public Ad setDayPartTargeting(DayPartTargeting dayPartTargeting) {
this.dayPartTargeting = dayPartTargeting;
return this;
}
/**
* Default click-through event tag properties for this ad.
* @return value or {@code null} for none
*/
public DefaultClickThroughEventTagProperties getDefaultClickThroughEventTagProperties() {
return defaultClickThroughEventTagProperties;
}
/**
* Default click-through event tag properties for this ad.
* @param defaultClickThroughEventTagProperties defaultClickThroughEventTagProperties or {@code null} for none
*/
public Ad setDefaultClickThroughEventTagProperties(DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties) {
this.defaultClickThroughEventTagProperties = defaultClickThroughEventTagProperties;
return this;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DeliverySchedule getDeliverySchedule() {
return deliverySchedule;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @param deliverySchedule deliverySchedule or {@code null} for none
*/
public Ad setDeliverySchedule(DeliverySchedule deliverySchedule) {
this.deliverySchedule = deliverySchedule;
return this;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDynamicClickTracker() {
return dynamicClickTracker;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @param dynamicClickTracker dynamicClickTracker or {@code null} for none
*/
public Ad setDynamicClickTracker(java.lang.Boolean dynamicClickTracker) {
this.dynamicClickTracker = dynamicClickTracker;
return this;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getEndTime() {
return endTime;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @param endTime endTime or {@code null} for none
*/
public Ad setEndTime(com.google.api.client.util.DateTime endTime) {
this.endTime = endTime;
return this;
}
/**
* Event tag overrides for this ad.
* @return value or {@code null} for none
*/
public java.util.List<EventTagOverride> getEventTagOverrides() {
return eventTagOverrides;
}
/**
* Event tag overrides for this ad.
* @param eventTagOverrides eventTagOverrides or {@code null} for none
*/
public Ad setEventTagOverrides(java.util.List<EventTagOverride> eventTagOverrides) {
this.eventTagOverrides = eventTagOverrides;
return this;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public GeoTargeting getGeoTargeting() {
return geoTargeting;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param geoTargeting geoTargeting or {@code null} for none
*/
public Ad setGeoTargeting(GeoTargeting geoTargeting) {
this.geoTargeting = geoTargeting;
return this;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public java.lang.Long getId() {
return id;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @param id id or {@code null} for none
*/
public Ad setId(java.lang.Long id) {
this.id = id;
return this;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getIdDimensionValue() {
return idDimensionValue;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @param idDimensionValue idDimensionValue or {@code null} for none
*/
public Ad setIdDimensionValue(DimensionValue idDimensionValue) {
this.idDimensionValue = idDimensionValue;
return this;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public KeyValueTargetingExpression getKeyValueTargetingExpression() {
return keyValueTargetingExpression;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param keyValueTargetingExpression keyValueTargetingExpression or {@code null} for none
*/
public Ad setKeyValueTargetingExpression(KeyValueTargetingExpression keyValueTargetingExpression) {
this.keyValueTargetingExpression = keyValueTargetingExpression;
return this;
}
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* @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 "dfareporting#ad".
* @param kind kind or {@code null} for none
*/
public Ad setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public LanguageTargeting getLanguageTargeting() {
return languageTargeting;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param languageTargeting languageTargeting or {@code null} for none
*/
public Ad setLanguageTargeting(LanguageTargeting languageTargeting) {
this.languageTargeting = languageTargeting;
return this;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getLastModifiedInfo() {
return lastModifiedInfo;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @param lastModifiedInfo lastModifiedInfo or {@code null} for none
*/
public Ad setLastModifiedInfo(LastModifiedInfo lastModifiedInfo) {
this.lastModifiedInfo = lastModifiedInfo;
return this;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @param name name or {@code null} for none
*/
public Ad setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Placement assignments for this ad.
* @return value or {@code null} for none
*/
public java.util.List<PlacementAssignment> getPlacementAssignments() {
return placementAssignments;
}
/**
* Placement assignments for this ad.
* @param placementAssignments placementAssignments or {@code null} for none
*/
public Ad setPlacementAssignments(java.util.List<PlacementAssignment> placementAssignments) {
this.placementAssignments = placementAssignments;
return this;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public ListTargetingExpression getRemarketingListExpression() {
return remarketingListExpression;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param remarketingListExpression remarketingListExpression or {@code null} for none
*/
public Ad setRemarketingListExpression(ListTargetingExpression remarketingListExpression) {
this.remarketingListExpression = remarketingListExpression;
return this;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @return value or {@code null} for none
*/
public Size getSize() {
return size;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @param size size or {@code null} for none
*/
public Ad setSize(Size size) {
this.size = size;
return this;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslCompliant() {
return sslCompliant;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @param sslCompliant sslCompliant or {@code null} for none
*/
public Ad setSslCompliant(java.lang.Boolean sslCompliant) {
this.sslCompliant = sslCompliant;
return this;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslRequired() {
return sslRequired;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @param sslRequired sslRequired or {@code null} for none
*/
public Ad setSslRequired(java.lang.Boolean sslRequired) {
this.sslRequired = sslRequired;
return this;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getStartTime() {
return startTime;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @param startTime startTime or {@code null} for none
*/
public Ad setStartTime(com.google.api.client.util.DateTime startTime) {
this.startTime = startTime;
return this;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getSubaccountId() {
return subaccountId;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @param subaccountId subaccountId or {@code null} for none
*/
public Ad setSubaccountId(java.lang.Long subaccountId) {
this.subaccountId = subaccountId;
return this;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getTargetingTemplateId() {
return targetingTemplateId;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @param targetingTemplateId targetingTemplateId or {@code null} for none
*/
public Ad setTargetingTemplateId(java.lang.Long targetingTemplateId) {
this.targetingTemplateId = targetingTemplateId;
return this;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public TechnologyTargeting getTechnologyTargeting() {
return technologyTargeting;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param technologyTargeting technologyTargeting or {@code null} for none
*/
public Ad setTechnologyTargeting(TechnologyTargeting technologyTargeting) {
this.technologyTargeting = technologyTargeting;
return this;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @return value or {@code null} for none
*/
public java.lang.String getType() {
return type;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @param type type or {@code null} for none
*/
public Ad setType(java.lang.String type) {
this.type = type;
return this;
}
@Override
public Ad set(String fieldName, Object value) {
return (Ad) super.set(fieldName, value);
}
@Override
public Ad clone() {
return (Ad) super.clone();
}
}
|
googleapis/google-api-java-client-services | 36,499 | clients/google-api-services-dfareporting/v3.3/1.29.2/com/google/api/services/dfareporting/model/Ad.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.dfareporting.model;
/**
* Contains properties of a Campaign Manager ad.
*
* <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 DCM/DFA Reporting And Trafficking 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 Ad extends com.google.api.client.json.GenericJson {
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long accountId;
/**
* Whether this ad is active. When true, archived must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean active;
/**
* Advertiser ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long advertiserId;
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue advertiserIdDimensionValue;
/**
* Whether this ad is archived. When true, active must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean archived;
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long audienceSegmentId;
/**
* Campaign ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long campaignId;
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue campaignIdDimensionValue;
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrl clickThroughUrl;
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties;
/**
* Comments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String comments;
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String compatibility;
/**
* Information about the creation of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo createInfo;
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<CreativeGroupAssignment> creativeGroupAssignments;
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CreativeRotation creativeRotation;
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DayPartTargeting dayPartTargeting;
/**
* Default click-through event tag properties for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties;
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DeliverySchedule deliverySchedule;
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean dynamicClickTracker;
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime endTime;
/**
* Event tag overrides for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<EventTagOverride> eventTagOverrides;
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GeoTargeting geoTargeting;
/**
* ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long id;
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue idDimensionValue;
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private KeyValueTargetingExpression keyValueTargetingExpression;
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LanguageTargeting languageTargeting;
/**
* Information about the most recent modification of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo lastModifiedInfo;
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Placement assignments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<PlacementAssignment> placementAssignments;
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ListTargetingExpression remarketingListExpression;
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Size size;
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslCompliant;
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslRequired;
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime startTime;
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long subaccountId;
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long targetingTemplateId;
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TechnologyTargeting technologyTargeting;
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String type;
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getAccountId() {
return accountId;
}
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @param accountId accountId or {@code null} for none
*/
public Ad setAccountId(java.lang.Long accountId) {
this.accountId = accountId;
return this;
}
/**
* Whether this ad is active. When true, archived must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getActive() {
return active;
}
/**
* Whether this ad is active. When true, archived must be false.
* @param active active or {@code null} for none
*/
public Ad setActive(java.lang.Boolean active) {
this.active = active;
return this;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getAdvertiserId() {
return advertiserId;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @param advertiserId advertiserId or {@code null} for none
*/
public Ad setAdvertiserId(java.lang.Long advertiserId) {
this.advertiserId = advertiserId;
return this;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getAdvertiserIdDimensionValue() {
return advertiserIdDimensionValue;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @param advertiserIdDimensionValue advertiserIdDimensionValue or {@code null} for none
*/
public Ad setAdvertiserIdDimensionValue(DimensionValue advertiserIdDimensionValue) {
this.advertiserIdDimensionValue = advertiserIdDimensionValue;
return this;
}
/**
* Whether this ad is archived. When true, active must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getArchived() {
return archived;
}
/**
* Whether this ad is archived. When true, active must be false.
* @param archived archived or {@code null} for none
*/
public Ad setArchived(java.lang.Boolean archived) {
this.archived = archived;
return this;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getAudienceSegmentId() {
return audienceSegmentId;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @param audienceSegmentId audienceSegmentId or {@code null} for none
*/
public Ad setAudienceSegmentId(java.lang.Long audienceSegmentId) {
this.audienceSegmentId = audienceSegmentId;
return this;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getCampaignId() {
return campaignId;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @param campaignId campaignId or {@code null} for none
*/
public Ad setCampaignId(java.lang.Long campaignId) {
this.campaignId = campaignId;
return this;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getCampaignIdDimensionValue() {
return campaignIdDimensionValue;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @param campaignIdDimensionValue campaignIdDimensionValue or {@code null} for none
*/
public Ad setCampaignIdDimensionValue(DimensionValue campaignIdDimensionValue) {
this.campaignIdDimensionValue = campaignIdDimensionValue;
return this;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @return value or {@code null} for none
*/
public ClickThroughUrl getClickThroughUrl() {
return clickThroughUrl;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @param clickThroughUrl clickThroughUrl or {@code null} for none
*/
public Ad setClickThroughUrl(ClickThroughUrl clickThroughUrl) {
this.clickThroughUrl = clickThroughUrl;
return this;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @return value or {@code null} for none
*/
public ClickThroughUrlSuffixProperties getClickThroughUrlSuffixProperties() {
return clickThroughUrlSuffixProperties;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @param clickThroughUrlSuffixProperties clickThroughUrlSuffixProperties or {@code null} for none
*/
public Ad setClickThroughUrlSuffixProperties(ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties) {
this.clickThroughUrlSuffixProperties = clickThroughUrlSuffixProperties;
return this;
}
/**
* Comments for this ad.
* @return value or {@code null} for none
*/
public java.lang.String getComments() {
return comments;
}
/**
* Comments for this ad.
* @param comments comments or {@code null} for none
*/
public Ad setComments(java.lang.String comments) {
this.comments = comments;
return this;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @return value or {@code null} for none
*/
public java.lang.String getCompatibility() {
return compatibility;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @param compatibility compatibility or {@code null} for none
*/
public Ad setCompatibility(java.lang.String compatibility) {
this.compatibility = compatibility;
return this;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getCreateInfo() {
return createInfo;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @param createInfo createInfo or {@code null} for none
*/
public Ad setCreateInfo(LastModifiedInfo createInfo) {
this.createInfo = createInfo;
return this;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @return value or {@code null} for none
*/
public java.util.List<CreativeGroupAssignment> getCreativeGroupAssignments() {
return creativeGroupAssignments;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @param creativeGroupAssignments creativeGroupAssignments or {@code null} for none
*/
public Ad setCreativeGroupAssignments(java.util.List<CreativeGroupAssignment> creativeGroupAssignments) {
this.creativeGroupAssignments = creativeGroupAssignments;
return this;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @return value or {@code null} for none
*/
public CreativeRotation getCreativeRotation() {
return creativeRotation;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @param creativeRotation creativeRotation or {@code null} for none
*/
public Ad setCreativeRotation(CreativeRotation creativeRotation) {
this.creativeRotation = creativeRotation;
return this;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DayPartTargeting getDayPartTargeting() {
return dayPartTargeting;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param dayPartTargeting dayPartTargeting or {@code null} for none
*/
public Ad setDayPartTargeting(DayPartTargeting dayPartTargeting) {
this.dayPartTargeting = dayPartTargeting;
return this;
}
/**
* Default click-through event tag properties for this ad.
* @return value or {@code null} for none
*/
public DefaultClickThroughEventTagProperties getDefaultClickThroughEventTagProperties() {
return defaultClickThroughEventTagProperties;
}
/**
* Default click-through event tag properties for this ad.
* @param defaultClickThroughEventTagProperties defaultClickThroughEventTagProperties or {@code null} for none
*/
public Ad setDefaultClickThroughEventTagProperties(DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties) {
this.defaultClickThroughEventTagProperties = defaultClickThroughEventTagProperties;
return this;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DeliverySchedule getDeliverySchedule() {
return deliverySchedule;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @param deliverySchedule deliverySchedule or {@code null} for none
*/
public Ad setDeliverySchedule(DeliverySchedule deliverySchedule) {
this.deliverySchedule = deliverySchedule;
return this;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDynamicClickTracker() {
return dynamicClickTracker;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @param dynamicClickTracker dynamicClickTracker or {@code null} for none
*/
public Ad setDynamicClickTracker(java.lang.Boolean dynamicClickTracker) {
this.dynamicClickTracker = dynamicClickTracker;
return this;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getEndTime() {
return endTime;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @param endTime endTime or {@code null} for none
*/
public Ad setEndTime(com.google.api.client.util.DateTime endTime) {
this.endTime = endTime;
return this;
}
/**
* Event tag overrides for this ad.
* @return value or {@code null} for none
*/
public java.util.List<EventTagOverride> getEventTagOverrides() {
return eventTagOverrides;
}
/**
* Event tag overrides for this ad.
* @param eventTagOverrides eventTagOverrides or {@code null} for none
*/
public Ad setEventTagOverrides(java.util.List<EventTagOverride> eventTagOverrides) {
this.eventTagOverrides = eventTagOverrides;
return this;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public GeoTargeting getGeoTargeting() {
return geoTargeting;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param geoTargeting geoTargeting or {@code null} for none
*/
public Ad setGeoTargeting(GeoTargeting geoTargeting) {
this.geoTargeting = geoTargeting;
return this;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public java.lang.Long getId() {
return id;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @param id id or {@code null} for none
*/
public Ad setId(java.lang.Long id) {
this.id = id;
return this;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getIdDimensionValue() {
return idDimensionValue;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @param idDimensionValue idDimensionValue or {@code null} for none
*/
public Ad setIdDimensionValue(DimensionValue idDimensionValue) {
this.idDimensionValue = idDimensionValue;
return this;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public KeyValueTargetingExpression getKeyValueTargetingExpression() {
return keyValueTargetingExpression;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param keyValueTargetingExpression keyValueTargetingExpression or {@code null} for none
*/
public Ad setKeyValueTargetingExpression(KeyValueTargetingExpression keyValueTargetingExpression) {
this.keyValueTargetingExpression = keyValueTargetingExpression;
return this;
}
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* @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 "dfareporting#ad".
* @param kind kind or {@code null} for none
*/
public Ad setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public LanguageTargeting getLanguageTargeting() {
return languageTargeting;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param languageTargeting languageTargeting or {@code null} for none
*/
public Ad setLanguageTargeting(LanguageTargeting languageTargeting) {
this.languageTargeting = languageTargeting;
return this;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getLastModifiedInfo() {
return lastModifiedInfo;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @param lastModifiedInfo lastModifiedInfo or {@code null} for none
*/
public Ad setLastModifiedInfo(LastModifiedInfo lastModifiedInfo) {
this.lastModifiedInfo = lastModifiedInfo;
return this;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @param name name or {@code null} for none
*/
public Ad setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Placement assignments for this ad.
* @return value or {@code null} for none
*/
public java.util.List<PlacementAssignment> getPlacementAssignments() {
return placementAssignments;
}
/**
* Placement assignments for this ad.
* @param placementAssignments placementAssignments or {@code null} for none
*/
public Ad setPlacementAssignments(java.util.List<PlacementAssignment> placementAssignments) {
this.placementAssignments = placementAssignments;
return this;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public ListTargetingExpression getRemarketingListExpression() {
return remarketingListExpression;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param remarketingListExpression remarketingListExpression or {@code null} for none
*/
public Ad setRemarketingListExpression(ListTargetingExpression remarketingListExpression) {
this.remarketingListExpression = remarketingListExpression;
return this;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @return value or {@code null} for none
*/
public Size getSize() {
return size;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @param size size or {@code null} for none
*/
public Ad setSize(Size size) {
this.size = size;
return this;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslCompliant() {
return sslCompliant;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @param sslCompliant sslCompliant or {@code null} for none
*/
public Ad setSslCompliant(java.lang.Boolean sslCompliant) {
this.sslCompliant = sslCompliant;
return this;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslRequired() {
return sslRequired;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @param sslRequired sslRequired or {@code null} for none
*/
public Ad setSslRequired(java.lang.Boolean sslRequired) {
this.sslRequired = sslRequired;
return this;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getStartTime() {
return startTime;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @param startTime startTime or {@code null} for none
*/
public Ad setStartTime(com.google.api.client.util.DateTime startTime) {
this.startTime = startTime;
return this;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getSubaccountId() {
return subaccountId;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @param subaccountId subaccountId or {@code null} for none
*/
public Ad setSubaccountId(java.lang.Long subaccountId) {
this.subaccountId = subaccountId;
return this;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getTargetingTemplateId() {
return targetingTemplateId;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @param targetingTemplateId targetingTemplateId or {@code null} for none
*/
public Ad setTargetingTemplateId(java.lang.Long targetingTemplateId) {
this.targetingTemplateId = targetingTemplateId;
return this;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public TechnologyTargeting getTechnologyTargeting() {
return technologyTargeting;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param technologyTargeting technologyTargeting or {@code null} for none
*/
public Ad setTechnologyTargeting(TechnologyTargeting technologyTargeting) {
this.technologyTargeting = technologyTargeting;
return this;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @return value or {@code null} for none
*/
public java.lang.String getType() {
return type;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @param type type or {@code null} for none
*/
public Ad setType(java.lang.String type) {
this.type = type;
return this;
}
@Override
public Ad set(String fieldName, Object value) {
return (Ad) super.set(fieldName, value);
}
@Override
public Ad clone() {
return (Ad) super.clone();
}
}
|
googleapis/google-api-java-client-services | 36,499 | clients/google-api-services-dfareporting/v3.4/1.28.0/com/google/api/services/dfareporting/model/Ad.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.dfareporting.model;
/**
* Contains properties of a Campaign Manager ad.
*
* <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 DCM/DFA Reporting And Trafficking 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 Ad extends com.google.api.client.json.GenericJson {
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long accountId;
/**
* Whether this ad is active. When true, archived must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean active;
/**
* Advertiser ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long advertiserId;
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue advertiserIdDimensionValue;
/**
* Whether this ad is archived. When true, active must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean archived;
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long audienceSegmentId;
/**
* Campaign ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long campaignId;
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue campaignIdDimensionValue;
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrl clickThroughUrl;
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties;
/**
* Comments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String comments;
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String compatibility;
/**
* Information about the creation of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo createInfo;
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<CreativeGroupAssignment> creativeGroupAssignments;
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CreativeRotation creativeRotation;
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DayPartTargeting dayPartTargeting;
/**
* Default click-through event tag properties for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties;
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DeliverySchedule deliverySchedule;
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean dynamicClickTracker;
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime endTime;
/**
* Event tag overrides for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<EventTagOverride> eventTagOverrides;
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GeoTargeting geoTargeting;
/**
* ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long id;
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue idDimensionValue;
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private KeyValueTargetingExpression keyValueTargetingExpression;
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LanguageTargeting languageTargeting;
/**
* Information about the most recent modification of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo lastModifiedInfo;
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Placement assignments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<PlacementAssignment> placementAssignments;
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ListTargetingExpression remarketingListExpression;
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Size size;
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslCompliant;
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslRequired;
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime startTime;
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long subaccountId;
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long targetingTemplateId;
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TechnologyTargeting technologyTargeting;
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String type;
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getAccountId() {
return accountId;
}
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @param accountId accountId or {@code null} for none
*/
public Ad setAccountId(java.lang.Long accountId) {
this.accountId = accountId;
return this;
}
/**
* Whether this ad is active. When true, archived must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getActive() {
return active;
}
/**
* Whether this ad is active. When true, archived must be false.
* @param active active or {@code null} for none
*/
public Ad setActive(java.lang.Boolean active) {
this.active = active;
return this;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getAdvertiserId() {
return advertiserId;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @param advertiserId advertiserId or {@code null} for none
*/
public Ad setAdvertiserId(java.lang.Long advertiserId) {
this.advertiserId = advertiserId;
return this;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getAdvertiserIdDimensionValue() {
return advertiserIdDimensionValue;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @param advertiserIdDimensionValue advertiserIdDimensionValue or {@code null} for none
*/
public Ad setAdvertiserIdDimensionValue(DimensionValue advertiserIdDimensionValue) {
this.advertiserIdDimensionValue = advertiserIdDimensionValue;
return this;
}
/**
* Whether this ad is archived. When true, active must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getArchived() {
return archived;
}
/**
* Whether this ad is archived. When true, active must be false.
* @param archived archived or {@code null} for none
*/
public Ad setArchived(java.lang.Boolean archived) {
this.archived = archived;
return this;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getAudienceSegmentId() {
return audienceSegmentId;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @param audienceSegmentId audienceSegmentId or {@code null} for none
*/
public Ad setAudienceSegmentId(java.lang.Long audienceSegmentId) {
this.audienceSegmentId = audienceSegmentId;
return this;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getCampaignId() {
return campaignId;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @param campaignId campaignId or {@code null} for none
*/
public Ad setCampaignId(java.lang.Long campaignId) {
this.campaignId = campaignId;
return this;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getCampaignIdDimensionValue() {
return campaignIdDimensionValue;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @param campaignIdDimensionValue campaignIdDimensionValue or {@code null} for none
*/
public Ad setCampaignIdDimensionValue(DimensionValue campaignIdDimensionValue) {
this.campaignIdDimensionValue = campaignIdDimensionValue;
return this;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @return value or {@code null} for none
*/
public ClickThroughUrl getClickThroughUrl() {
return clickThroughUrl;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @param clickThroughUrl clickThroughUrl or {@code null} for none
*/
public Ad setClickThroughUrl(ClickThroughUrl clickThroughUrl) {
this.clickThroughUrl = clickThroughUrl;
return this;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @return value or {@code null} for none
*/
public ClickThroughUrlSuffixProperties getClickThroughUrlSuffixProperties() {
return clickThroughUrlSuffixProperties;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @param clickThroughUrlSuffixProperties clickThroughUrlSuffixProperties or {@code null} for none
*/
public Ad setClickThroughUrlSuffixProperties(ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties) {
this.clickThroughUrlSuffixProperties = clickThroughUrlSuffixProperties;
return this;
}
/**
* Comments for this ad.
* @return value or {@code null} for none
*/
public java.lang.String getComments() {
return comments;
}
/**
* Comments for this ad.
* @param comments comments or {@code null} for none
*/
public Ad setComments(java.lang.String comments) {
this.comments = comments;
return this;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @return value or {@code null} for none
*/
public java.lang.String getCompatibility() {
return compatibility;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @param compatibility compatibility or {@code null} for none
*/
public Ad setCompatibility(java.lang.String compatibility) {
this.compatibility = compatibility;
return this;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getCreateInfo() {
return createInfo;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @param createInfo createInfo or {@code null} for none
*/
public Ad setCreateInfo(LastModifiedInfo createInfo) {
this.createInfo = createInfo;
return this;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @return value or {@code null} for none
*/
public java.util.List<CreativeGroupAssignment> getCreativeGroupAssignments() {
return creativeGroupAssignments;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @param creativeGroupAssignments creativeGroupAssignments or {@code null} for none
*/
public Ad setCreativeGroupAssignments(java.util.List<CreativeGroupAssignment> creativeGroupAssignments) {
this.creativeGroupAssignments = creativeGroupAssignments;
return this;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @return value or {@code null} for none
*/
public CreativeRotation getCreativeRotation() {
return creativeRotation;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @param creativeRotation creativeRotation or {@code null} for none
*/
public Ad setCreativeRotation(CreativeRotation creativeRotation) {
this.creativeRotation = creativeRotation;
return this;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DayPartTargeting getDayPartTargeting() {
return dayPartTargeting;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param dayPartTargeting dayPartTargeting or {@code null} for none
*/
public Ad setDayPartTargeting(DayPartTargeting dayPartTargeting) {
this.dayPartTargeting = dayPartTargeting;
return this;
}
/**
* Default click-through event tag properties for this ad.
* @return value or {@code null} for none
*/
public DefaultClickThroughEventTagProperties getDefaultClickThroughEventTagProperties() {
return defaultClickThroughEventTagProperties;
}
/**
* Default click-through event tag properties for this ad.
* @param defaultClickThroughEventTagProperties defaultClickThroughEventTagProperties or {@code null} for none
*/
public Ad setDefaultClickThroughEventTagProperties(DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties) {
this.defaultClickThroughEventTagProperties = defaultClickThroughEventTagProperties;
return this;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DeliverySchedule getDeliverySchedule() {
return deliverySchedule;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @param deliverySchedule deliverySchedule or {@code null} for none
*/
public Ad setDeliverySchedule(DeliverySchedule deliverySchedule) {
this.deliverySchedule = deliverySchedule;
return this;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDynamicClickTracker() {
return dynamicClickTracker;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @param dynamicClickTracker dynamicClickTracker or {@code null} for none
*/
public Ad setDynamicClickTracker(java.lang.Boolean dynamicClickTracker) {
this.dynamicClickTracker = dynamicClickTracker;
return this;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getEndTime() {
return endTime;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @param endTime endTime or {@code null} for none
*/
public Ad setEndTime(com.google.api.client.util.DateTime endTime) {
this.endTime = endTime;
return this;
}
/**
* Event tag overrides for this ad.
* @return value or {@code null} for none
*/
public java.util.List<EventTagOverride> getEventTagOverrides() {
return eventTagOverrides;
}
/**
* Event tag overrides for this ad.
* @param eventTagOverrides eventTagOverrides or {@code null} for none
*/
public Ad setEventTagOverrides(java.util.List<EventTagOverride> eventTagOverrides) {
this.eventTagOverrides = eventTagOverrides;
return this;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public GeoTargeting getGeoTargeting() {
return geoTargeting;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param geoTargeting geoTargeting or {@code null} for none
*/
public Ad setGeoTargeting(GeoTargeting geoTargeting) {
this.geoTargeting = geoTargeting;
return this;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public java.lang.Long getId() {
return id;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @param id id or {@code null} for none
*/
public Ad setId(java.lang.Long id) {
this.id = id;
return this;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getIdDimensionValue() {
return idDimensionValue;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @param idDimensionValue idDimensionValue or {@code null} for none
*/
public Ad setIdDimensionValue(DimensionValue idDimensionValue) {
this.idDimensionValue = idDimensionValue;
return this;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public KeyValueTargetingExpression getKeyValueTargetingExpression() {
return keyValueTargetingExpression;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param keyValueTargetingExpression keyValueTargetingExpression or {@code null} for none
*/
public Ad setKeyValueTargetingExpression(KeyValueTargetingExpression keyValueTargetingExpression) {
this.keyValueTargetingExpression = keyValueTargetingExpression;
return this;
}
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* @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 "dfareporting#ad".
* @param kind kind or {@code null} for none
*/
public Ad setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public LanguageTargeting getLanguageTargeting() {
return languageTargeting;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param languageTargeting languageTargeting or {@code null} for none
*/
public Ad setLanguageTargeting(LanguageTargeting languageTargeting) {
this.languageTargeting = languageTargeting;
return this;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getLastModifiedInfo() {
return lastModifiedInfo;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @param lastModifiedInfo lastModifiedInfo or {@code null} for none
*/
public Ad setLastModifiedInfo(LastModifiedInfo lastModifiedInfo) {
this.lastModifiedInfo = lastModifiedInfo;
return this;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @param name name or {@code null} for none
*/
public Ad setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Placement assignments for this ad.
* @return value or {@code null} for none
*/
public java.util.List<PlacementAssignment> getPlacementAssignments() {
return placementAssignments;
}
/**
* Placement assignments for this ad.
* @param placementAssignments placementAssignments or {@code null} for none
*/
public Ad setPlacementAssignments(java.util.List<PlacementAssignment> placementAssignments) {
this.placementAssignments = placementAssignments;
return this;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public ListTargetingExpression getRemarketingListExpression() {
return remarketingListExpression;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param remarketingListExpression remarketingListExpression or {@code null} for none
*/
public Ad setRemarketingListExpression(ListTargetingExpression remarketingListExpression) {
this.remarketingListExpression = remarketingListExpression;
return this;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @return value or {@code null} for none
*/
public Size getSize() {
return size;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @param size size or {@code null} for none
*/
public Ad setSize(Size size) {
this.size = size;
return this;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslCompliant() {
return sslCompliant;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @param sslCompliant sslCompliant or {@code null} for none
*/
public Ad setSslCompliant(java.lang.Boolean sslCompliant) {
this.sslCompliant = sslCompliant;
return this;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslRequired() {
return sslRequired;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @param sslRequired sslRequired or {@code null} for none
*/
public Ad setSslRequired(java.lang.Boolean sslRequired) {
this.sslRequired = sslRequired;
return this;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getStartTime() {
return startTime;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @param startTime startTime or {@code null} for none
*/
public Ad setStartTime(com.google.api.client.util.DateTime startTime) {
this.startTime = startTime;
return this;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getSubaccountId() {
return subaccountId;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @param subaccountId subaccountId or {@code null} for none
*/
public Ad setSubaccountId(java.lang.Long subaccountId) {
this.subaccountId = subaccountId;
return this;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getTargetingTemplateId() {
return targetingTemplateId;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @param targetingTemplateId targetingTemplateId or {@code null} for none
*/
public Ad setTargetingTemplateId(java.lang.Long targetingTemplateId) {
this.targetingTemplateId = targetingTemplateId;
return this;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public TechnologyTargeting getTechnologyTargeting() {
return technologyTargeting;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param technologyTargeting technologyTargeting or {@code null} for none
*/
public Ad setTechnologyTargeting(TechnologyTargeting technologyTargeting) {
this.technologyTargeting = technologyTargeting;
return this;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @return value or {@code null} for none
*/
public java.lang.String getType() {
return type;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @param type type or {@code null} for none
*/
public Ad setType(java.lang.String type) {
this.type = type;
return this;
}
@Override
public Ad set(String fieldName, Object value) {
return (Ad) super.set(fieldName, value);
}
@Override
public Ad clone() {
return (Ad) super.clone();
}
}
|
googleapis/google-api-java-client-services | 36,499 | clients/google-api-services-dfareporting/v3.4/1.29.2/com/google/api/services/dfareporting/model/Ad.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.dfareporting.model;
/**
* Contains properties of a Campaign Manager ad.
*
* <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 DCM/DFA Reporting And Trafficking 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 Ad extends com.google.api.client.json.GenericJson {
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long accountId;
/**
* Whether this ad is active. When true, archived must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean active;
/**
* Advertiser ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long advertiserId;
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue advertiserIdDimensionValue;
/**
* Whether this ad is archived. When true, active must be false.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean archived;
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long audienceSegmentId;
/**
* Campaign ID of this ad. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long campaignId;
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue campaignIdDimensionValue;
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrl clickThroughUrl;
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties;
/**
* Comments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String comments;
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String compatibility;
/**
* Information about the creation of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo createInfo;
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<CreativeGroupAssignment> creativeGroupAssignments;
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CreativeRotation creativeRotation;
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DayPartTargeting dayPartTargeting;
/**
* Default click-through event tag properties for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties;
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DeliverySchedule deliverySchedule;
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean dynamicClickTracker;
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime endTime;
/**
* Event tag overrides for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<EventTagOverride> eventTagOverrides;
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GeoTargeting geoTargeting;
/**
* ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long id;
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DimensionValue idDimensionValue;
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private KeyValueTargetingExpression keyValueTargetingExpression;
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LanguageTargeting languageTargeting;
/**
* Information about the most recent modification of this ad. This is a read-only field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private LastModifiedInfo lastModifiedInfo;
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Placement assignments for this ad.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<PlacementAssignment> placementAssignments;
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ListTargetingExpression remarketingListExpression;
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Size size;
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslCompliant;
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean sslRequired;
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime startTime;
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long subaccountId;
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long targetingTemplateId;
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TechnologyTargeting technologyTargeting;
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String type;
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getAccountId() {
return accountId;
}
/**
* Account ID of this ad. This is a read-only field that can be left blank.
* @param accountId accountId or {@code null} for none
*/
public Ad setAccountId(java.lang.Long accountId) {
this.accountId = accountId;
return this;
}
/**
* Whether this ad is active. When true, archived must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getActive() {
return active;
}
/**
* Whether this ad is active. When true, archived must be false.
* @param active active or {@code null} for none
*/
public Ad setActive(java.lang.Boolean active) {
this.active = active;
return this;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getAdvertiserId() {
return advertiserId;
}
/**
* Advertiser ID of this ad. This is a required field on insertion.
* @param advertiserId advertiserId or {@code null} for none
*/
public Ad setAdvertiserId(java.lang.Long advertiserId) {
this.advertiserId = advertiserId;
return this;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getAdvertiserIdDimensionValue() {
return advertiserIdDimensionValue;
}
/**
* Dimension value for the ID of the advertiser. This is a read-only, auto-generated field.
* @param advertiserIdDimensionValue advertiserIdDimensionValue or {@code null} for none
*/
public Ad setAdvertiserIdDimensionValue(DimensionValue advertiserIdDimensionValue) {
this.advertiserIdDimensionValue = advertiserIdDimensionValue;
return this;
}
/**
* Whether this ad is archived. When true, active must be false.
* @return value or {@code null} for none
*/
public java.lang.Boolean getArchived() {
return archived;
}
/**
* Whether this ad is archived. When true, active must be false.
* @param archived archived or {@code null} for none
*/
public Ad setArchived(java.lang.Boolean archived) {
this.archived = archived;
return this;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getAudienceSegmentId() {
return audienceSegmentId;
}
/**
* Audience segment ID that is being targeted for this ad. Applicable when type is
* AD_SERVING_STANDARD_AD.
* @param audienceSegmentId audienceSegmentId or {@code null} for none
*/
public Ad setAudienceSegmentId(java.lang.Long audienceSegmentId) {
this.audienceSegmentId = audienceSegmentId;
return this;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @return value or {@code null} for none
*/
public java.lang.Long getCampaignId() {
return campaignId;
}
/**
* Campaign ID of this ad. This is a required field on insertion.
* @param campaignId campaignId or {@code null} for none
*/
public Ad setCampaignId(java.lang.Long campaignId) {
this.campaignId = campaignId;
return this;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getCampaignIdDimensionValue() {
return campaignIdDimensionValue;
}
/**
* Dimension value for the ID of the campaign. This is a read-only, auto-generated field.
* @param campaignIdDimensionValue campaignIdDimensionValue or {@code null} for none
*/
public Ad setCampaignIdDimensionValue(DimensionValue campaignIdDimensionValue) {
this.campaignIdDimensionValue = campaignIdDimensionValue;
return this;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @return value or {@code null} for none
*/
public ClickThroughUrl getClickThroughUrl() {
return clickThroughUrl;
}
/**
* Click-through URL for this ad. This is a required field on insertion. Applicable when type is
* AD_SERVING_CLICK_TRACKER.
* @param clickThroughUrl clickThroughUrl or {@code null} for none
*/
public Ad setClickThroughUrl(ClickThroughUrl clickThroughUrl) {
this.clickThroughUrl = clickThroughUrl;
return this;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @return value or {@code null} for none
*/
public ClickThroughUrlSuffixProperties getClickThroughUrlSuffixProperties() {
return clickThroughUrlSuffixProperties;
}
/**
* Click-through URL suffix properties for this ad. Applies to the URL in the ad or (if overriding
* ad properties) the URL in the creative.
* @param clickThroughUrlSuffixProperties clickThroughUrlSuffixProperties or {@code null} for none
*/
public Ad setClickThroughUrlSuffixProperties(ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties) {
this.clickThroughUrlSuffixProperties = clickThroughUrlSuffixProperties;
return this;
}
/**
* Comments for this ad.
* @return value or {@code null} for none
*/
public java.lang.String getComments() {
return comments;
}
/**
* Comments for this ad.
* @param comments comments or {@code null} for none
*/
public Ad setComments(java.lang.String comments) {
this.comments = comments;
return this;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @return value or {@code null} for none
*/
public java.lang.String getCompatibility() {
return compatibility;
}
/**
* Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. DISPLAY and
* DISPLAY_INTERSTITIAL refer to either rendering on desktop or on mobile devices or in mobile
* apps for regular or interstitial ads, respectively. APP and APP_INTERSTITIAL are only used for
* existing default ads. New mobile placements must be assigned DISPLAY or DISPLAY_INTERSTITIAL
* and default ads created for those placements will be limited to those compatibility types.
* IN_STREAM_VIDEO refers to rendering in-stream video ads developed with the VAST standard.
* @param compatibility compatibility or {@code null} for none
*/
public Ad setCompatibility(java.lang.String compatibility) {
this.compatibility = compatibility;
return this;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getCreateInfo() {
return createInfo;
}
/**
* Information about the creation of this ad. This is a read-only field.
* @param createInfo createInfo or {@code null} for none
*/
public Ad setCreateInfo(LastModifiedInfo createInfo) {
this.createInfo = createInfo;
return this;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @return value or {@code null} for none
*/
public java.util.List<CreativeGroupAssignment> getCreativeGroupAssignments() {
return creativeGroupAssignments;
}
/**
* Creative group assignments for this ad. Applicable when type is AD_SERVING_CLICK_TRACKER. Only
* one assignment per creative group number is allowed for a maximum of two assignments.
* @param creativeGroupAssignments creativeGroupAssignments or {@code null} for none
*/
public Ad setCreativeGroupAssignments(java.util.List<CreativeGroupAssignment> creativeGroupAssignments) {
this.creativeGroupAssignments = creativeGroupAssignments;
return this;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @return value or {@code null} for none
*/
public CreativeRotation getCreativeRotation() {
return creativeRotation;
}
/**
* Creative rotation for this ad. Applicable when type is AD_SERVING_DEFAULT_AD,
* AD_SERVING_STANDARD_AD, or AD_SERVING_TRACKING. When type is AD_SERVING_DEFAULT_AD, this field
* should have exactly one creativeAssignment.
* @param creativeRotation creativeRotation or {@code null} for none
*/
public Ad setCreativeRotation(CreativeRotation creativeRotation) {
this.creativeRotation = creativeRotation;
return this;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DayPartTargeting getDayPartTargeting() {
return dayPartTargeting;
}
/**
* Time and day targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param dayPartTargeting dayPartTargeting or {@code null} for none
*/
public Ad setDayPartTargeting(DayPartTargeting dayPartTargeting) {
this.dayPartTargeting = dayPartTargeting;
return this;
}
/**
* Default click-through event tag properties for this ad.
* @return value or {@code null} for none
*/
public DefaultClickThroughEventTagProperties getDefaultClickThroughEventTagProperties() {
return defaultClickThroughEventTagProperties;
}
/**
* Default click-through event tag properties for this ad.
* @param defaultClickThroughEventTagProperties defaultClickThroughEventTagProperties or {@code null} for none
*/
public Ad setDefaultClickThroughEventTagProperties(DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties) {
this.defaultClickThroughEventTagProperties = defaultClickThroughEventTagProperties;
return this;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public DeliverySchedule getDeliverySchedule() {
return deliverySchedule;
}
/**
* Delivery schedule information for this ad. Applicable when type is AD_SERVING_STANDARD_AD or
* AD_SERVING_TRACKING. This field along with subfields priority and impressionRatio are required
* on insertion when type is AD_SERVING_STANDARD_AD.
* @param deliverySchedule deliverySchedule or {@code null} for none
*/
public Ad setDeliverySchedule(DeliverySchedule deliverySchedule) {
this.deliverySchedule = deliverySchedule;
return this;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDynamicClickTracker() {
return dynamicClickTracker;
}
/**
* Whether this ad is a dynamic click tracker. Applicable when type is AD_SERVING_CLICK_TRACKER.
* This is a required field on insert, and is read-only after insert.
* @param dynamicClickTracker dynamicClickTracker or {@code null} for none
*/
public Ad setDynamicClickTracker(java.lang.Boolean dynamicClickTracker) {
this.dynamicClickTracker = dynamicClickTracker;
return this;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getEndTime() {
return endTime;
}
/**
* Date and time that this ad should stop serving. Must be later than the start time. This is a
* required field on insertion.
* @param endTime endTime or {@code null} for none
*/
public Ad setEndTime(com.google.api.client.util.DateTime endTime) {
this.endTime = endTime;
return this;
}
/**
* Event tag overrides for this ad.
* @return value or {@code null} for none
*/
public java.util.List<EventTagOverride> getEventTagOverrides() {
return eventTagOverrides;
}
/**
* Event tag overrides for this ad.
* @param eventTagOverrides eventTagOverrides or {@code null} for none
*/
public Ad setEventTagOverrides(java.util.List<EventTagOverride> eventTagOverrides) {
this.eventTagOverrides = eventTagOverrides;
return this;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public GeoTargeting getGeoTargeting() {
return geoTargeting;
}
/**
* Geographical targeting information for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param geoTargeting geoTargeting or {@code null} for none
*/
public Ad setGeoTargeting(GeoTargeting geoTargeting) {
this.geoTargeting = geoTargeting;
return this;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public java.lang.Long getId() {
return id;
}
/**
* ID of this ad. This is a read-only, auto-generated field.
* @param id id or {@code null} for none
*/
public Ad setId(java.lang.Long id) {
this.id = id;
return this;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @return value or {@code null} for none
*/
public DimensionValue getIdDimensionValue() {
return idDimensionValue;
}
/**
* Dimension value for the ID of this ad. This is a read-only, auto-generated field.
* @param idDimensionValue idDimensionValue or {@code null} for none
*/
public Ad setIdDimensionValue(DimensionValue idDimensionValue) {
this.idDimensionValue = idDimensionValue;
return this;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public KeyValueTargetingExpression getKeyValueTargetingExpression() {
return keyValueTargetingExpression;
}
/**
* Key-value targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param keyValueTargetingExpression keyValueTargetingExpression or {@code null} for none
*/
public Ad setKeyValueTargetingExpression(KeyValueTargetingExpression keyValueTargetingExpression) {
this.keyValueTargetingExpression = keyValueTargetingExpression;
return this;
}
/**
* Identifies what kind of resource this is. Value: the fixed string "dfareporting#ad".
* @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 "dfareporting#ad".
* @param kind kind or {@code null} for none
*/
public Ad setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public LanguageTargeting getLanguageTargeting() {
return languageTargeting;
}
/**
* Language targeting information for this ad. This field must be left blank if the ad is using a
* targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param languageTargeting languageTargeting or {@code null} for none
*/
public Ad setLanguageTargeting(LanguageTargeting languageTargeting) {
this.languageTargeting = languageTargeting;
return this;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @return value or {@code null} for none
*/
public LastModifiedInfo getLastModifiedInfo() {
return lastModifiedInfo;
}
/**
* Information about the most recent modification of this ad. This is a read-only field.
* @param lastModifiedInfo lastModifiedInfo or {@code null} for none
*/
public Ad setLastModifiedInfo(LastModifiedInfo lastModifiedInfo) {
this.lastModifiedInfo = lastModifiedInfo;
return this;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of this ad. This is a required field and must be less than 256 characters long.
* @param name name or {@code null} for none
*/
public Ad setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Placement assignments for this ad.
* @return value or {@code null} for none
*/
public java.util.List<PlacementAssignment> getPlacementAssignments() {
return placementAssignments;
}
/**
* Placement assignments for this ad.
* @param placementAssignments placementAssignments or {@code null} for none
*/
public Ad setPlacementAssignments(java.util.List<PlacementAssignment> placementAssignments) {
this.placementAssignments = placementAssignments;
return this;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public ListTargetingExpression getRemarketingListExpression() {
return remarketingListExpression;
}
/**
* Remarketing list targeting expression for this ad. This field must be left blank if the ad is
* using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param remarketingListExpression remarketingListExpression or {@code null} for none
*/
public Ad setRemarketingListExpression(ListTargetingExpression remarketingListExpression) {
this.remarketingListExpression = remarketingListExpression;
return this;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @return value or {@code null} for none
*/
public Size getSize() {
return size;
}
/**
* Size of this ad. Applicable when type is AD_SERVING_DEFAULT_AD.
* @param size size or {@code null} for none
*/
public Ad setSize(Size size) {
this.size = size;
return this;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslCompliant() {
return sslCompliant;
}
/**
* Whether this ad is ssl compliant. This is a read-only field that is auto-generated when the ad
* is inserted or updated.
* @param sslCompliant sslCompliant or {@code null} for none
*/
public Ad setSslCompliant(java.lang.Boolean sslCompliant) {
this.sslCompliant = sslCompliant;
return this;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @return value or {@code null} for none
*/
public java.lang.Boolean getSslRequired() {
return sslRequired;
}
/**
* Whether this ad requires ssl. This is a read-only field that is auto-generated when the ad is
* inserted or updated.
* @param sslRequired sslRequired or {@code null} for none
*/
public Ad setSslRequired(java.lang.Boolean sslRequired) {
this.sslRequired = sslRequired;
return this;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getStartTime() {
return startTime;
}
/**
* Date and time that this ad should start serving. If creating an ad, this field must be a time
* in the future. This is a required field on insertion.
* @param startTime startTime or {@code null} for none
*/
public Ad setStartTime(com.google.api.client.util.DateTime startTime) {
this.startTime = startTime;
return this;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @return value or {@code null} for none
*/
public java.lang.Long getSubaccountId() {
return subaccountId;
}
/**
* Subaccount ID of this ad. This is a read-only field that can be left blank.
* @param subaccountId subaccountId or {@code null} for none
*/
public Ad setSubaccountId(java.lang.Long subaccountId) {
this.subaccountId = subaccountId;
return this;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public java.lang.Long getTargetingTemplateId() {
return targetingTemplateId;
}
/**
* Targeting template ID, used to apply preconfigured targeting information to this ad. This
* cannot be set while any of dayPartTargeting, geoTargeting, keyValueTargetingExpression,
* languageTargeting, remarketingListExpression, or technologyTargeting are set. Applicable when
* type is AD_SERVING_STANDARD_AD.
* @param targetingTemplateId targetingTemplateId or {@code null} for none
*/
public Ad setTargetingTemplateId(java.lang.Long targetingTemplateId) {
this.targetingTemplateId = targetingTemplateId;
return this;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @return value or {@code null} for none
*/
public TechnologyTargeting getTechnologyTargeting() {
return technologyTargeting;
}
/**
* Technology platform targeting information for this ad. This field must be left blank if the ad
* is using a targeting template. Applicable when type is AD_SERVING_STANDARD_AD.
* @param technologyTargeting technologyTargeting or {@code null} for none
*/
public Ad setTechnologyTargeting(TechnologyTargeting technologyTargeting) {
this.technologyTargeting = technologyTargeting;
return this;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @return value or {@code null} for none
*/
public java.lang.String getType() {
return type;
}
/**
* Type of ad. This is a required field on insertion. Note that default ads
* (AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative resource).
* @param type type or {@code null} for none
*/
public Ad setType(java.lang.String type) {
this.type = type;
return this;
}
@Override
public Ad set(String fieldName, Object value) {
return (Ad) super.set(fieldName, value);
}
@Override
public Ad clone() {
return (Ad) super.clone();
}
}
|
googleapis/google-cloud-java | 36,391 | java-datacatalog/proto-google-cloud-datacatalog-v1/src/main/java/com/google/cloud/datacatalog/v1/ListTaxonomiesResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/datacatalog/v1/policytagmanager.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.datacatalog.v1;
/**
*
*
* <pre>
* Response message for
* [ListTaxonomies][google.cloud.datacatalog.v1.PolicyTagManager.ListTaxonomies].
* </pre>
*
* Protobuf type {@code google.cloud.datacatalog.v1.ListTaxonomiesResponse}
*/
public final class ListTaxonomiesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.datacatalog.v1.ListTaxonomiesResponse)
ListTaxonomiesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListTaxonomiesResponse.newBuilder() to construct.
private ListTaxonomiesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListTaxonomiesResponse() {
taxonomies_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListTaxonomiesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datacatalog.v1.PolicyTagManagerProto
.internal_static_google_cloud_datacatalog_v1_ListTaxonomiesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datacatalog.v1.PolicyTagManagerProto
.internal_static_google_cloud_datacatalog_v1_ListTaxonomiesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datacatalog.v1.ListTaxonomiesResponse.class,
com.google.cloud.datacatalog.v1.ListTaxonomiesResponse.Builder.class);
}
public static final int TAXONOMIES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.datacatalog.v1.Taxonomy> taxonomies_;
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.datacatalog.v1.Taxonomy> getTaxonomiesList() {
return taxonomies_;
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.datacatalog.v1.TaxonomyOrBuilder>
getTaxonomiesOrBuilderList() {
return taxonomies_;
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
@java.lang.Override
public int getTaxonomiesCount() {
return taxonomies_.size();
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
@java.lang.Override
public com.google.cloud.datacatalog.v1.Taxonomy getTaxonomies(int index) {
return taxonomies_.get(index);
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
@java.lang.Override
public com.google.cloud.datacatalog.v1.TaxonomyOrBuilder getTaxonomiesOrBuilder(int index) {
return taxonomies_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Pagination token of the next results page. 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>
* Pagination token of the next results page. 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 < taxonomies_.size(); i++) {
output.writeMessage(1, taxonomies_.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 < taxonomies_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, taxonomies_.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.datacatalog.v1.ListTaxonomiesResponse)) {
return super.equals(obj);
}
com.google.cloud.datacatalog.v1.ListTaxonomiesResponse other =
(com.google.cloud.datacatalog.v1.ListTaxonomiesResponse) obj;
if (!getTaxonomiesList().equals(other.getTaxonomiesList())) 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 (getTaxonomiesCount() > 0) {
hash = (37 * hash) + TAXONOMIES_FIELD_NUMBER;
hash = (53 * hash) + getTaxonomiesList().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.datacatalog.v1.ListTaxonomiesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1.ListTaxonomiesResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datacatalog.v1.ListTaxonomiesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1.ListTaxonomiesResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datacatalog.v1.ListTaxonomiesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1.ListTaxonomiesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datacatalog.v1.ListTaxonomiesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.v1.ListTaxonomiesResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.datacatalog.v1.ListTaxonomiesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.v1.ListTaxonomiesResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.datacatalog.v1.ListTaxonomiesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.v1.ListTaxonomiesResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.datacatalog.v1.ListTaxonomiesResponse 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
* [ListTaxonomies][google.cloud.datacatalog.v1.PolicyTagManager.ListTaxonomies].
* </pre>
*
* Protobuf type {@code google.cloud.datacatalog.v1.ListTaxonomiesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.datacatalog.v1.ListTaxonomiesResponse)
com.google.cloud.datacatalog.v1.ListTaxonomiesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datacatalog.v1.PolicyTagManagerProto
.internal_static_google_cloud_datacatalog_v1_ListTaxonomiesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datacatalog.v1.PolicyTagManagerProto
.internal_static_google_cloud_datacatalog_v1_ListTaxonomiesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datacatalog.v1.ListTaxonomiesResponse.class,
com.google.cloud.datacatalog.v1.ListTaxonomiesResponse.Builder.class);
}
// Construct using com.google.cloud.datacatalog.v1.ListTaxonomiesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (taxonomiesBuilder_ == null) {
taxonomies_ = java.util.Collections.emptyList();
} else {
taxonomies_ = null;
taxonomiesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.datacatalog.v1.PolicyTagManagerProto
.internal_static_google_cloud_datacatalog_v1_ListTaxonomiesResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1.ListTaxonomiesResponse getDefaultInstanceForType() {
return com.google.cloud.datacatalog.v1.ListTaxonomiesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.datacatalog.v1.ListTaxonomiesResponse build() {
com.google.cloud.datacatalog.v1.ListTaxonomiesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1.ListTaxonomiesResponse buildPartial() {
com.google.cloud.datacatalog.v1.ListTaxonomiesResponse result =
new com.google.cloud.datacatalog.v1.ListTaxonomiesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.datacatalog.v1.ListTaxonomiesResponse result) {
if (taxonomiesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
taxonomies_ = java.util.Collections.unmodifiableList(taxonomies_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.taxonomies_ = taxonomies_;
} else {
result.taxonomies_ = taxonomiesBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.datacatalog.v1.ListTaxonomiesResponse 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.datacatalog.v1.ListTaxonomiesResponse) {
return mergeFrom((com.google.cloud.datacatalog.v1.ListTaxonomiesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.datacatalog.v1.ListTaxonomiesResponse other) {
if (other == com.google.cloud.datacatalog.v1.ListTaxonomiesResponse.getDefaultInstance())
return this;
if (taxonomiesBuilder_ == null) {
if (!other.taxonomies_.isEmpty()) {
if (taxonomies_.isEmpty()) {
taxonomies_ = other.taxonomies_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureTaxonomiesIsMutable();
taxonomies_.addAll(other.taxonomies_);
}
onChanged();
}
} else {
if (!other.taxonomies_.isEmpty()) {
if (taxonomiesBuilder_.isEmpty()) {
taxonomiesBuilder_.dispose();
taxonomiesBuilder_ = null;
taxonomies_ = other.taxonomies_;
bitField0_ = (bitField0_ & ~0x00000001);
taxonomiesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getTaxonomiesFieldBuilder()
: null;
} else {
taxonomiesBuilder_.addAllMessages(other.taxonomies_);
}
}
}
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.datacatalog.v1.Taxonomy m =
input.readMessage(
com.google.cloud.datacatalog.v1.Taxonomy.parser(), extensionRegistry);
if (taxonomiesBuilder_ == null) {
ensureTaxonomiesIsMutable();
taxonomies_.add(m);
} else {
taxonomiesBuilder_.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.datacatalog.v1.Taxonomy> taxonomies_ =
java.util.Collections.emptyList();
private void ensureTaxonomiesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
taxonomies_ =
new java.util.ArrayList<com.google.cloud.datacatalog.v1.Taxonomy>(taxonomies_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datacatalog.v1.Taxonomy,
com.google.cloud.datacatalog.v1.Taxonomy.Builder,
com.google.cloud.datacatalog.v1.TaxonomyOrBuilder>
taxonomiesBuilder_;
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public java.util.List<com.google.cloud.datacatalog.v1.Taxonomy> getTaxonomiesList() {
if (taxonomiesBuilder_ == null) {
return java.util.Collections.unmodifiableList(taxonomies_);
} else {
return taxonomiesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public int getTaxonomiesCount() {
if (taxonomiesBuilder_ == null) {
return taxonomies_.size();
} else {
return taxonomiesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public com.google.cloud.datacatalog.v1.Taxonomy getTaxonomies(int index) {
if (taxonomiesBuilder_ == null) {
return taxonomies_.get(index);
} else {
return taxonomiesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public Builder setTaxonomies(int index, com.google.cloud.datacatalog.v1.Taxonomy value) {
if (taxonomiesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTaxonomiesIsMutable();
taxonomies_.set(index, value);
onChanged();
} else {
taxonomiesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public Builder setTaxonomies(
int index, com.google.cloud.datacatalog.v1.Taxonomy.Builder builderForValue) {
if (taxonomiesBuilder_ == null) {
ensureTaxonomiesIsMutable();
taxonomies_.set(index, builderForValue.build());
onChanged();
} else {
taxonomiesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public Builder addTaxonomies(com.google.cloud.datacatalog.v1.Taxonomy value) {
if (taxonomiesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTaxonomiesIsMutable();
taxonomies_.add(value);
onChanged();
} else {
taxonomiesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public Builder addTaxonomies(int index, com.google.cloud.datacatalog.v1.Taxonomy value) {
if (taxonomiesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTaxonomiesIsMutable();
taxonomies_.add(index, value);
onChanged();
} else {
taxonomiesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public Builder addTaxonomies(com.google.cloud.datacatalog.v1.Taxonomy.Builder builderForValue) {
if (taxonomiesBuilder_ == null) {
ensureTaxonomiesIsMutable();
taxonomies_.add(builderForValue.build());
onChanged();
} else {
taxonomiesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public Builder addTaxonomies(
int index, com.google.cloud.datacatalog.v1.Taxonomy.Builder builderForValue) {
if (taxonomiesBuilder_ == null) {
ensureTaxonomiesIsMutable();
taxonomies_.add(index, builderForValue.build());
onChanged();
} else {
taxonomiesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public Builder addAllTaxonomies(
java.lang.Iterable<? extends com.google.cloud.datacatalog.v1.Taxonomy> values) {
if (taxonomiesBuilder_ == null) {
ensureTaxonomiesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, taxonomies_);
onChanged();
} else {
taxonomiesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public Builder clearTaxonomies() {
if (taxonomiesBuilder_ == null) {
taxonomies_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
taxonomiesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public Builder removeTaxonomies(int index) {
if (taxonomiesBuilder_ == null) {
ensureTaxonomiesIsMutable();
taxonomies_.remove(index);
onChanged();
} else {
taxonomiesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public com.google.cloud.datacatalog.v1.Taxonomy.Builder getTaxonomiesBuilder(int index) {
return getTaxonomiesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public com.google.cloud.datacatalog.v1.TaxonomyOrBuilder getTaxonomiesOrBuilder(int index) {
if (taxonomiesBuilder_ == null) {
return taxonomies_.get(index);
} else {
return taxonomiesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public java.util.List<? extends com.google.cloud.datacatalog.v1.TaxonomyOrBuilder>
getTaxonomiesOrBuilderList() {
if (taxonomiesBuilder_ != null) {
return taxonomiesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(taxonomies_);
}
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public com.google.cloud.datacatalog.v1.Taxonomy.Builder addTaxonomiesBuilder() {
return getTaxonomiesFieldBuilder()
.addBuilder(com.google.cloud.datacatalog.v1.Taxonomy.getDefaultInstance());
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public com.google.cloud.datacatalog.v1.Taxonomy.Builder addTaxonomiesBuilder(int index) {
return getTaxonomiesFieldBuilder()
.addBuilder(index, com.google.cloud.datacatalog.v1.Taxonomy.getDefaultInstance());
}
/**
*
*
* <pre>
* Taxonomies that the project contains.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.Taxonomy taxonomies = 1;</code>
*/
public java.util.List<com.google.cloud.datacatalog.v1.Taxonomy.Builder>
getTaxonomiesBuilderList() {
return getTaxonomiesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datacatalog.v1.Taxonomy,
com.google.cloud.datacatalog.v1.Taxonomy.Builder,
com.google.cloud.datacatalog.v1.TaxonomyOrBuilder>
getTaxonomiesFieldBuilder() {
if (taxonomiesBuilder_ == null) {
taxonomiesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datacatalog.v1.Taxonomy,
com.google.cloud.datacatalog.v1.Taxonomy.Builder,
com.google.cloud.datacatalog.v1.TaxonomyOrBuilder>(
taxonomies_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
taxonomies_ = null;
}
return taxonomiesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Pagination token of the next results page. 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>
* Pagination token of the next results page. 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>
* Pagination token of the next results page. 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>
* Pagination token of the next results page. 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>
* Pagination token of the next results page. 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.datacatalog.v1.ListTaxonomiesResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.datacatalog.v1.ListTaxonomiesResponse)
private static final com.google.cloud.datacatalog.v1.ListTaxonomiesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.datacatalog.v1.ListTaxonomiesResponse();
}
public static com.google.cloud.datacatalog.v1.ListTaxonomiesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListTaxonomiesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListTaxonomiesResponse>() {
@java.lang.Override
public ListTaxonomiesResponse 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<ListTaxonomiesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListTaxonomiesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1.ListTaxonomiesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,711 | java-discoveryengine/google-cloud-discoveryengine/src/main/java/com/google/cloud/discoveryengine/v1beta/stub/CompletionServiceStubSettings.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.discoveryengine.v1beta.stub;
import com.google.api.core.ApiFunction;
import com.google.api.core.BetaApi;
import com.google.api.core.ObsoleteApi;
import com.google.api.gax.core.GaxProperties;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.grpc.GaxGrpcProperties;
import com.google.api.gax.grpc.GrpcTransportChannel;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.grpc.ProtoOperationTransformers;
import com.google.api.gax.httpjson.GaxHttpJsonProperties;
import com.google.api.gax.httpjson.HttpJsonTransportChannel;
import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider;
import com.google.api.gax.longrunning.OperationSnapshot;
import com.google.api.gax.longrunning.OperationTimedPollAlgorithm;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.StubSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.cloud.discoveryengine.v1beta.AdvancedCompleteQueryRequest;
import com.google.cloud.discoveryengine.v1beta.AdvancedCompleteQueryResponse;
import com.google.cloud.discoveryengine.v1beta.CompleteQueryRequest;
import com.google.cloud.discoveryengine.v1beta.CompleteQueryResponse;
import com.google.cloud.discoveryengine.v1beta.ImportCompletionSuggestionsMetadata;
import com.google.cloud.discoveryengine.v1beta.ImportCompletionSuggestionsRequest;
import com.google.cloud.discoveryengine.v1beta.ImportCompletionSuggestionsResponse;
import com.google.cloud.discoveryengine.v1beta.ImportSuggestionDenyListEntriesMetadata;
import com.google.cloud.discoveryengine.v1beta.ImportSuggestionDenyListEntriesRequest;
import com.google.cloud.discoveryengine.v1beta.ImportSuggestionDenyListEntriesResponse;
import com.google.cloud.discoveryengine.v1beta.PurgeCompletionSuggestionsMetadata;
import com.google.cloud.discoveryengine.v1beta.PurgeCompletionSuggestionsRequest;
import com.google.cloud.discoveryengine.v1beta.PurgeCompletionSuggestionsResponse;
import com.google.cloud.discoveryengine.v1beta.PurgeSuggestionDenyListEntriesMetadata;
import com.google.cloud.discoveryengine.v1beta.PurgeSuggestionDenyListEntriesRequest;
import com.google.cloud.discoveryengine.v1beta.PurgeSuggestionDenyListEntriesResponse;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.longrunning.Operation;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Settings class to configure an instance of {@link CompletionServiceStub}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (discoveryengine.googleapis.com) and default port (443) are
* used.
* <li>Credentials are acquired automatically through Application Default Credentials.
* <li>Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object.
*
* <p>For example, to set the
* [RetrySettings](https://cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.retrying.RetrySettings)
* of completeQuery:
*
* <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
* CompletionServiceStubSettings.Builder completionServiceSettingsBuilder =
* CompletionServiceStubSettings.newBuilder();
* completionServiceSettingsBuilder
* .completeQuerySettings()
* .setRetrySettings(
* completionServiceSettingsBuilder
* .completeQuerySettings()
* .getRetrySettings()
* .toBuilder()
* .setInitialRetryDelayDuration(Duration.ofSeconds(1))
* .setInitialRpcTimeoutDuration(Duration.ofSeconds(5))
* .setMaxAttempts(5)
* .setMaxRetryDelayDuration(Duration.ofSeconds(30))
* .setMaxRpcTimeoutDuration(Duration.ofSeconds(60))
* .setRetryDelayMultiplier(1.3)
* .setRpcTimeoutMultiplier(1.5)
* .setTotalTimeoutDuration(Duration.ofSeconds(300))
* .build());
* CompletionServiceStubSettings completionServiceSettings =
* completionServiceSettingsBuilder.build();
* }</pre>
*
* Please refer to the [Client Side Retry
* Guide](https://github.com/googleapis/google-cloud-java/blob/main/docs/client_retries.md) for
* additional support in setting retries.
*
* <p>To configure the RetrySettings of a Long Running Operation method, create an
* OperationTimedPollAlgorithm object and update the RPC's polling algorithm. For example, to
* configure the RetrySettings for importSuggestionDenyListEntries:
*
* <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
* CompletionServiceStubSettings.Builder completionServiceSettingsBuilder =
* CompletionServiceStubSettings.newBuilder();
* TimedRetryAlgorithm timedRetryAlgorithm =
* OperationalTimedPollAlgorithm.create(
* RetrySettings.newBuilder()
* .setInitialRetryDelayDuration(Duration.ofMillis(500))
* .setRetryDelayMultiplier(1.5)
* .setMaxRetryDelayDuration(Duration.ofMillis(5000))
* .setTotalTimeoutDuration(Duration.ofHours(24))
* .build());
* completionServiceSettingsBuilder
* .createClusterOperationSettings()
* .setPollingAlgorithm(timedRetryAlgorithm)
* .build();
* }</pre>
*/
@BetaApi
@Generated("by gapic-generator-java")
public class CompletionServiceStubSettings extends StubSettings<CompletionServiceStubSettings> {
/** The default scopes of the service. */
private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES =
ImmutableList.<String>builder().add("https://www.googleapis.com/auth/cloud-platform").build();
private final UnaryCallSettings<CompleteQueryRequest, CompleteQueryResponse>
completeQuerySettings;
private final UnaryCallSettings<AdvancedCompleteQueryRequest, AdvancedCompleteQueryResponse>
advancedCompleteQuerySettings;
private final UnaryCallSettings<ImportSuggestionDenyListEntriesRequest, Operation>
importSuggestionDenyListEntriesSettings;
private final OperationCallSettings<
ImportSuggestionDenyListEntriesRequest,
ImportSuggestionDenyListEntriesResponse,
ImportSuggestionDenyListEntriesMetadata>
importSuggestionDenyListEntriesOperationSettings;
private final UnaryCallSettings<PurgeSuggestionDenyListEntriesRequest, Operation>
purgeSuggestionDenyListEntriesSettings;
private final OperationCallSettings<
PurgeSuggestionDenyListEntriesRequest,
PurgeSuggestionDenyListEntriesResponse,
PurgeSuggestionDenyListEntriesMetadata>
purgeSuggestionDenyListEntriesOperationSettings;
private final UnaryCallSettings<ImportCompletionSuggestionsRequest, Operation>
importCompletionSuggestionsSettings;
private final OperationCallSettings<
ImportCompletionSuggestionsRequest,
ImportCompletionSuggestionsResponse,
ImportCompletionSuggestionsMetadata>
importCompletionSuggestionsOperationSettings;
private final UnaryCallSettings<PurgeCompletionSuggestionsRequest, Operation>
purgeCompletionSuggestionsSettings;
private final OperationCallSettings<
PurgeCompletionSuggestionsRequest,
PurgeCompletionSuggestionsResponse,
PurgeCompletionSuggestionsMetadata>
purgeCompletionSuggestionsOperationSettings;
/** Returns the object with the settings used for calls to completeQuery. */
public UnaryCallSettings<CompleteQueryRequest, CompleteQueryResponse> completeQuerySettings() {
return completeQuerySettings;
}
/** Returns the object with the settings used for calls to advancedCompleteQuery. */
public UnaryCallSettings<AdvancedCompleteQueryRequest, AdvancedCompleteQueryResponse>
advancedCompleteQuerySettings() {
return advancedCompleteQuerySettings;
}
/** Returns the object with the settings used for calls to importSuggestionDenyListEntries. */
public UnaryCallSettings<ImportSuggestionDenyListEntriesRequest, Operation>
importSuggestionDenyListEntriesSettings() {
return importSuggestionDenyListEntriesSettings;
}
/** Returns the object with the settings used for calls to importSuggestionDenyListEntries. */
public OperationCallSettings<
ImportSuggestionDenyListEntriesRequest,
ImportSuggestionDenyListEntriesResponse,
ImportSuggestionDenyListEntriesMetadata>
importSuggestionDenyListEntriesOperationSettings() {
return importSuggestionDenyListEntriesOperationSettings;
}
/** Returns the object with the settings used for calls to purgeSuggestionDenyListEntries. */
public UnaryCallSettings<PurgeSuggestionDenyListEntriesRequest, Operation>
purgeSuggestionDenyListEntriesSettings() {
return purgeSuggestionDenyListEntriesSettings;
}
/** Returns the object with the settings used for calls to purgeSuggestionDenyListEntries. */
public OperationCallSettings<
PurgeSuggestionDenyListEntriesRequest,
PurgeSuggestionDenyListEntriesResponse,
PurgeSuggestionDenyListEntriesMetadata>
purgeSuggestionDenyListEntriesOperationSettings() {
return purgeSuggestionDenyListEntriesOperationSettings;
}
/** Returns the object with the settings used for calls to importCompletionSuggestions. */
public UnaryCallSettings<ImportCompletionSuggestionsRequest, Operation>
importCompletionSuggestionsSettings() {
return importCompletionSuggestionsSettings;
}
/** Returns the object with the settings used for calls to importCompletionSuggestions. */
public OperationCallSettings<
ImportCompletionSuggestionsRequest,
ImportCompletionSuggestionsResponse,
ImportCompletionSuggestionsMetadata>
importCompletionSuggestionsOperationSettings() {
return importCompletionSuggestionsOperationSettings;
}
/** Returns the object with the settings used for calls to purgeCompletionSuggestions. */
public UnaryCallSettings<PurgeCompletionSuggestionsRequest, Operation>
purgeCompletionSuggestionsSettings() {
return purgeCompletionSuggestionsSettings;
}
/** Returns the object with the settings used for calls to purgeCompletionSuggestions. */
public OperationCallSettings<
PurgeCompletionSuggestionsRequest,
PurgeCompletionSuggestionsResponse,
PurgeCompletionSuggestionsMetadata>
purgeCompletionSuggestionsOperationSettings() {
return purgeCompletionSuggestionsOperationSettings;
}
public CompletionServiceStub createStub() throws IOException {
if (getTransportChannelProvider()
.getTransportName()
.equals(GrpcTransportChannel.getGrpcTransportName())) {
return GrpcCompletionServiceStub.create(this);
}
if (getTransportChannelProvider()
.getTransportName()
.equals(HttpJsonTransportChannel.getHttpJsonTransportName())) {
return HttpJsonCompletionServiceStub.create(this);
}
throw new UnsupportedOperationException(
String.format(
"Transport not supported: %s", getTransportChannelProvider().getTransportName()));
}
/** Returns the default service name. */
@Override
public String getServiceName() {
return "discoveryengine";
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return InstantiatingExecutorProvider.newBuilder();
}
/** Returns the default service endpoint. */
@ObsoleteApi("Use getEndpoint() instead")
public static String getDefaultEndpoint() {
return "discoveryengine.googleapis.com:443";
}
/** Returns the default mTLS service endpoint. */
public static String getDefaultMtlsEndpoint() {
return "discoveryengine.mtls.googleapis.com:443";
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return DEFAULT_SERVICE_SCOPES;
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return GoogleCredentialsProvider.newBuilder()
.setScopesToApply(DEFAULT_SERVICE_SCOPES)
.setUseJwtAccessWithScope(true);
}
/** Returns a builder for the default gRPC ChannelProvider for this service. */
public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() {
return InstantiatingGrpcChannelProvider.newBuilder()
.setMaxInboundMessageSize(Integer.MAX_VALUE);
}
/** Returns a builder for the default REST ChannelProvider for this service. */
@BetaApi
public static InstantiatingHttpJsonChannelProvider.Builder
defaultHttpJsonTransportProviderBuilder() {
return InstantiatingHttpJsonChannelProvider.newBuilder();
}
public static TransportChannelProvider defaultTransportChannelProvider() {
return defaultGrpcTransportProviderBuilder().build();
}
public static ApiClientHeaderProvider.Builder defaultGrpcApiClientHeaderProviderBuilder() {
return ApiClientHeaderProvider.newBuilder()
.setGeneratedLibToken(
"gapic", GaxProperties.getLibraryVersion(CompletionServiceStubSettings.class))
.setTransportToken(
GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion());
}
public static ApiClientHeaderProvider.Builder defaultHttpJsonApiClientHeaderProviderBuilder() {
return ApiClientHeaderProvider.newBuilder()
.setGeneratedLibToken(
"gapic", GaxProperties.getLibraryVersion(CompletionServiceStubSettings.class))
.setTransportToken(
GaxHttpJsonProperties.getHttpJsonTokenName(),
GaxHttpJsonProperties.getHttpJsonVersion());
}
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return CompletionServiceStubSettings.defaultGrpcApiClientHeaderProviderBuilder();
}
/** Returns a new gRPC builder for this class. */
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Returns a new REST builder for this class. */
public static Builder newHttpJsonBuilder() {
return Builder.createHttpJsonDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder(ClientContext clientContext) {
return new Builder(clientContext);
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
protected CompletionServiceStubSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
completeQuerySettings = settingsBuilder.completeQuerySettings().build();
advancedCompleteQuerySettings = settingsBuilder.advancedCompleteQuerySettings().build();
importSuggestionDenyListEntriesSettings =
settingsBuilder.importSuggestionDenyListEntriesSettings().build();
importSuggestionDenyListEntriesOperationSettings =
settingsBuilder.importSuggestionDenyListEntriesOperationSettings().build();
purgeSuggestionDenyListEntriesSettings =
settingsBuilder.purgeSuggestionDenyListEntriesSettings().build();
purgeSuggestionDenyListEntriesOperationSettings =
settingsBuilder.purgeSuggestionDenyListEntriesOperationSettings().build();
importCompletionSuggestionsSettings =
settingsBuilder.importCompletionSuggestionsSettings().build();
importCompletionSuggestionsOperationSettings =
settingsBuilder.importCompletionSuggestionsOperationSettings().build();
purgeCompletionSuggestionsSettings =
settingsBuilder.purgeCompletionSuggestionsSettings().build();
purgeCompletionSuggestionsOperationSettings =
settingsBuilder.purgeCompletionSuggestionsOperationSettings().build();
}
/** Builder for CompletionServiceStubSettings. */
public static class Builder extends StubSettings.Builder<CompletionServiceStubSettings, Builder> {
private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders;
private final UnaryCallSettings.Builder<CompleteQueryRequest, CompleteQueryResponse>
completeQuerySettings;
private final UnaryCallSettings.Builder<
AdvancedCompleteQueryRequest, AdvancedCompleteQueryResponse>
advancedCompleteQuerySettings;
private final UnaryCallSettings.Builder<ImportSuggestionDenyListEntriesRequest, Operation>
importSuggestionDenyListEntriesSettings;
private final OperationCallSettings.Builder<
ImportSuggestionDenyListEntriesRequest,
ImportSuggestionDenyListEntriesResponse,
ImportSuggestionDenyListEntriesMetadata>
importSuggestionDenyListEntriesOperationSettings;
private final UnaryCallSettings.Builder<PurgeSuggestionDenyListEntriesRequest, Operation>
purgeSuggestionDenyListEntriesSettings;
private final OperationCallSettings.Builder<
PurgeSuggestionDenyListEntriesRequest,
PurgeSuggestionDenyListEntriesResponse,
PurgeSuggestionDenyListEntriesMetadata>
purgeSuggestionDenyListEntriesOperationSettings;
private final UnaryCallSettings.Builder<ImportCompletionSuggestionsRequest, Operation>
importCompletionSuggestionsSettings;
private final OperationCallSettings.Builder<
ImportCompletionSuggestionsRequest,
ImportCompletionSuggestionsResponse,
ImportCompletionSuggestionsMetadata>
importCompletionSuggestionsOperationSettings;
private final UnaryCallSettings.Builder<PurgeCompletionSuggestionsRequest, Operation>
purgeCompletionSuggestionsSettings;
private final OperationCallSettings.Builder<
PurgeCompletionSuggestionsRequest,
PurgeCompletionSuggestionsResponse,
PurgeCompletionSuggestionsMetadata>
purgeCompletionSuggestionsOperationSettings;
private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>>
RETRYABLE_CODE_DEFINITIONS;
static {
ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions =
ImmutableMap.builder();
definitions.put(
"retry_policy_0_codes",
ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList(StatusCode.Code.UNAVAILABLE)));
RETRYABLE_CODE_DEFINITIONS = definitions.build();
}
private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS;
static {
ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder();
RetrySettings settings = null;
settings =
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(100L))
.setRetryDelayMultiplier(1.3)
.setMaxRetryDelayDuration(Duration.ofMillis(5000L))
.setInitialRpcTimeoutDuration(Duration.ofMillis(5000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ofMillis(5000L))
.setTotalTimeoutDuration(Duration.ofMillis(5000L))
.build();
definitions.put("retry_policy_0_params", settings);
RETRY_PARAM_DEFINITIONS = definitions.build();
}
protected Builder() {
this(((ClientContext) null));
}
protected Builder(ClientContext clientContext) {
super(clientContext);
completeQuerySettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
advancedCompleteQuerySettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
importSuggestionDenyListEntriesSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
importSuggestionDenyListEntriesOperationSettings = OperationCallSettings.newBuilder();
purgeSuggestionDenyListEntriesSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
purgeSuggestionDenyListEntriesOperationSettings = OperationCallSettings.newBuilder();
importCompletionSuggestionsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
importCompletionSuggestionsOperationSettings = OperationCallSettings.newBuilder();
purgeCompletionSuggestionsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
purgeCompletionSuggestionsOperationSettings = OperationCallSettings.newBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
completeQuerySettings,
advancedCompleteQuerySettings,
importSuggestionDenyListEntriesSettings,
purgeSuggestionDenyListEntriesSettings,
importCompletionSuggestionsSettings,
purgeCompletionSuggestionsSettings);
initDefaults(this);
}
protected Builder(CompletionServiceStubSettings settings) {
super(settings);
completeQuerySettings = settings.completeQuerySettings.toBuilder();
advancedCompleteQuerySettings = settings.advancedCompleteQuerySettings.toBuilder();
importSuggestionDenyListEntriesSettings =
settings.importSuggestionDenyListEntriesSettings.toBuilder();
importSuggestionDenyListEntriesOperationSettings =
settings.importSuggestionDenyListEntriesOperationSettings.toBuilder();
purgeSuggestionDenyListEntriesSettings =
settings.purgeSuggestionDenyListEntriesSettings.toBuilder();
purgeSuggestionDenyListEntriesOperationSettings =
settings.purgeSuggestionDenyListEntriesOperationSettings.toBuilder();
importCompletionSuggestionsSettings =
settings.importCompletionSuggestionsSettings.toBuilder();
importCompletionSuggestionsOperationSettings =
settings.importCompletionSuggestionsOperationSettings.toBuilder();
purgeCompletionSuggestionsSettings = settings.purgeCompletionSuggestionsSettings.toBuilder();
purgeCompletionSuggestionsOperationSettings =
settings.purgeCompletionSuggestionsOperationSettings.toBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
completeQuerySettings,
advancedCompleteQuerySettings,
importSuggestionDenyListEntriesSettings,
purgeSuggestionDenyListEntriesSettings,
importCompletionSuggestionsSettings,
purgeCompletionSuggestionsSettings);
}
private static Builder createDefault() {
Builder builder = new Builder(((ClientContext) null));
builder.setTransportChannelProvider(defaultTransportChannelProvider());
builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build());
builder.setMtlsEndpoint(getDefaultMtlsEndpoint());
builder.setSwitchToMtlsEndpointAllowed(true);
return initDefaults(builder);
}
private static Builder createHttpJsonDefault() {
Builder builder = new Builder(((ClientContext) null));
builder.setTransportChannelProvider(defaultHttpJsonTransportProviderBuilder().build());
builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
builder.setInternalHeaderProvider(defaultHttpJsonApiClientHeaderProviderBuilder().build());
builder.setMtlsEndpoint(getDefaultMtlsEndpoint());
builder.setSwitchToMtlsEndpointAllowed(true);
return initDefaults(builder);
}
private static Builder initDefaults(Builder builder) {
builder
.completeQuerySettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.advancedCompleteQuerySettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.importSuggestionDenyListEntriesSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.purgeSuggestionDenyListEntriesSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.importCompletionSuggestionsSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.purgeCompletionSuggestionsSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.importSuggestionDenyListEntriesOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<ImportSuggestionDenyListEntriesRequest, OperationSnapshot>
newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(
ImportSuggestionDenyListEntriesResponse.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(
ImportSuggestionDenyListEntriesMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(45000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(300000L))
.build()));
builder
.purgeSuggestionDenyListEntriesOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<PurgeSuggestionDenyListEntriesRequest, OperationSnapshot>
newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(
PurgeSuggestionDenyListEntriesResponse.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(
PurgeSuggestionDenyListEntriesMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(45000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(300000L))
.build()));
builder
.importCompletionSuggestionsOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<ImportCompletionSuggestionsRequest, OperationSnapshot>
newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(
ImportCompletionSuggestionsResponse.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(
ImportCompletionSuggestionsMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(45000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(300000L))
.build()));
builder
.purgeCompletionSuggestionsOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<PurgeCompletionSuggestionsRequest, OperationSnapshot>
newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(
PurgeCompletionSuggestionsResponse.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(
PurgeCompletionSuggestionsMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(45000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(300000L))
.build()));
return builder;
}
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater);
return this;
}
public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() {
return unaryMethodSettingsBuilders;
}
/** Returns the builder for the settings used for calls to completeQuery. */
public UnaryCallSettings.Builder<CompleteQueryRequest, CompleteQueryResponse>
completeQuerySettings() {
return completeQuerySettings;
}
/** Returns the builder for the settings used for calls to advancedCompleteQuery. */
public UnaryCallSettings.Builder<AdvancedCompleteQueryRequest, AdvancedCompleteQueryResponse>
advancedCompleteQuerySettings() {
return advancedCompleteQuerySettings;
}
/** Returns the builder for the settings used for calls to importSuggestionDenyListEntries. */
public UnaryCallSettings.Builder<ImportSuggestionDenyListEntriesRequest, Operation>
importSuggestionDenyListEntriesSettings() {
return importSuggestionDenyListEntriesSettings;
}
/** Returns the builder for the settings used for calls to importSuggestionDenyListEntries. */
public OperationCallSettings.Builder<
ImportSuggestionDenyListEntriesRequest,
ImportSuggestionDenyListEntriesResponse,
ImportSuggestionDenyListEntriesMetadata>
importSuggestionDenyListEntriesOperationSettings() {
return importSuggestionDenyListEntriesOperationSettings;
}
/** Returns the builder for the settings used for calls to purgeSuggestionDenyListEntries. */
public UnaryCallSettings.Builder<PurgeSuggestionDenyListEntriesRequest, Operation>
purgeSuggestionDenyListEntriesSettings() {
return purgeSuggestionDenyListEntriesSettings;
}
/** Returns the builder for the settings used for calls to purgeSuggestionDenyListEntries. */
public OperationCallSettings.Builder<
PurgeSuggestionDenyListEntriesRequest,
PurgeSuggestionDenyListEntriesResponse,
PurgeSuggestionDenyListEntriesMetadata>
purgeSuggestionDenyListEntriesOperationSettings() {
return purgeSuggestionDenyListEntriesOperationSettings;
}
/** Returns the builder for the settings used for calls to importCompletionSuggestions. */
public UnaryCallSettings.Builder<ImportCompletionSuggestionsRequest, Operation>
importCompletionSuggestionsSettings() {
return importCompletionSuggestionsSettings;
}
/** Returns the builder for the settings used for calls to importCompletionSuggestions. */
public OperationCallSettings.Builder<
ImportCompletionSuggestionsRequest,
ImportCompletionSuggestionsResponse,
ImportCompletionSuggestionsMetadata>
importCompletionSuggestionsOperationSettings() {
return importCompletionSuggestionsOperationSettings;
}
/** Returns the builder for the settings used for calls to purgeCompletionSuggestions. */
public UnaryCallSettings.Builder<PurgeCompletionSuggestionsRequest, Operation>
purgeCompletionSuggestionsSettings() {
return purgeCompletionSuggestionsSettings;
}
/** Returns the builder for the settings used for calls to purgeCompletionSuggestions. */
public OperationCallSettings.Builder<
PurgeCompletionSuggestionsRequest,
PurgeCompletionSuggestionsResponse,
PurgeCompletionSuggestionsMetadata>
purgeCompletionSuggestionsOperationSettings() {
return purgeCompletionSuggestionsOperationSettings;
}
@Override
public CompletionServiceStubSettings build() throws IOException {
return new CompletionServiceStubSettings(this);
}
}
}
|
apache/tajo | 36,822 | tajo-core/src/main/java/org/apache/tajo/engine/planner/global/builder/DistinctGroupbyBuilder.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tajo.engine.planner.global.builder;
import com.google.common.base.Preconditions;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tajo.catalog.Column;
import org.apache.tajo.catalog.Schema;
import org.apache.tajo.catalog.SchemaBuilder;
import org.apache.tajo.catalog.SchemaFactory;
import org.apache.tajo.catalog.proto.CatalogProtos.SortSpecProto;
import org.apache.tajo.common.TajoDataTypes.Type;
import org.apache.tajo.engine.planner.global.DataChannel;
import org.apache.tajo.engine.planner.global.ExecutionBlock;
import org.apache.tajo.engine.planner.global.GlobalPlanner;
import org.apache.tajo.engine.planner.global.GlobalPlanner.GlobalPlanContext;
import org.apache.tajo.engine.planner.global.MasterPlan;
import org.apache.tajo.exception.TajoException;
import org.apache.tajo.exception.TajoInternalError;
import org.apache.tajo.plan.serder.PlanProto.DistinctGroupbyEnforcer.DistinctAggregationAlgorithm;
import org.apache.tajo.plan.serder.PlanProto.DistinctGroupbyEnforcer.MultipleAggregationStage;
import org.apache.tajo.plan.serder.PlanProto.DistinctGroupbyEnforcer.SortSpecArray;
import org.apache.tajo.plan.LogicalPlan;
import org.apache.tajo.plan.util.PlannerUtil;
import org.apache.tajo.plan.Target;
import org.apache.tajo.plan.expr.AggregationFunctionCallEval;
import org.apache.tajo.plan.expr.EvalNode;
import org.apache.tajo.plan.expr.EvalTreeUtil;
import org.apache.tajo.plan.expr.FieldEval;
import org.apache.tajo.plan.logical.DistinctGroupbyNode;
import org.apache.tajo.plan.logical.GroupbyNode;
import org.apache.tajo.plan.logical.LogicalNode;
import org.apache.tajo.plan.logical.ScanNode;
import org.apache.tajo.util.TUtil;
import java.util.*;
import static org.apache.tajo.plan.serder.PlanProto.ShuffleType.HASH_SHUFFLE;
public class DistinctGroupbyBuilder {
private static Log LOG = LogFactory.getLog(DistinctGroupbyBuilder.class);
private GlobalPlanner globalPlanner;
public DistinctGroupbyBuilder(GlobalPlanner globalPlanner) {
this.globalPlanner = globalPlanner;
}
public ExecutionBlock buildMultiLevelPlan(GlobalPlanContext context,
ExecutionBlock latestExecBlock,
LogicalNode currentNode) {
try {
GroupbyNode groupbyNode = (GroupbyNode) currentNode;
LogicalPlan plan = context.getPlan().getLogicalPlan();
DistinctGroupbyNode baseDistinctNode =
buildMultiLevelBaseDistinctGroupByNode(context, latestExecBlock, groupbyNode);
baseDistinctNode.setGroupbyPlan(groupbyNode);
// Set total Aggregation Functions.
List<AggregationFunctionCallEval> aggFunctions = new ArrayList<>();
for (int i = 0; i < groupbyNode.getAggFunctions().size(); i++) {
aggFunctions.add((AggregationFunctionCallEval) groupbyNode.getAggFunctions().get(i).clone());
aggFunctions.get(i).setFirstPhase();
// If there is not grouping column, we can't find column alias.
// Thus we should find the alias at Groupbynode output schema.
if (groupbyNode.getGroupingColumns().length == 0
&& aggFunctions.size() == groupbyNode.getOutSchema().getRootColumns().size()) {
aggFunctions.get(i).setAlias(groupbyNode.getOutSchema().getColumn(i).getQualifiedName());
}
}
if (groupbyNode.getGroupingColumns().length == 0
&& aggFunctions.size() == groupbyNode.getOutSchema().getRootColumns().size()) {
groupbyNode.setAggFunctions(aggFunctions);
}
baseDistinctNode.setAggFunctions(aggFunctions);
// Create First, SecondStage's Node using baseNode
DistinctGroupbyNode firstStageDistinctNode = PlannerUtil.clone(plan, baseDistinctNode);
DistinctGroupbyNode secondStageDistinctNode = PlannerUtil.clone(plan, baseDistinctNode);
DistinctGroupbyNode thirdStageDistinctNode = PlannerUtil.clone(plan, baseDistinctNode);
// Set second, third non-distinct aggregation's eval node to field eval
GroupbyNode lastGroupbyNode = secondStageDistinctNode.getSubPlans().get(secondStageDistinctNode.getSubPlans().size() - 1);
if (!lastGroupbyNode.isDistinct()) {
int index = 0;
for (AggregationFunctionCallEval aggrFunction: lastGroupbyNode.getAggFunctions()) {
aggrFunction.setIntermediatePhase();
aggrFunction.setArgs(new EvalNode[]{new FieldEval(lastGroupbyNode.getTargets().get(index).getNamedColumn())});
index++;
}
}
lastGroupbyNode = thirdStageDistinctNode.getSubPlans().get(thirdStageDistinctNode.getSubPlans().size() - 1);
if (!lastGroupbyNode.isDistinct()) {
int index = 0;
for (AggregationFunctionCallEval aggrFunction: lastGroupbyNode.getAggFunctions()) {
aggrFunction.setFirstPhase();
aggrFunction.setArgs(new EvalNode[]{new FieldEval(lastGroupbyNode.getTargets().get(index).getNamedColumn())});
index++;
}
}
// Set in & out schema for each DistinctGroupbyNode.
secondStageDistinctNode.setInSchema(firstStageDistinctNode.getOutSchema());
secondStageDistinctNode.setOutSchema(firstStageDistinctNode.getOutSchema());
thirdStageDistinctNode.setInSchema(firstStageDistinctNode.getOutSchema());
thirdStageDistinctNode.setOutSchema(groupbyNode.getOutSchema());
// Set latestExecBlock's plan with firstDistinctNode
latestExecBlock.setPlan(firstStageDistinctNode);
// Make SecondStage ExecutionBlock
ExecutionBlock secondStageBlock = context.getPlan().newExecutionBlock();
// Make ThirdStage ExecutionBlock
ExecutionBlock thirdStageBlock = context.getPlan().newExecutionBlock();
// Set Enforcer
setMultiStageAggregationEnforcer(latestExecBlock, firstStageDistinctNode, secondStageBlock,
secondStageDistinctNode, thirdStageBlock, thirdStageDistinctNode);
//Create data channel FirstStage to SecondStage
DataChannel firstChannel = new DataChannel(latestExecBlock, secondStageBlock, HASH_SHUFFLE, 32);
firstChannel.setShuffleKeys(firstStageDistinctNode.getFirstStageShuffleKeyColumns());
firstChannel.setSchema(firstStageDistinctNode.getOutSchema());
firstChannel.setDataFormat(globalPlanner.getDataFormat());
ScanNode scanNode = GlobalPlanner.buildInputExecutor(context.getPlan().getLogicalPlan(), firstChannel);
secondStageDistinctNode.setChild(scanNode);
secondStageBlock.setPlan(secondStageDistinctNode);
context.getPlan().addConnect(firstChannel);
DataChannel secondChannel;
//Create data channel SecondStage to ThirdStage
if (groupbyNode.isEmptyGrouping()) {
secondChannel = new DataChannel(secondStageBlock, thirdStageBlock, HASH_SHUFFLE, 1);
secondChannel.setShuffleKeys(firstStageDistinctNode.getGroupingColumns());
} else {
secondChannel = new DataChannel(secondStageBlock, thirdStageBlock, HASH_SHUFFLE, 32);
secondChannel.setShuffleKeys(firstStageDistinctNode.getGroupingColumns());
}
secondChannel.setSchema(secondStageDistinctNode.getOutSchema());
secondChannel.setDataFormat(globalPlanner.getDataFormat());
scanNode = GlobalPlanner.buildInputExecutor(context.getPlan().getLogicalPlan(), secondChannel);
thirdStageDistinctNode.setChild(scanNode);
thirdStageBlock.setPlan(thirdStageDistinctNode);
context.getPlan().addConnect(secondChannel);
if (GlobalPlanner.hasUnionChild(firstStageDistinctNode)) {
buildDistinctGroupbyAndUnionPlan(
context.getPlan(), latestExecBlock, firstStageDistinctNode, firstStageDistinctNode);
}
return thirdStageBlock;
} catch (Exception e) {
throw new TajoInternalError(e);
}
}
private DistinctGroupbyNode buildMultiLevelBaseDistinctGroupByNode(GlobalPlanContext context,
ExecutionBlock latestExecBlock,
GroupbyNode groupbyNode) {
/*
Making DistinctGroupbyNode from GroupByNode
select col1, count(distinct col2), count(distinct col3), sum(col4) from ... group by col1
=> DistinctGroupbyNode
Distinct Seq
grouping key = col1
Sub GroupbyNodes
- GroupByNode1: grouping(col2), expr(count distinct col2)
- GroupByNode2: grouping(col3), expr(count distinct col3)
- GroupByNode3: expr(sum col4)
*/
List<Column> originalGroupingColumns = Arrays.asList(groupbyNode.getGroupingColumns());
List<GroupbyNode> childGroupbyNodes = new ArrayList<>();
List<AggregationFunctionCallEval> otherAggregationFunctionCallEvals = new ArrayList<>();
List<Target> otherAggregationFunctionTargets = new ArrayList<>();
//distinct columns -> GroupbyNode
Map<String, DistinctGroupbyNodeBuildInfo> distinctNodeBuildInfos = new HashMap<>();
List<AggregationFunctionCallEval> aggFunctions = groupbyNode.getAggFunctions();
for (int aggIdx = 0; aggIdx < aggFunctions.size(); aggIdx++) {
AggregationFunctionCallEval aggFunction = aggFunctions.get(aggIdx);
aggFunction.setFirstPhase();
Target originAggFunctionTarget = groupbyNode.getTargets().get(originalGroupingColumns.size() + aggIdx);
Target aggFunctionTarget =
new Target(new FieldEval(originAggFunctionTarget.getEvalTree().getName(), aggFunction.getValueType()));
if (aggFunction.isDistinct()) {
// Create or reuse Groupby node for each Distinct expression.
LinkedHashSet<Column> groupbyUniqColumns = EvalTreeUtil.findUniqueColumns(aggFunction);
String groupbyMapKey = EvalTreeUtil.columnsToStr(groupbyUniqColumns);
DistinctGroupbyNodeBuildInfo buildInfo = distinctNodeBuildInfos.get(groupbyMapKey);
if (buildInfo == null) {
GroupbyNode distinctGroupbyNode = new GroupbyNode(context.getPlan().getLogicalPlan().newPID());
buildInfo = new DistinctGroupbyNodeBuildInfo(distinctGroupbyNode);
distinctNodeBuildInfos.put(groupbyMapKey, buildInfo);
// Grouping columns are GROUP BY clause's column + Distinct column.
List<Column> groupingColumns = new ArrayList<>();
for (Column eachGroupingColumn: groupbyUniqColumns) {
if (!groupingColumns.contains(eachGroupingColumn)) {
groupingColumns.add(eachGroupingColumn);
}
}
distinctGroupbyNode.setGroupingColumns(groupingColumns.toArray(new Column[groupingColumns.size()]));
}
buildInfo.addAggFunction(aggFunction);
buildInfo.addAggFunctionTarget(aggFunctionTarget);
} else {
otherAggregationFunctionCallEvals.add(aggFunction);
otherAggregationFunctionTargets.add(aggFunctionTarget);
}
}
List<Target> baseGroupByTargets = new ArrayList<>();
baseGroupByTargets.add(new Target(new FieldEval(new Column("?distinctseq", Type.INT2))));
for (Column column : originalGroupingColumns) {
baseGroupByTargets.add(new Target(new FieldEval(column)));
}
//Add child groupby node for each Distinct clause
for (DistinctGroupbyNodeBuildInfo buildInfo: distinctNodeBuildInfos.values()) {
GroupbyNode eachGroupbyNode = buildInfo.getGroupbyNode();
List<AggregationFunctionCallEval> groupbyAggFunctions = buildInfo.getAggFunctions();
List<Target> targets = new ArrayList<>();
for (Column column : eachGroupbyNode.getGroupingColumns()) {
Target target = new Target(new FieldEval(column));
targets.add(target);
baseGroupByTargets.add(target);
}
targets.addAll(buildInfo.getAggFunctionTargets());
eachGroupbyNode.setTargets(targets);
eachGroupbyNode.setAggFunctions(groupbyAggFunctions);
eachGroupbyNode.setDistinct(true);
eachGroupbyNode.setInSchema(groupbyNode.getInSchema());
childGroupbyNodes.add(eachGroupbyNode);
}
// Merge other aggregation function to a GroupBy Node.
if (!otherAggregationFunctionCallEvals.isEmpty()) {
// finally this aggregation output tuple's order is GROUP_BY_COL1, COL2, .... + AGG_VALUE, SUM_VALUE, ...
GroupbyNode otherGroupbyNode = new GroupbyNode(context.getPlan().getLogicalPlan().newPID());
List<Target> targets = new ArrayList<>();
targets.addAll(otherAggregationFunctionTargets);
baseGroupByTargets.addAll(otherAggregationFunctionTargets);
otherGroupbyNode.setTargets(targets);
otherGroupbyNode.setGroupingColumns(new Column[]{});
otherGroupbyNode.setAggFunctions(otherAggregationFunctionCallEvals);
otherGroupbyNode.setInSchema(groupbyNode.getInSchema());
childGroupbyNodes.add(otherGroupbyNode);
}
DistinctGroupbyNode baseDistinctNode = new DistinctGroupbyNode(context.getPlan().getLogicalPlan().newPID());
baseDistinctNode.setTargets(baseGroupByTargets);
baseDistinctNode.setGroupingColumns(groupbyNode.getGroupingColumns());
baseDistinctNode.setInSchema(groupbyNode.getInSchema());
baseDistinctNode.setChild(groupbyNode.getChild());
baseDistinctNode.setSubPlans(childGroupbyNodes);
return baseDistinctNode;
}
public ExecutionBlock buildPlan(GlobalPlanContext context,
ExecutionBlock latestExecBlock,
LogicalNode currentNode) {
try {
GroupbyNode groupbyNode = (GroupbyNode)currentNode;
LogicalPlan plan = context.getPlan().getLogicalPlan();
DistinctGroupbyNode baseDistinctNode = buildBaseDistinctGroupByNode(context, latestExecBlock, groupbyNode);
// Create First, SecondStage's Node using baseNode
DistinctGroupbyNode[] distinctNodes = createTwoPhaseDistinctNode(plan, groupbyNode, baseDistinctNode);
DistinctGroupbyNode firstStageDistinctNode = distinctNodes[0];
DistinctGroupbyNode secondStageDistinctNode = distinctNodes[1];
// Set latestExecBlock's plan with firstDistinctNode
latestExecBlock.setPlan(firstStageDistinctNode);
// Make SecondStage ExecutionBlock
ExecutionBlock secondStageBlock = context.getPlan().newExecutionBlock();
// Set Enforcer: SecondStage => SortAggregationAlgorithm
setDistinctAggregationEnforcer(latestExecBlock, firstStageDistinctNode, secondStageBlock, secondStageDistinctNode);
//Create data channel FirstStage to SecondStage
DataChannel channel;
if (groupbyNode.isEmptyGrouping()) {
channel = new DataChannel(latestExecBlock, secondStageBlock, HASH_SHUFFLE, 1);
channel.setShuffleKeys(firstStageDistinctNode.getGroupingColumns());
} else {
channel = new DataChannel(latestExecBlock, secondStageBlock, HASH_SHUFFLE, 32);
channel.setShuffleKeys(firstStageDistinctNode.getGroupingColumns());
}
channel.setSchema(firstStageDistinctNode.getOutSchema());
channel.setDataFormat(globalPlanner.getDataFormat());
ScanNode scanNode = GlobalPlanner.buildInputExecutor(context.getPlan().getLogicalPlan(), channel);
secondStageDistinctNode.setChild(scanNode);
secondStageBlock.setPlan(secondStageDistinctNode);
context.getPlan().addConnect(channel);
if (GlobalPlanner.hasUnionChild(firstStageDistinctNode)) {
buildDistinctGroupbyAndUnionPlan(
context.getPlan(), latestExecBlock, firstStageDistinctNode, firstStageDistinctNode);
}
return secondStageBlock;
} catch (Exception e) {
throw new TajoInternalError(e);
}
}
private DistinctGroupbyNode buildBaseDistinctGroupByNode(GlobalPlanContext context,
ExecutionBlock latestExecBlock,
GroupbyNode groupbyNode) {
/*
Making DistinctGroupbyNode from GroupByNode
select col1, count(distinct col2), count(distinct col3), sum(col4) from ... group by col1
=> DistinctGroupbyNode
grouping key = col1
Sub GroupbyNodes
- GroupByNode1: grouping(col1, col2), expr(count distinct col2)
- GroupByNode2: grouping(col1, col3), expr(count distinct col3)
- GroupByNode3: grouping(col1), expr(sum col4)
*/
List<Column> originalGroupingColumns = Arrays.asList(groupbyNode.getGroupingColumns());
List<GroupbyNode> childGroupbyNodes = new ArrayList<>();
List<AggregationFunctionCallEval> otherAggregationFunctionCallEvals = new ArrayList<>();
List<Target> otherAggregationFunctionTargets = new ArrayList<>();
//distinct columns -> GroupbyNode
Map<String, DistinctGroupbyNodeBuildInfo> distinctNodeBuildInfos = new HashMap<>();
List<AggregationFunctionCallEval> aggFunctions = groupbyNode.getAggFunctions();
for (int aggIdx = 0; aggIdx < aggFunctions.size(); aggIdx++) {
AggregationFunctionCallEval aggFunction = aggFunctions.get(aggIdx);
Target aggFunctionTarget = groupbyNode.getTargets().get(originalGroupingColumns.size() + aggIdx);
if (aggFunction.isDistinct()) {
// Create or reuse Groupby node for each Distinct expression.
LinkedHashSet<Column> groupbyUniqColumns = EvalTreeUtil.findUniqueColumns(aggFunction);
String groupbyMapKey = EvalTreeUtil.columnsToStr(groupbyUniqColumns);
DistinctGroupbyNodeBuildInfo buildInfo = distinctNodeBuildInfos.get(groupbyMapKey);
if (buildInfo == null) {
GroupbyNode distinctGroupbyNode = new GroupbyNode(context.getPlan().getLogicalPlan().newPID());
buildInfo = new DistinctGroupbyNodeBuildInfo(distinctGroupbyNode);
distinctNodeBuildInfos.put(groupbyMapKey, buildInfo);
// Grouping columns are GROUP BY clause's column + Distinct column.
List<Column> groupingColumns = new ArrayList<>(originalGroupingColumns);
for (Column eachGroupingColumn: groupbyUniqColumns) {
if (!groupingColumns.contains(eachGroupingColumn)) {
groupingColumns.add(eachGroupingColumn);
}
}
distinctGroupbyNode.setGroupingColumns(groupingColumns.toArray(new Column[groupingColumns.size()]));
}
buildInfo.addAggFunction(aggFunction);
buildInfo.addAggFunctionTarget(aggFunctionTarget);
} else {
aggFunction.setLastPhase();
otherAggregationFunctionCallEvals.add(aggFunction);
otherAggregationFunctionTargets.add(aggFunctionTarget);
}
}
//Add child groupby node for each Distinct clause
for (DistinctGroupbyNodeBuildInfo buildInfo: distinctNodeBuildInfos.values()) {
GroupbyNode eachGroupbyNode = buildInfo.getGroupbyNode();
List<AggregationFunctionCallEval> groupbyAggFunctions = buildInfo.getAggFunctions();
List<Target> targets = new ArrayList<>();
for (Column column : eachGroupbyNode.getGroupingColumns()) {
targets.add(new Target(new FieldEval(column)));
}
targets.addAll(buildInfo.getAggFunctionTargets());
eachGroupbyNode.setTargets(targets);
eachGroupbyNode.setAggFunctions(groupbyAggFunctions);
eachGroupbyNode.setDistinct(true);
eachGroupbyNode.setInSchema(groupbyNode.getInSchema());
childGroupbyNodes.add(eachGroupbyNode);
}
// Merge other aggregation function to a GroupBy Node.
if (!otherAggregationFunctionCallEvals.isEmpty()) {
// finally this aggregation output tuple's order is GROUP_BY_COL1, COL2, .... + AGG_VALUE, SUM_VALUE, ...
GroupbyNode otherGroupbyNode = new GroupbyNode(context.getPlan().getLogicalPlan().newPID());
List<Target> targets = new ArrayList<>();
for (Column column : originalGroupingColumns) {
targets.add(new Target(new FieldEval(column)));
}
targets.addAll(otherAggregationFunctionTargets);
otherGroupbyNode.setTargets(targets);
otherGroupbyNode.setGroupingColumns(originalGroupingColumns.toArray(new Column[originalGroupingColumns.size()]));
otherGroupbyNode.setAggFunctions(otherAggregationFunctionCallEvals);
otherGroupbyNode.setInSchema(groupbyNode.getInSchema());
childGroupbyNodes.add(otherGroupbyNode);
}
DistinctGroupbyNode baseDistinctNode = new DistinctGroupbyNode(context.getPlan().getLogicalPlan().newPID());
baseDistinctNode.setTargets(groupbyNode.getTargets());
baseDistinctNode.setGroupingColumns(groupbyNode.getGroupingColumns());
baseDistinctNode.setInSchema(groupbyNode.getInSchema());
baseDistinctNode.setChild(groupbyNode.getChild());
baseDistinctNode.setSubPlans(childGroupbyNodes);
return baseDistinctNode;
}
public DistinctGroupbyNode[] createTwoPhaseDistinctNode(LogicalPlan plan,
GroupbyNode originGroupbyNode,
DistinctGroupbyNode baseDistinctNode) {
/*
Creating 2 stage execution block
- first stage: HashAggregation -> groupby distinct column and eval not distinct aggregation
==> HashShuffle
- second stage: SortAggregation -> sort and eval(aggregate) with distinct aggregation function, not distinct aggregation
select col1, count(distinct col2), count(distinct col3), sum(col4) from ... group by col1
-------------------------------------------------------------------------
- baseDistinctNode
grouping key = col1
- GroupByNode1: grouping(col1, col2), expr(count distinct col2)
- GroupByNode2: grouping(col1, col3), expr(count distinct col3)
- GroupByNode3: grouping(col1), expr(sum col4)
-------------------------------------------------------------------------
- FirstStage:
- GroupByNode1: grouping(col1, col2)
- GroupByNode2: grouping(col1, col3)
- GroupByNode3: grouping(col1), expr(sum col4)
- SecondStage:
- GroupByNode1: grouping(col1, col2), expr(count distinct col2)
- GroupByNode2: grouping(col1, col3), expr(count distinct col3)
- GroupByNode3: grouping(col1), expr(sum col4)
*/
Preconditions.checkNotNull(baseDistinctNode);
Schema originOutputSchema = originGroupbyNode.getOutSchema();
DistinctGroupbyNode firstStageDistinctNode = PlannerUtil.clone(plan, baseDistinctNode);
DistinctGroupbyNode secondStageDistinctNode = baseDistinctNode;
List<Column> originGroupColumns = Arrays.asList(firstStageDistinctNode.getGroupingColumns());
int[] secondStageColumnIds = new int[secondStageDistinctNode.getOutSchema().size()];
int columnIdIndex = 0;
for (Column column: secondStageDistinctNode.getGroupingColumns()) {
if (column.hasQualifier()) {
secondStageColumnIds[originOutputSchema.getColumnId(column.getQualifiedName())] = columnIdIndex;
} else {
secondStageColumnIds[originOutputSchema.getColumnIdByName(column.getSimpleName())] = columnIdIndex;
}
columnIdIndex++;
}
// Split groupby node into two stage.
// - Remove distinct aggregations from FirstStage.
// - Change SecondStage's aggregation expr and target column name. For example:
// exprs: (sum(default.lineitem.l_quantity (FLOAT8))) ==> exprs: (sum(?sum_3 (FLOAT8)))
int grpIdx = 0;
for (GroupbyNode firstStageGroupbyNode: firstStageDistinctNode.getSubPlans()) {
GroupbyNode secondStageGroupbyNode = secondStageDistinctNode.getSubPlans().get(grpIdx);
if (firstStageGroupbyNode.isDistinct()) {
// FirstStage: Remove aggregation, Set target with only grouping columns
firstStageGroupbyNode.setAggFunctions(PlannerUtil.EMPTY_AGG_FUNCS);
List<Target> firstGroupbyTargets = new ArrayList<>();
for (Column column : firstStageGroupbyNode.getGroupingColumns()) {
Target target = new Target(new FieldEval(column));
firstGroupbyTargets.add(target);
}
firstStageGroupbyNode.setTargets(firstGroupbyTargets);
// SecondStage:
// Set grouping column with origin groupby's columns
// Remove distinct group column from targets
secondStageGroupbyNode.setGroupingColumns(originGroupColumns.toArray(new Column[originGroupColumns.size()]));
List<Target> oldTargets = secondStageGroupbyNode.getTargets();
List<Target> secondGroupbyTargets = new ArrayList<>();
LinkedHashSet<Column> distinctColumns = EvalTreeUtil.findUniqueColumns(secondStageGroupbyNode.getAggFunctions().get(0));
List<Column> uniqueDistinctColumn = new ArrayList<>();
// remove origin group by column from distinctColumns
for (Column eachColumn: distinctColumns) {
if (!originGroupColumns.contains(eachColumn)) {
uniqueDistinctColumn.add(eachColumn);
}
}
for (int i = 0; i < originGroupColumns.size(); i++) {
secondGroupbyTargets.add(oldTargets.get(i));
if (grpIdx > 0) {
columnIdIndex++;
}
}
for (int aggFuncIdx = 0; aggFuncIdx < secondStageGroupbyNode.getAggFunctions().size(); aggFuncIdx++) {
secondStageGroupbyNode.getAggFunctions().get(aggFuncIdx).setLastPhase();
int targetIdx = originGroupColumns.size() + uniqueDistinctColumn.size() + aggFuncIdx;
Target aggFuncTarget = oldTargets.get(targetIdx);
secondGroupbyTargets.add(aggFuncTarget);
Column column = aggFuncTarget.getNamedColumn();
if (column.hasQualifier()) {
secondStageColumnIds[originOutputSchema.getColumnId(column.getQualifiedName())] = columnIdIndex;
} else {
secondStageColumnIds[originOutputSchema.getColumnIdByName(column.getSimpleName())] = columnIdIndex;
}
columnIdIndex++;
}
secondStageGroupbyNode.setTargets(secondGroupbyTargets);
} else {
// FirstStage: Change target of aggFunction to function name expr
List<Target> firstGroupbyTargets = new ArrayList<>();
for (Column column : firstStageDistinctNode.getGroupingColumns()) {
firstGroupbyTargets.add(new Target(new FieldEval(column)));
columnIdIndex++;
}
int aggFuncIdx = 0;
for (AggregationFunctionCallEval aggFunction: firstStageGroupbyNode.getAggFunctions()) {
aggFunction.setFirstPhase();
String firstEvalNames = plan.generateUniqueColumnName(aggFunction);
FieldEval firstEval = new FieldEval(firstEvalNames, aggFunction.getValueType());
firstGroupbyTargets.add(new Target(firstEval));
AggregationFunctionCallEval secondStageAggFunction = secondStageGroupbyNode.getAggFunctions().get(aggFuncIdx);
secondStageAggFunction.setArgs(new EvalNode[] {firstEval});
secondStageAggFunction.setLastPhase();
Target secondTarget = secondStageGroupbyNode.getTargets().get(secondStageGroupbyNode.getGroupingColumns().length + aggFuncIdx);
Column column = secondTarget.getNamedColumn();
if (column.hasQualifier()) {
secondStageColumnIds[originOutputSchema.getColumnId(column.getQualifiedName())] = columnIdIndex;
} else {
secondStageColumnIds[originOutputSchema.getColumnIdByName(column.getSimpleName())] = columnIdIndex;
}
columnIdIndex++;
aggFuncIdx++;
}
firstStageGroupbyNode.setTargets(firstGroupbyTargets);
secondStageGroupbyNode.setInSchema(firstStageGroupbyNode.getOutSchema());
}
grpIdx++;
}
// In the case of distinct query without group by clause
// other aggregation function is added to last distinct group by node.
List<GroupbyNode> secondStageGroupbyNodes = secondStageDistinctNode.getSubPlans();
GroupbyNode lastSecondStageGroupbyNode = secondStageGroupbyNodes.get(secondStageGroupbyNodes.size() - 1);
if (!lastSecondStageGroupbyNode.isDistinct() && lastSecondStageGroupbyNode.isEmptyGrouping()) {
GroupbyNode otherGroupbyNode = lastSecondStageGroupbyNode;
lastSecondStageGroupbyNode = secondStageGroupbyNodes.get(secondStageGroupbyNodes.size() - 2);
secondStageGroupbyNodes.remove(secondStageGroupbyNodes.size() - 1);
List<Target> targets = new ArrayList<>();
targets.addAll(lastSecondStageGroupbyNode.getTargets());
targets.addAll(otherGroupbyNode.getTargets());
lastSecondStageGroupbyNode.setTargets(targets);
List<AggregationFunctionCallEval> aggFunctions = new ArrayList<>();
aggFunctions.addAll(lastSecondStageGroupbyNode.getAggFunctions());
aggFunctions.addAll(otherGroupbyNode.getAggFunctions());
lastSecondStageGroupbyNode.setAggFunctions(aggFunctions);
}
// Set FirstStage DistinctNode's target with grouping column and other aggregation function
List<Integer> firstStageColumnIds = new ArrayList<>();
columnIdIndex = 0;
List<Target> firstTargets = new ArrayList<>();
for (GroupbyNode firstStageGroupbyNode: firstStageDistinctNode.getSubPlans()) {
if (firstStageGroupbyNode.isDistinct()) {
for (Column column : firstStageGroupbyNode.getGroupingColumns()) {
Target firstTarget = new Target(new FieldEval(column));
if (!firstTargets.contains(firstTarget)) {
firstTargets.add(firstTarget);
firstStageColumnIds.add(columnIdIndex);
}
columnIdIndex++;
}
} else {
//add aggr function target
columnIdIndex += firstStageGroupbyNode.getGroupingColumns().length;
List<Target> baseGroupbyTargets = firstStageGroupbyNode.getTargets();
for (int i = firstStageGroupbyNode.getGroupingColumns().length;
i < baseGroupbyTargets.size(); i++) {
firstTargets.add(baseGroupbyTargets.get(i));
firstStageColumnIds.add(columnIdIndex++);
}
}
}
firstStageDistinctNode.setTargets(firstTargets);
firstStageDistinctNode.setResultColumnIds(TUtil.toArray(firstStageColumnIds));
//Set SecondStage ColumnId and Input schema
secondStageDistinctNode.setResultColumnIds(secondStageColumnIds);
SchemaBuilder secondStageInSchema = SchemaBuilder.uniqueNameBuilder();
//TODO merged tuple schema
int index = 0;
for(GroupbyNode eachNode: secondStageDistinctNode.getSubPlans()) {
eachNode.setInSchema(firstStageDistinctNode.getOutSchema());
for (Column column: eachNode.getOutSchema().getRootColumns()) {
secondStageInSchema.add(column);
}
}
secondStageDistinctNode.setInSchema(secondStageInSchema.build());
return new DistinctGroupbyNode[]{firstStageDistinctNode, secondStageDistinctNode};
}
private void setDistinctAggregationEnforcer(
ExecutionBlock firstStageBlock, DistinctGroupbyNode firstStageDistinctNode,
ExecutionBlock secondStageBlock, DistinctGroupbyNode secondStageDistinctNode) {
firstStageBlock.getEnforcer().enforceDistinctAggregation(firstStageDistinctNode.getPID(),
DistinctAggregationAlgorithm.HASH_AGGREGATION, null);
List<SortSpecArray> sortSpecArrays = new ArrayList<>();
int index = 0;
for (GroupbyNode groupbyNode: firstStageDistinctNode.getSubPlans()) {
List<SortSpecProto> sortSpecs = new ArrayList<>();
for (Column column: groupbyNode.getGroupingColumns()) {
sortSpecs.add(SortSpecProto.newBuilder().setColumn(column.getProto()).build());
}
sortSpecArrays.add( SortSpecArray.newBuilder()
.setNodeId(secondStageDistinctNode.getSubPlans().get(index).getPID())
.addAllSortSpecs(sortSpecs).build());
}
secondStageBlock.getEnforcer().enforceDistinctAggregation(secondStageDistinctNode.getPID(),
DistinctAggregationAlgorithm.SORT_AGGREGATION, sortSpecArrays);
}
private void setMultiStageAggregationEnforcer(
ExecutionBlock firstStageBlock, DistinctGroupbyNode firstStageDistinctNode,
ExecutionBlock secondStageBlock, DistinctGroupbyNode secondStageDistinctNode,
ExecutionBlock thirdStageBlock, DistinctGroupbyNode thirdStageDistinctNode) {
firstStageBlock.getEnforcer().enforceDistinctAggregation(firstStageDistinctNode.getPID(),
true, MultipleAggregationStage.FIRST_STAGE,
DistinctAggregationAlgorithm.HASH_AGGREGATION, null);
secondStageBlock.getEnforcer().enforceDistinctAggregation(secondStageDistinctNode.getPID(),
true, MultipleAggregationStage.SECOND_STAGE,
DistinctAggregationAlgorithm.HASH_AGGREGATION, null);
List<SortSpecArray> sortSpecArrays = new ArrayList<>();
int index = 0;
for (GroupbyNode groupbyNode: firstStageDistinctNode.getSubPlans()) {
List<SortSpecProto> sortSpecs = new ArrayList<>();
for (Column column: groupbyNode.getGroupingColumns()) {
sortSpecs.add(SortSpecProto.newBuilder().setColumn(column.getProto()).build());
}
sortSpecArrays.add( SortSpecArray.newBuilder()
.setNodeId(thirdStageDistinctNode.getSubPlans().get(index).getPID())
.addAllSortSpecs(sortSpecs).build());
}
thirdStageBlock.getEnforcer().enforceDistinctAggregation(thirdStageDistinctNode.getPID(),
true, MultipleAggregationStage.THRID_STAGE,
DistinctAggregationAlgorithm.SORT_AGGREGATION, sortSpecArrays);
}
private ExecutionBlock buildDistinctGroupbyAndUnionPlan(MasterPlan masterPlan, ExecutionBlock lastBlock,
DistinctGroupbyNode firstPhaseGroupBy,
DistinctGroupbyNode secondPhaseGroupBy) throws TajoException {
DataChannel lastDataChannel = null;
// It pushes down the first phase group-by operator into all child blocks.
//
// (second phase) G (currentBlock)
// /|\
// / / | \
// (first phase) G G G G (child block)
// They are already connected one another.
// So, we don't need to connect them again.
for (DataChannel dataChannel : masterPlan.getIncomingChannels(lastBlock.getId())) {
if (firstPhaseGroupBy.isEmptyGrouping()) {
dataChannel.setShuffle(HASH_SHUFFLE, firstPhaseGroupBy.getGroupingColumns(), 1);
} else {
dataChannel.setShuffle(HASH_SHUFFLE, firstPhaseGroupBy.getGroupingColumns(), 32);
}
dataChannel.setSchema(firstPhaseGroupBy.getOutSchema());
ExecutionBlock childBlock = masterPlan.getExecBlock(dataChannel.getSrcId());
// Why must firstPhaseGroupby be copied?
//
// A groupby in each execution block can have different child.
// It affects groupby's input schema.
DistinctGroupbyNode firstPhaseGroupbyCopy = PlannerUtil.clone(masterPlan.getLogicalPlan(), firstPhaseGroupBy);
firstPhaseGroupbyCopy.setChild(childBlock.getPlan());
childBlock.setPlan(firstPhaseGroupbyCopy);
// just keep the last data channel.
lastDataChannel = dataChannel;
}
ScanNode scanNode = GlobalPlanner.buildInputExecutor(masterPlan.getLogicalPlan(), lastDataChannel);
secondPhaseGroupBy.setChild(scanNode);
lastBlock.setPlan(secondPhaseGroupBy);
return lastBlock;
}
static class DistinctGroupbyNodeBuildInfo {
private GroupbyNode groupbyNode;
private List<AggregationFunctionCallEval> aggFunctions = new ArrayList<>();
private List<Target> aggFunctionTargets = new ArrayList<>();
public DistinctGroupbyNodeBuildInfo(GroupbyNode groupbyNode) {
this.groupbyNode = groupbyNode;
}
public GroupbyNode getGroupbyNode() {
return groupbyNode;
}
public List<AggregationFunctionCallEval> getAggFunctions() {
return aggFunctions;
}
public List<Target> getAggFunctionTargets() {
return aggFunctionTargets;
}
public void addAggFunction(AggregationFunctionCallEval aggFunction) {
this.aggFunctions.add(aggFunction);
}
public void addAggFunctionTarget(Target target) {
this.aggFunctionTargets.add(target);
}
}
}
|
googleapis/google-cloud-java | 36,360 | java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/GetIamPolicyRegionInstantSnapshotRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.compute.v1;
/**
*
*
* <pre>
* A request message for RegionInstantSnapshots.GetIamPolicy. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest}
*/
public final class GetIamPolicyRegionInstantSnapshotRequest
extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest)
GetIamPolicyRegionInstantSnapshotRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use GetIamPolicyRegionInstantSnapshotRequest.newBuilder() to construct.
private GetIamPolicyRegionInstantSnapshotRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GetIamPolicyRegionInstantSnapshotRequest() {
project_ = "";
region_ = "";
resource_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new GetIamPolicyRegionInstantSnapshotRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetIamPolicyRegionInstantSnapshotRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetIamPolicyRegionInstantSnapshotRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest.class,
com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest.Builder.class);
}
private int bitField0_;
public static final int OPTIONS_REQUESTED_POLICY_VERSION_FIELD_NUMBER = 499220029;
private int optionsRequestedPolicyVersion_ = 0;
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @return Whether the optionsRequestedPolicyVersion field is set.
*/
@java.lang.Override
public boolean hasOptionsRequestedPolicyVersion() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @return The optionsRequestedPolicyVersion.
*/
@java.lang.Override
public int getOptionsRequestedPolicyVersion() {
return optionsRequestedPolicyVersion_;
}
public static final int PROJECT_FIELD_NUMBER = 227560217;
@SuppressWarnings("serial")
private volatile java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The project.
*/
@java.lang.Override
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for project.
*/
@java.lang.Override
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int REGION_FIELD_NUMBER = 138946292;
@SuppressWarnings("serial")
private volatile java.lang.Object region_ = "";
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The region.
*/
@java.lang.Override
public java.lang.String getRegion() {
java.lang.Object ref = region_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
region_ = s;
return s;
}
}
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for region.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRegionBytes() {
java.lang.Object ref = region_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
region_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int RESOURCE_FIELD_NUMBER = 195806222;
@SuppressWarnings("serial")
private volatile java.lang.Object resource_ = "";
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The resource.
*/
@java.lang.Override
public java.lang.String getResource() {
java.lang.Object ref = resource_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resource_ = s;
return s;
}
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for resource.
*/
@java.lang.Override
public com.google.protobuf.ByteString getResourceBytes() {
java.lang.Object ref = resource_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resource_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(region_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 138946292, region_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resource_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 195806222, resource_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeInt32(499220029, optionsRequestedPolicyVersion_);
}
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(region_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(138946292, region_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resource_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(195806222, resource_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size +=
com.google.protobuf.CodedOutputStream.computeInt32Size(
499220029, optionsRequestedPolicyVersion_);
}
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.GetIamPolicyRegionInstantSnapshotRequest)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest other =
(com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest) obj;
if (hasOptionsRequestedPolicyVersion() != other.hasOptionsRequestedPolicyVersion())
return false;
if (hasOptionsRequestedPolicyVersion()) {
if (getOptionsRequestedPolicyVersion() != other.getOptionsRequestedPolicyVersion())
return false;
}
if (!getProject().equals(other.getProject())) return false;
if (!getRegion().equals(other.getRegion())) return false;
if (!getResource().equals(other.getResource())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasOptionsRequestedPolicyVersion()) {
hash = (37 * hash) + OPTIONS_REQUESTED_POLICY_VERSION_FIELD_NUMBER;
hash = (53 * hash) + getOptionsRequestedPolicyVersion();
}
hash = (37 * hash) + PROJECT_FIELD_NUMBER;
hash = (53 * hash) + getProject().hashCode();
hash = (37 * hash) + REGION_FIELD_NUMBER;
hash = (53 * hash) + getRegion().hashCode();
hash = (37 * hash) + RESOURCE_FIELD_NUMBER;
hash = (53 * hash) + getResource().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest 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.GetIamPolicyRegionInstantSnapshotRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest 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.GetIamPolicyRegionInstantSnapshotRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest 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.GetIamPolicyRegionInstantSnapshotRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest 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.GetIamPolicyRegionInstantSnapshotRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest
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.GetIamPolicyRegionInstantSnapshotRequest 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.GetIamPolicyRegionInstantSnapshotRequest 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.GetIamPolicyRegionInstantSnapshotRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* A request message for RegionInstantSnapshots.GetIamPolicy. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest)
com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetIamPolicyRegionInstantSnapshotRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetIamPolicyRegionInstantSnapshotRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest.class,
com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest.Builder.class);
}
// Construct using
// com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
optionsRequestedPolicyVersion_ = 0;
project_ = "";
region_ = "";
resource_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetIamPolicyRegionInstantSnapshotRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest
getDefaultInstanceForType() {
return com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest build() {
com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest buildPartial() {
com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest result =
new com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.optionsRequestedPolicyVersion_ = optionsRequestedPolicyVersion_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.project_ = project_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.region_ = region_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.resource_ = resource_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest) {
return mergeFrom(
(com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest other) {
if (other
== com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest
.getDefaultInstance()) return this;
if (other.hasOptionsRequestedPolicyVersion()) {
setOptionsRequestedPolicyVersion(other.getOptionsRequestedPolicyVersion());
}
if (!other.getProject().isEmpty()) {
project_ = other.project_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getRegion().isEmpty()) {
region_ = other.region_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getResource().isEmpty()) {
resource_ = other.resource_;
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 1111570338:
{
region_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 1111570338
case 1566449778:
{
resource_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 1566449778
case 1820481738:
{
project_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 1820481738
case -301207064:
{
optionsRequestedPolicyVersion_ = input.readInt32();
bitField0_ |= 0x00000001;
break;
} // case -301207064
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 optionsRequestedPolicyVersion_;
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @return Whether the optionsRequestedPolicyVersion field is set.
*/
@java.lang.Override
public boolean hasOptionsRequestedPolicyVersion() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @return The optionsRequestedPolicyVersion.
*/
@java.lang.Override
public int getOptionsRequestedPolicyVersion() {
return optionsRequestedPolicyVersion_;
}
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @param value The optionsRequestedPolicyVersion to set.
* @return This builder for chaining.
*/
public Builder setOptionsRequestedPolicyVersion(int value) {
optionsRequestedPolicyVersion_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @return This builder for chaining.
*/
public Builder clearOptionsRequestedPolicyVersion() {
bitField0_ = (bitField0_ & ~0x00000001);
optionsRequestedPolicyVersion_ = 0;
onChanged();
return this;
}
private java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The project.
*/
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for project.
*/
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The project to set.
* @return This builder for chaining.
*/
public Builder setProject(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
project_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearProject() {
project_ = getDefaultInstance().getProject();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for project to set.
* @return This builder for chaining.
*/
public Builder setProjectBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
project_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object region_ = "";
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The region.
*/
public java.lang.String getRegion() {
java.lang.Object ref = region_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
region_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for region.
*/
public com.google.protobuf.ByteString getRegionBytes() {
java.lang.Object ref = region_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
region_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The region to set.
* @return This builder for chaining.
*/
public Builder setRegion(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
region_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearRegion() {
region_ = getDefaultInstance().getRegion();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for region to set.
* @return This builder for chaining.
*/
public Builder setRegionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
region_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object resource_ = "";
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The resource.
*/
public java.lang.String getResource() {
java.lang.Object ref = resource_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resource_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for resource.
*/
public com.google.protobuf.ByteString getResourceBytes() {
java.lang.Object ref = resource_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resource_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The resource to set.
* @return This builder for chaining.
*/
public Builder setResource(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
resource_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearResource() {
resource_ = getDefaultInstance().getResource();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for resource to set.
* @return This builder for chaining.
*/
public Builder setResourceBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
resource_ = value;
bitField0_ |= 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.compute.v1.GetIamPolicyRegionInstantSnapshotRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest)
private static final com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest();
}
public static com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GetIamPolicyRegionInstantSnapshotRequest> PARSER =
new com.google.protobuf.AbstractParser<GetIamPolicyRegionInstantSnapshotRequest>() {
@java.lang.Override
public GetIamPolicyRegionInstantSnapshotRequest 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<GetIamPolicyRegionInstantSnapshotRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GetIamPolicyRegionInstantSnapshotRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.GetIamPolicyRegionInstantSnapshotRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/incubator-kie-drools | 36,666 | kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/mcdc/MCDCAnalyser.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.kie.dmn.validation.dtanalysis.mcdc;
import java.math.BigDecimal;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.kie.dmn.feel.runtime.Range.RangeBoundary;
import org.kie.dmn.model.api.DecisionTable;
import org.kie.dmn.model.api.HitPolicy;
import org.kie.dmn.validation.dtanalysis.model.Bound;
import org.kie.dmn.validation.dtanalysis.model.DDTAInputEntry;
import org.kie.dmn.validation.dtanalysis.model.DDTARule;
import org.kie.dmn.validation.dtanalysis.model.DDTATable;
import org.kie.dmn.validation.dtanalysis.model.Interval;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MCDCAnalyser {
private static final Logger LOG = LoggerFactory.getLogger(MCDCAnalyser.class);
private final DDTATable ddtaTable;
private final DecisionTable dt;
private Optional<Integer> elseRuleIdx = Optional.empty();
private List<List<?>> allEnumValues = new ArrayList<>();
private List<PosNegBlock> selectedBlocks = new ArrayList<>();
public MCDCAnalyser(DDTATable ddtaTable, DecisionTable dt) {
this.ddtaTable = ddtaTable;
this.dt = dt;
}
public List<PosNegBlock> compute() {
if (dt.getHitPolicy() != HitPolicy.UNIQUE && dt.getHitPolicy() != HitPolicy.ANY && dt.getHitPolicy() != HitPolicy.PRIORITY) {
return Collections.emptyList(); // cannot analyse.
}
if (!ddtaTable.getColIDsStringWithoutEnum().isEmpty()) {
return Collections.emptyList(); // if not enumerated output values, cannot analyse.
}
// Step1
calculateElseRuleIdx();
calculateAllEnumValues();
// Step2, 3
int i = 1;
while (areInputsYetToBeVisited()) {
LOG.debug("=== Step23, iteration {}", i);
step23();
i++;
}
while (!step4whichOutputYetToVisit().isEmpty()) {
step4();
}
LOG.info("The final results are as follows. (marked with R the 'red color' records which are duplicates, changing input is marked with * sign)");
LOG.info("Left Hand Side for Positive:");
Set<Record> mcdcRecords = new LinkedHashSet<>();
// cycle positive side first
for (PosNegBlock b : selectedBlocks) {
boolean add = mcdcRecords.add(b.posRecord);
if (add) {
LOG.info("+ {}", b.posRecord.toString(b.cMarker));
} else {
LOG.info("R {}", b.posRecord.toString(b.cMarker));
}
}
// cycle negative side
LOG.info("Right Hand Side for Negative:");
for (PosNegBlock b : selectedBlocks) {
for (Record negRecord : b.negRecords) {
boolean add = mcdcRecords.add(negRecord);
if (add) {
LOG.info("- {}", negRecord);
} else {
LOG.info("R {}", negRecord);
}
}
LOG.info(" ");
}
LOG.info("total of cases: {}", mcdcRecords.size());
return selectedBlocks;
}
private void step4() {
Set<List<Comparable<?>>> outYetToVisit = step4whichOutputYetToVisit();
Optional<List<Comparable<?>>> findFirst = outYetToVisit.stream().findFirst();
if (findFirst.isEmpty()) {
throw new IllegalArgumentException("step4 was invoked despite there are no longer output to visit.");
}
List<Comparable<?>> pickOutToVisit = findFirst.get();
List<Integer> rules = new ArrayList<>();
for (int ruleIdx = 0; ruleIdx < ddtaTable.getRule().size(); ruleIdx++) {
if (ddtaTable.getRule().get(ruleIdx).getOutputEntry().equals(pickOutToVisit)) {
rules.add(ruleIdx);
}
}
LOG.trace("rules {}", rules);
List<Entry<PosNegBlock, Integer>> blocks = new ArrayList<>();
for (int ruleIdx : rules) {
List<Object[]> valuesForRule = negBlockValuesForRule(ruleIdx);
if (valuesForRule.isEmpty()) {
LOG.debug("step4, while looking for candidate values for rule {} I could NOT re-use from a negative case, computing new set.", ruleIdx);
Object[] posCandidate = findValuesForRule(ruleIdx, Collections.unmodifiableList(allEnumValues));
if (Stream.of(posCandidate).anyMatch(x -> x == null)) {
throw new IllegalStateException();
}
valuesForRule.add(posCandidate);
}
for (Object[] posCandidate : valuesForRule) {
LOG.trace("ruleIdx {} values {}", ruleIdx + 1, posCandidate);
Record posCandidateRecord = new Record(ruleIdx, posCandidate, ddtaTable.getRule().get(ruleIdx).getOutputEntry());
for (int chgInput = 0; chgInput < ddtaTable.getInputs().size(); chgInput++) {
Optional<PosNegBlock> calculatePosNegBlock = calculatePosNegBlock(chgInput, posCandidate[chgInput], posCandidateRecord, Collections.unmodifiableList(allEnumValues));
if (calculatePosNegBlock.isPresent()) {
PosNegBlock posNegBlock = calculatePosNegBlock.get();
int w = computeAdditionalWeightIntroBlock(posNegBlock);
LOG.trace("{} weight: {}", posNegBlock, w);
blocks.add(new SimpleEntry<>(posNegBlock, w));
}
}
}
}
Optional<PosNegBlock> posNegBlockFirst = blocks.stream().sorted(Entry.comparingByValue()).map(Entry::getKey).findFirst();
if (posNegBlockFirst.isEmpty()) {
throw new IllegalStateException("there is no candidable posNegBlocks.");
}
PosNegBlock posNegBlock = posNegBlockFirst.get();
LOG.trace("step4 selecting block: \n{}", posNegBlock);
selectBlock(posNegBlock);
}
private Set<List<Comparable<?>>> step4whichOutputYetToVisit() {
Set<List<Comparable<?>>> outYetToVisit = ddtaTable.getRule().stream().map(r -> r.getOutputEntry()).collect(Collectors.toSet());
outYetToVisit.removeAll(getVisitedPositiveOutput());
LOG.trace("outYetToVisit {}", outYetToVisit);
if (outYetToVisit.size() > 1 && elseRuleIdx.isPresent() && outYetToVisit.contains(ddtaTable.getRule().get(elseRuleIdx.get()).getOutputEntry())) {
LOG.trace("outYetToVisit will be filtered of the Else rule's output {}.", ddtaTable.getRule().get(elseRuleIdx.get()).getOutputEntry());
outYetToVisit.remove(ddtaTable.getRule().get(elseRuleIdx.get()).getOutputEntry());
LOG.trace("outYetToVisit {}", outYetToVisit);
}
return outYetToVisit;
}
private List<Object[]> negBlockValuesForRule(int ruleIdx) {
List<Object[]> result = new ArrayList<>();
for (PosNegBlock b : selectedBlocks) {
for (Record nr : b.negRecords) {
if (nr.ruleIdx == ruleIdx) {
result.add(nr.enums);
}
}
}
return result;
}
private boolean areInputsYetToBeVisited() {
List<Integer> idx = getAllColumnIndexes();
idx.removeAll(getAllColumnVisited());
return idx.size() > 0;
}
private void step23() {
LOG.debug("step23() ------------------------------");
List<Integer> visitedIndexes = getAllColumnVisited();
LOG.debug("Visited Inputs: {}", debugListPlusOne(visitedIndexes));
List<List<Comparable<?>>> visitedPositiveOutput = getVisitedPositiveOutput();
LOG.debug("Visited positive Outputs: {}", visitedPositiveOutput);
debugAllEnumValues();
List<Integer> allIndexes = getAllColumnIndexes();
allIndexes.removeAll(visitedIndexes);
LOG.debug("Inputs yet to be analysed: {}", debugListPlusOne(allIndexes));
List<Integer> idxMoreEnums = whichIndexHasMoreEnums(allIndexes);
LOG.debug("2.a Pick the input with greatest number of enum values {} ? it's: {}",
debugListPlusOne(allIndexes),
debugListPlusOne(idxMoreEnums));
Integer idxMostMatchingRules = idxMoreEnums.stream()
.map(i -> new SimpleEntry<Integer, Integer>(i, matchingRulesForInput(i, allEnumValues.get(i).get(0)).size()))
.max(Entry.comparingByValue())
.map(Entry::getKey)
.orElseThrow(() -> new RuntimeException());
LOG.debug("2.b Choose the input with the greatest number of rules matching that enum {} ? it's: {}",
idxMoreEnums.stream()
.map(i -> new SimpleEntry<Integer, Integer>(i, matchingRulesForInput(i, allEnumValues.get(i).get(0)).size()))
.collect(Collectors.toList()),
idxMostMatchingRules + 1);
List<PosNegBlock> candidateBlocks = new ArrayList<>();
Object value = allEnumValues.get(idxMostMatchingRules).get(0);
List<Integer> matchingRulesForInput = matchingRulesForInput(idxMostMatchingRules, value);
for (int ruleIdx : matchingRulesForInput) {
Object[] knownValues = new Object[ddtaTable.getInputs().size()];
knownValues[idxMostMatchingRules] = value;
List<Object[]> valuesForRule = combinatorialValuesForRule(ruleIdx, knownValues, Collections.unmodifiableList(allEnumValues));
for (Object[] posCandidate : valuesForRule) {
LOG.trace("ruleIdx {} values {}", ruleIdx + 1, posCandidate);
if (Stream.of(posCandidate).anyMatch(x -> x == null)) {
continue;
}
List<Integer> ruleIndexesMatchingValues = ruleIndexesMatchingValues(posCandidate);
if (!ruleIndexesMatchingValues.remove((Integer) ruleIdx)) {
continue; // the posCandidate is actually matching another rule (in priorities)
}
if (ruleIndexesMatchingValues.size() > 0) {
LOG.debug("Skipping posCandidate {} as it could also match rules {}, besides the one currently under calculus {}", posCandidate, ruleIndexesMatchingValues, ruleIdx);
continue;
}
Record posCandidateRecord = new Record(ruleIdx, posCandidate, ddtaTable.getRule().get(ruleIdx).getOutputEntry());
Optional<PosNegBlock> calculatePosNegBlock = calculatePosNegBlock(idxMostMatchingRules, value, posCandidateRecord, Collections.unmodifiableList(allEnumValues));
if (calculatePosNegBlock.isPresent()) {
candidateBlocks.add(calculatePosNegBlock.get());
}
}
}
LOG.trace("3. Input {}, initial candidate blocks \n{}", idxMostMatchingRules + 1, candidateBlocks);
Set<List<Comparable<?>>> filter1outs = candidateBlocks.stream().map(b -> b.posRecord.output).collect(Collectors.toSet());
LOG.trace("filter1outs {}", filter1outs);
if (filter1outs.stream().anyMatch(not(getVisitedPositiveOutput()::contains))) {
LOG.trace("Trying to prioritize non-yet visited outputs...");
Set<List<Comparable<?>>> hypo = new HashSet<>(filter1outs);
hypo.removeAll(getVisitedPositiveOutput());
if (elseRuleIdx.isPresent() && hypo.size() == 1 && hypo.iterator().next().equals(ddtaTable.getRule().get(elseRuleIdx.get()).getOutputEntry())) {
LOG.trace("...won't be prioritizing non-yet visited outputs, otherwise I would prioritize the Else rules.");
} else {
filter1outs.removeAll(getVisitedPositiveOutput());
LOG.trace("I recomputed filter1outs to prioritize non-yet visited outputs {}", filter1outs);
}
}
if (filter1outs.size() > 1 && elseRuleIdx.isPresent() && filter1outs.contains(ddtaTable.getRule().get(elseRuleIdx.get()).getOutputEntry())) {
LOG.trace("filter1outs will be filtered of the Else rule's output {}.", ddtaTable.getRule().get(elseRuleIdx.get()).getOutputEntry());
filter1outs.remove(ddtaTable.getRule().get(elseRuleIdx.get()).getOutputEntry());
LOG.trace("filter1outs {}", filter1outs);
}
List<SimpleEntry<List<Comparable<?>>, Integer>> filter1outsMatchingRules = filter1outs.stream()
.map(out -> new SimpleEntry<>(out, (int) ddtaTable.getRule().stream().filter(r -> r.getOutputEntry().equals(out)).count()))
.sorted(Entry.comparingByValue())
.collect(Collectors.toList());
LOG.trace("3. of those blocks positive outputs, how many rule do they match? {}", filter1outsMatchingRules);
List<Comparable<?>> filter1outWithLessMatchingRules = filter1outsMatchingRules.get(0).getKey();
LOG.trace("3. positive output of those block with the less matching rules? {}", filter1outWithLessMatchingRules);
List<PosNegBlock> filter2 = candidateBlocks.stream().filter(b -> b.posRecord.output.equals(filter1outWithLessMatchingRules)).collect(Collectors.toList());
LOG.trace("3.FILTER-2 blocks with output corresponding to the less matching rules {}, the blocks are: \n{}", filter1outWithLessMatchingRules, filter2);
List<SimpleEntry<PosNegBlock, Integer>> blockWeighted = filter2.stream()
.map(b -> new SimpleEntry<>(b, computeAdditionalWeightIntroBlock(b)))
.sorted(Entry.comparingByValue())
.collect(Collectors.toList());
LOG.trace("3. blocks sorted by fewest new cases (natural weight order): \n{}", blockWeighted);
PosNegBlock selectedBlock = blockWeighted.get(0).getKey();
LOG.trace("3. I select the first, chosen block to be select: \n{}", selectedBlock);
selectBlock(selectedBlock);
}
/**
* JDK-11 polyfill
*/
public static <T> Predicate<T> not(Predicate<T> t) {
return t.negate();
}
private int computeAdditionalWeightIntroBlock(PosNegBlock newBlock) {
int score = 0;
Record posRecord = newBlock.posRecord;
if (selectedBlocks.stream().noneMatch(vb -> vb.posRecord.equals(posRecord))) {
score++;
}
for (Record negRecord : newBlock.negRecords) {
if (selectedBlocks.stream().flatMap(vb -> vb.negRecords.stream()).noneMatch(nr -> nr.equals(negRecord))) {
score++;
}
}
return score;
}
private void selectBlock(PosNegBlock selected) {
selectedBlocks.add(selected);
// int index = selected.cMarker;
// allEnumValues.get(index).removeAll(Arrays.asList(selected.posRecord.enums[index]));
}
private List<List<Comparable<?>>> getVisitedPositiveOutput() {
return selectedBlocks.stream().map(b -> b.posRecord.output).collect(Collectors.toList());
}
private List<Integer> getAllColumnVisited() {
return selectedBlocks.stream().map(b -> b.cMarker).collect(Collectors.toList());
}
private List<Integer> getAllColumnIndexes() {
return IntStream.range(0, ddtaTable.getInputs().size()).boxed().collect(Collectors.toList());
}
private List<Integer> debugListPlusOne(List<Integer> input) {
return input.stream().map(x -> x + 1).collect(Collectors.toList());
}
private List<Integer> whichIndexHasMoreEnums(List<Integer> allIndexes) {
Map<Integer, List<?>> byIndex = new HashMap<>();
for (Integer idx : allIndexes) {
byIndex.put(idx, allEnumValues.get(idx));
}
Integer max = byIndex.values().stream().map(List::size).max(Integer::compareTo).orElse(0);
List<Integer> collect = byIndex.entrySet().stream().filter(kv -> kv.getValue().size() == max).map(Entry::getKey).collect(Collectors.toList());
return collect;
}
private Optional<PosNegBlock> calculatePosNegBlock(Integer idx, Object value, Record posCandidate, List<List<?>> allEnumValues) {
List<Comparable<?>> posOutput = posCandidate.output;
List<?> enumValues = allEnumValues.get(idx);
List<?> allOtherEnumValues = new ArrayList<>(enumValues);
allOtherEnumValues.remove(value);
List<Record> negativeRecords = new ArrayList<>();
for (Object otherEnumValue : allOtherEnumValues) {
Object[] negCandidate = Arrays.copyOf(posCandidate.enums, posCandidate.enums.length);
negCandidate[idx] = otherEnumValue;
Record negRecordForNegCandidate = null;
for (int i = 0; negRecordForNegCandidate == null && i < ddtaTable.getRule().size(); i++) {
DDTARule rule = ddtaTable.getRule().get(i);
boolean ruleMatches = ruleMatches(rule, negCandidate);
if (ruleMatches) {
negRecordForNegCandidate = new Record(i, negCandidate, rule.getOutputEntry());
}
}
if (negRecordForNegCandidate != null) {
negativeRecords.add(negRecordForNegCandidate);
}
}
boolean allNegValuesDiffer = true;
for (Record record : negativeRecords) {
allNegValuesDiffer &= !record.output.equals(posOutput);
}
if (allNegValuesDiffer) {
PosNegBlock posNegBlock = new PosNegBlock(idx, posCandidate, negativeRecords);
return Optional.of(posNegBlock);
}
LOG.trace("For In{}={} and candidate positive of {}, it cannot be a matching rule because some negative case had SAME output {}", idx + 1, value, posCandidate, negativeRecords);
return Optional.empty();
}
private static boolean ruleMatches(DDTARule rule, Object[] values) {
boolean ruleMatches = true;
for (int c = 0; ruleMatches && c < rule.getInputEntry().size(); c++) {
Object cValue = values[c];
ruleMatches &= rule.getInputEntry().get(c).getIntervals().stream().anyMatch(interval -> interval.asRangeIncludes(cValue));
}
return ruleMatches;
}
private List<Integer> ruleIndexesMatchingValues(Object[] values) {
List<Integer> ruleIndexes = new ArrayList<>();
for (int i = 0; i < ddtaTable.getRule().size(); i++) {
DDTARule rule = ddtaTable.getRule().get(i);
if (ruleMatches(rule, values)) {
ruleIndexes.add(i);
}
}
if (dt.getHitPolicy() == HitPolicy.PRIORITY) {
List<List<Comparable<?>>> outputs = new ArrayList<>();
for (Integer ruleIdx : ruleIndexes) {
DDTARule rule = ddtaTable.getRule().get(ruleIdx);
List<Comparable<?>> ruleOutput = rule.getOutputEntry();
outputs.add(ruleOutput);
}
List<Comparable<?>> computedOutput = new ArrayList<>();
for (int i = 0; i < ddtaTable.getOutputs().size(); i++) {
List outputOrder = ddtaTable.getOutputs().get(i).getOutputOrder();
int outputCursor = Integer.MAX_VALUE;
for (List<Comparable<?>> outs : outputs) {
Comparable<?> out = outs.get(i);
if (outputOrder.indexOf(out) < outputCursor) {
outputCursor = outputOrder.indexOf(out);
}
}
computedOutput.add((Comparable<?>) outputOrder.get(outputCursor));
}
List<Integer> pIndexes = new ArrayList<>();
for (Integer ruleIdx : ruleIndexes) {
DDTARule rule = ddtaTable.getRule().get(ruleIdx);
List<Comparable<?>> ruleOutput = rule.getOutputEntry();
if (ruleOutput.equals(computedOutput)) {
pIndexes.add(ruleIdx);
}
}
return pIndexes;
}
return ruleIndexes;
}
public static class PosNegBlock {
public final int cMarker;
public final Record posRecord;
public final List<Record> negRecords;
public PosNegBlock(int cMarker, Record posRecord, List<Record> negRecords) {
this.cMarker = cMarker;
this.posRecord = posRecord;
this.negRecords = negRecords;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("PosNeg block In ").append(cMarker + 1).append("=").append(posRecord.enums[cMarker]).append("\n");
sb.append(" + ").append(posRecord).append("\n");
for (Record negRecord : negRecords) {
sb.append(" - ").append(negRecord).append("\n");
}
return sb.toString();
}
}
public static class Record {
public final int ruleIdx;
public final Object[] enums;
public final List<Comparable<?>> output;
public Record(int ruleIdx, Object[] enums, List<Comparable<?>> output) {
this.ruleIdx = ruleIdx;
this.enums = enums;
this.output = output;
}
@Override
public String toString() {
return String.format("%2s", ruleIdx + 1) + " [" + Arrays.stream(enums).map(Object::toString).collect(Collectors.joining("; ")) + "] -> " + output;
}
public String toString(int cMarker) {
StringBuilder ts = new StringBuilder(String.format("%2s", ruleIdx + 1));
ts.append(" [");
for (int i = 0; i < enums.length; i++) {
if (i == cMarker) {
ts.append("*");
}
ts.append(enums[i]);
if (i + 1 < enums.length) {
ts.append("; ");
}
}
ts.append("] -> ").append(output);
return ts.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.deepHashCode(enums);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Record other = (Record) obj;
if (!Arrays.deepEquals(enums, other.enums))
return false;
return true;
}
}
private List<Object[]> combinatorialValuesForRule(int ruleIdx, Object[] knownValues, List<List<?>> allEnumValues) {
List<Object[]> result = new ArrayList<>();
List<DDTAInputEntry> inputEntry = ddtaTable.getRule().get(ruleIdx).getInputEntry();
List<List<?>> validEnumValues = new ArrayList<>();
for (int i = 0; i < inputEntry.size(); i++) {
List<Object> enumForI = new ArrayList<>();
if (knownValues[i] == null) {
DDTAInputEntry ddtaInputEntry = inputEntry.get(i);
List<?> enumValues = allEnumValues.get(i);
for (Object object : enumValues) {
if (ddtaInputEntry.getIntervals().stream().anyMatch(interval -> interval.asRangeIncludes(object))) {
enumForI.add(object);
}
}
} else {
enumForI.add(knownValues[i]);
}
validEnumValues.add(enumForI);
}
List<List<Object>> combinatorial = new ArrayList<>();
combinatorial.add(new ArrayList<>());
for (int i = 0; i < inputEntry.size(); i++) {
List<List<Object>> combining = new ArrayList<>();
for (List<Object> existing : combinatorial) {
for (Object enumForI : validEnumValues.get(i)) {
List<Object> building = new ArrayList<>(existing);
building.add(enumForI);
combining.add(building);
}
}
combinatorial = combining;
}
return combinatorial.stream().map(List::toArray).collect(Collectors.toList());
}
private Object[] findValuesForRule(int ruleIdx, Object[] knownValues, List<List<?>> allEnumValues) {
Object[] result = Arrays.copyOf(knownValues, knownValues.length);
List<DDTAInputEntry> inputEntry = ddtaTable.getRule().get(ruleIdx).getInputEntry();
for (int i = 0; i < inputEntry.size(); i++) {
if (result[i] == null) {
DDTAInputEntry ddtaInputEntry = inputEntry.get(i);
List<?> enumValues = allEnumValues.get(i);
Interval interval0 = ddtaInputEntry.getIntervals().get(0);
if (interval0.isSingularity()) {
result[i] = interval0.getLowerBound().getValue();
} else if (interval0.getLowerBound().getBoundaryType() == RangeBoundary.CLOSED && interval0.getLowerBound().getValue() != Interval.NEG_INF) {
result[i] = interval0.getLowerBound().getValue();
} else if (interval0.getUpperBound().getBoundaryType() == RangeBoundary.CLOSED && interval0.getUpperBound().getValue() != Interval.POS_INF) {
result[i] = interval0.getUpperBound().getValue();
}
if (!enumValues.contains(result[i])) {
result[i] = null; // invalidating if the chosen enum is not part of the plausible ones
}
if (result[i] == null) {
for (Object object : enumValues) {
if (ddtaInputEntry.getIntervals().stream().anyMatch(interval -> interval.asRangeIncludes(object))) {
result[i]= object;
break;
}
}
}
}
}
return result;
}
private Object[] findValuesForRule(int ruleIdx, List<List<?>> allEnumValues) {
Object[] result = new Object[ddtaTable.getInputs().size()];
List<DDTAInputEntry> inputEntry = ddtaTable.getRule().get(ruleIdx).getInputEntry();
for (int i = 0; i < inputEntry.size(); i++) {
if (result[i] == null) {
DDTAInputEntry ddtaInputEntry = inputEntry.get(i);
List<?> enumValues = allEnumValues.get(i);
for (Object object : enumValues) {
if (ddtaInputEntry.getIntervals().stream().anyMatch(interval -> interval.asRangeIncludes(object))) {
result[i] = object;
break;
}
}
}
}
return result;
}
private List<Integer> matchingRulesForInput(int colIdx, Object value) {
List<Integer> results = new ArrayList<>();
List<DDTARule> rules = ddtaTable.getRule();
for (int i = 0; i < rules.size(); i++) {
List<Interval> intervals = rules.get(i).getInputEntry().get(colIdx).getIntervals();
if (intervals.stream().anyMatch(interval -> interval.asRangeIncludes(value))) {
results.add(i);
}
}
LOG.trace("Considering just In{}={} in the original decision tables matches rules: {} total of {} rules.", colIdx + 1, value, debugListPlusOne(results), results.size());
return results;
}
private void calculateAllEnumValues() {
for (int idx = 0; idx < ddtaTable.inputCols(); idx++) {
if (ddtaTable.getInputs().get(idx).isDiscreteDomain()) {
List<?> discreteValues = new ArrayList<>(ddtaTable.getInputs().get(idx).getDiscreteDMNOrder());
allEnumValues.add(discreteValues); // add _the collection_
continue;
}
List<Interval> colIntervals = ddtaTable.projectOnColumnIdx(idx);
List<Bound> bounds = colIntervals.stream().flatMap(i -> Stream.of(i.getLowerBound(), i.getUpperBound())).collect(Collectors.toList());
Collections.sort(bounds);
LOG.trace("bounds (sorted) {}", bounds);
List<Object> enumValues = new ArrayList<>();
Bound<?> prevBound = bounds.remove(0);
while (bounds.size() > 0 && bounds.get(0).compareTo(prevBound) == 0) {
prevBound = bounds.remove(0); //look-ahead.
}
while (bounds.size() > 0) {
Bound<?> curBound = bounds.remove(0);
while (bounds.size() > 0 && bounds.get(0).compareTo(curBound) == 0) {
curBound = bounds.remove(0); //look-ahead.
}
LOG.trace("prev {}, cur {}", prevBound, curBound);
if (prevBound.isUpperBound() && curBound.isLowerBound()) {
// do nothing.
} else if (prevBound.isUpperBound() && curBound.isUpperBound()) {
if (curBound.getBoundaryType() == RangeBoundary.CLOSED && !isBoundInfinity(curBound)) {
enumValues.add(curBound.getValue());
} else {
LOG.trace("looking for value in-between {} {} ", prevBound, curBound);
enumValues.add(inBetween(prevBound, curBound));
}
} else if (prevBound.isLowerBound() && curBound.isLowerBound()) {
if (prevBound.getBoundaryType() == RangeBoundary.CLOSED && !isBoundInfinity(prevBound)) {
enumValues.add(prevBound.getValue());
} else {
LOG.trace("looking for value in-between {} {} ", prevBound, curBound);
enumValues.add(inBetween(prevBound, curBound));
}
} else {
if (prevBound.getBoundaryType() == RangeBoundary.CLOSED && !isBoundInfinity(prevBound)) {
enumValues.add(prevBound.getValue());
} else if (curBound.getBoundaryType() == RangeBoundary.CLOSED && !isBoundInfinity(curBound)) {
enumValues.add(curBound.getValue());
} else {
LOG.trace("looking for value in-between {} {} ", prevBound, curBound);
enumValues.add(inBetween(prevBound, curBound));
}
}
prevBound = curBound;
while (bounds.size() > 0 && bounds.get(0).compareTo(prevBound) == 0) {
prevBound = bounds.remove(0); //look-ahead.
}
}
LOG.trace("enumValues: {}", enumValues);
allEnumValues.add(enumValues);
}
for (int in=0; in<allEnumValues.size(); in++) {
final int inIdx = in;
final List<?> inX = allEnumValues.get(in);
List<Pair> sorted = inX.stream().map(v -> new Pair((Comparable<?>) v, matchingRulesForInput(inIdx, v).size()))
.sorted()
.collect(Collectors.toList());
LOG.debug("Input {} sorted by number of matching rules: {}", inIdx + 1, sorted);
List<?> sortedByMatchingRules = sorted.stream()
.map(Pair::getKey)
.collect(Collectors.toList());
allEnumValues.set(inIdx, sortedByMatchingRules);
}
debugAllEnumValues();
}
public static class Pair implements Comparable<Pair> {
private final Comparable key;
private final int occurences;
private final Comparator<Pair> c1 = Comparator.comparing(Pair::getOccurences).reversed();
public Pair(Comparable<?> key, int occurences) {
this.key = key;
this.occurences = occurences;
}
public Comparable<?> getKey() {
return key;
}
public int getOccurences() {
return occurences;
}
@Override
public int compareTo(Pair o) {
if (c1.compare(this, o) != 0) {
return c1.compare(this, o);
} else {
return -1 * this.key.compareTo(o.key);
}
}
@Override
public String toString() {
return "{" + key + "=" + occurences + "}";
}
}
private void debugAllEnumValues() {
LOG.debug("allEnumValues:");
for (int idx = 0; idx < allEnumValues.size(); idx++) {
LOG.debug("allEnumValues In{}= {}", idx + 1, allEnumValues.get(idx));
}
}
private void calculateElseRuleIdx() {
if (dt.getHitPolicy() == HitPolicy.PRIORITY) {// calculate "else" rule if present.
for (int ruleIdx = ddtaTable.getRule().size() - 1; ruleIdx>=0 && elseRuleIdx.isEmpty(); ruleIdx--) {
DDTARule rule = ddtaTable.getRule().get(ruleIdx);
List<DDTAInputEntry> ie = rule.getInputEntry();
boolean checkAll = true;
for (int colIdx = 0; colIdx < ie.size() && checkAll; colIdx++) {
DDTAInputEntry ieIDX = ie.get(colIdx);
boolean idIDXsize1 = ieIDX.getIntervals().size() == 1;
Interval ieIDXint0 = ieIDX.getIntervals().get(0);
Interval domainMinMax = ddtaTable.getInputs().get(colIdx).getDomainMinMax();
boolean equals = ieIDXint0.equals(domainMinMax);
checkAll &= idIDXsize1 && equals;
}
if (checkAll) {
LOG.debug("I believe P table with else rule: {}", ruleIdx + 1);
elseRuleIdx = Optional.of(ruleIdx);
}
}
}
}
private Object inBetween(Bound a, Bound b) {
if (a.getValue() instanceof BigDecimal || b.getValue() instanceof BigDecimal) {
BigDecimal aValue = a.getValue() == Interval.NEG_INF ? ((BigDecimal) b.getValue()).add(new BigDecimal(-2)) : (BigDecimal) a.getValue();
BigDecimal bValue = b.getValue() == Interval.POS_INF ? ((BigDecimal) a.getValue()).add(new BigDecimal(+2)) : (BigDecimal) b.getValue();
BigDecimal guessWork = new BigDecimal(aValue.intValue() + 1);
if (bValue.compareTo(guessWork) > 0) {
return guessWork;
} else if (bValue.compareTo(guessWork) == 0 && b.isLowerBound() && b.getBoundaryType() == RangeBoundary.OPEN) {
return guessWork;
} else {
throw new UnsupportedOperationException();
}
}
throw new UnsupportedOperationException();
}
private boolean isBoundInfinity(Bound b) {
return b.getValue() == Interval.NEG_INF || b.getValue() == Interval.POS_INF;
}
}
|
google/sagetv | 36,363 | java/sage/EPGDataSource.java | /*
* Copyright 2015 The SageTV Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sage;
import sage.Wizard.MaintenanceType;
import java.util.List;
public class EPGDataSource
{
public static final long MILLIS_PER_HOUR = 1000L * 60L * 60L;
protected static final String PROVIDER_ID = "provider_id";
protected static final String ENABLED = "enabled";
protected static final String LAST_RUN = "last_run";
protected static final String EXPANDED_UNTIL = "expanded_until";
protected static final String EPG_NAME = "epg_name";
protected static final String DUMP_DIR = "dump_dir";
protected static final String UNAVAILABLE_STATIONS = "unavailable_stations";
protected static final String UNAVAILABLE_CHANNEL_NUMS = "unavailable_channel_nums";
protected static final String APPLIED_SERVICE_LEVEL = "applied_service_level";
protected static final String CHAN_DOWNLOAD_COMPLETE = "chan_download_complete";
protected static final String SERVER_UPDATE_ID = "server_update_id";
protected static final String DISABLE_DATA_SCANNING = "disable_data_scanning";
protected static final String EPG_DATA_SCAN_PERIOD = "epg_data_scan_period";
protected static final long CONFIRMATION_AHEAD_TIME = 24*MILLIS_PER_HOUR;
private static long GPS_OFFSET;
private static final java.text.DateFormat utcDateFormat = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
private static final java.text.DateFormat localDateFormat = new java.text.SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
static
{
// start time (GPS time), 0 is at Jan 6, 1980
java.util.GregorianCalendar gcal = new java.util.GregorianCalendar(1980, java.util.Calendar.JANUARY, 6, 0, 0, 0);
gcal.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
GPS_OFFSET = gcal.getTimeInMillis();
utcDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
}
public EPGDataSource(int inEPGSourceID)
{
wiz = Wizard.getInstance();
epgSourceID = inEPGSourceID;
//Wizard.getInstance().notifyOfID(epgSourceID);
prefsRoot = EPG.EPG_DATA_SOURCES_KEY + '/' + epgSourceID + '/';
lastRun = Sage.getLong(prefsRoot + LAST_RUN, 0);
expandedUntil = Sage.getLong(prefsRoot + EXPANDED_UNTIL, 0);
providerID = Sage.getLong(prefsRoot + PROVIDER_ID, 0);
enabled = Sage.getBoolean(prefsRoot + ENABLED, true);
name = Sage.get(prefsRoot + EPG_NAME, "Undefined Source Name");
Sage.put(prefsRoot + EPG.EPG_CLASS, "Basic");
unavailStations = Sage.parseCommaDelimIntSet(Sage.get(prefsRoot + UNAVAILABLE_STATIONS, ""));
unavailChanNums = Sage.parseCommaDelimSet(Sage.get(prefsRoot + UNAVAILABLE_CHANNEL_NUMS, ""));
appliedServiceLevel = Sage.getInt(prefsRoot + APPLIED_SERVICE_LEVEL, 0);
chanDownloadComplete = Sage.getBoolean(prefsRoot + CHAN_DOWNLOAD_COMPLETE, false);
dataScanAllowed = !Sage.getBoolean(prefsRoot + DISABLE_DATA_SCANNING, false);
dumpDir = Sage.get(prefsRoot + DUMP_DIR, null);
if (dumpDir != null)
{
new java.io.File(dumpDir).mkdirs();
}
updateIDMap = java.util.Collections.synchronizedMap(new java.util.HashMap());
String updateStr = Sage.get(prefsRoot + SERVER_UPDATE_ID, "");
java.util.StringTokenizer toker = new java.util.StringTokenizer(updateStr, ";");
while (toker.hasMoreTokens())
{
String toke = toker.nextToken();
int idx = toke.indexOf(',');
if (idx != -1)
{
try
{
updateIDMap.put(new Integer(toke.substring(0, idx)), new Long(toke.substring(idx + 1)));
}
catch (Exception e)
{}
}
}
}
public boolean doesStationIDWantScan(int statID)
{
// These are the station IDs we assign ourselves in the channel scan. Exclude the ones that map to default channels and
// also ones that map to tribune station IDs
return statID > 0 && statID < 10000 && dataScanAllowed;
}
public boolean initDataScanInfo()
{
if (Sage.client || !dataScanAllowed) return false;
// Get our CDI and find out if it does data scans, and if it does then sync our update times with when
// we're expanded until so the EPG will tell us to update when the next scan can be done
CaptureDeviceInput[] cdis = MMC.getInstance().getInputsForProvider(providerID);
scannedUntil = Long.MAX_VALUE;
if (cdis.length > 0 && cdis[0].doesDataScanning())
{
int[] allStations = EPG.getInstance().getAllStations(providerID);
for (int i = 0; i < allStations.length; i++)
{
if (canViewStation(allStations[i]) && doesStationIDWantScan(allStations[i]))
{
Long stationUpdateTime = updateIDMap.get(new Integer(allStations[i]));
if (stationUpdateTime != null)
{
scannedUntil = Math.min(stationUpdateTime.longValue(), scannedUntil);
}
else
scannedUntil = 0; // haven't scanned yet for this station!
}
}
}
if (scannedUntil <= Sage.time())
{
boolean foundOne = false;
for (int i = 0; i < cdis.length; i++)
{
if (cdis[i].getCaptureDevice().requestDataScan(cdis[i]))
foundOne = true;
}
if (foundOne)
{
dataScanRequested = true;
SeekerSelector.getInstance().kick();
}
return true;
}
else
return false;
}
protected void doDataScan()
{
long dataScanPeriod = Sage.getLong(EPG_DATA_SCAN_PERIOD, 4*Sage.MILLIS_PER_HR);
// This does the data scan if it needs to be done
CaptureDeviceInput[] cdis = MMC.getInstance().getInputsForProvider(providerID);
CaptureDeviceInput cdi = null;
boolean kickSeekNow = false;
for (int i = 0; i < cdis.length; i++)
{
if (cdi != null)
{
cdis[i].getCaptureDevice().cancelDataScanRequest(cdis[i]);
kickSeekNow = true;
}
else if (cdis[i].isActive() && cdis[i].getCaptureDevice().isDataScanning())
cdi = cdis[i];
}
if (kickSeekNow)
SeekerSelector.getInstance().kick();
if (dataScanAllowed && cdi != null && cdi.isActive() && cdi.getCaptureDevice().isDataScanning())
{
if (Sage.DBG) System.out.println("EPGDS " + name + " found a capture device to start data scanning with:" + cdi);
// Now we need to find the actual stations we want to scan for and go to it!
int[] allStations = EPG.getInstance().getAllStations(providerID);
long newScannedUntil = Long.MAX_VALUE;
java.util.Map<String, List<Integer>> majorToChannelMap = new java.util.HashMap<String, List<Integer>>();
for (int i = 0; i < allStations.length; i++)
{
if (abort || !enabled) return;
if (canViewStation(allStations[i]) && doesStationIDWantScan(allStations[i]))
{
Long stationUpdateTime = updateIDMap.get(new Integer(allStations[i]));
if (stationUpdateTime != null)
{
if (stationUpdateTime.longValue() > Sage.time())
{
newScannedUntil = Math.min(stationUpdateTime.longValue(), newScannedUntil);
continue;
}
}
String currChan = EPG.getInstance().getPhysicalChannel(providerID, allStations[i]);
java.util.StringTokenizer toker = new java.util.StringTokenizer(currChan, "-");
String majChan = currChan;
java.util.List<Integer> currStatList = null;
if (toker.countTokens() > 1)
{
if (toker.countTokens() > 2)
majChan = toker.nextToken() + "-" + toker.nextToken();
else
majChan = toker.nextToken();
}
/* else
{
// This probably isn't a digital TV channel which means it'll screw us up, so skip it
// This could also be a channel which doesn't have a major-minor identifier!!
continue;
}*/
currStatList = majorToChannelMap.get(majChan);
if (currStatList == null)
{
currStatList = new java.util.ArrayList<Integer>();
majorToChannelMap.put(majChan, currStatList);
}
currStatList.add(new Integer(allStations[i]));
}
}
java.util.Iterator<java.util.Map.Entry<String, List<Integer>>> walker = majorToChannelMap.entrySet().iterator();
while (walker.hasNext())
{
if (abort || !enabled) return;
java.util.Map.Entry<String, List<Integer>> ent = walker.next();
String currMajor = ent.getKey();
java.util.List<Integer> currStatList = ent.getValue();
// If we're here then we want to scan!
synchronized (SeekerSelector.getInstance())
{
if (cdi.getCaptureDevice().isDataScanning())
{
cdi.tuneToChannel(EPG.getInstance().getPhysicalChannel(providerID, currStatList.get(0).intValue()));
}
else // our data scanning has been stopped, so just return
return;
}
// Now we wait until we think we have all of the data for this channel
try
{
if (Sage.DBG) System.out.println("EPGDS waiting for data scan on major channel " + currMajor + "....");
Thread.sleep(Sage.getLong("epg/data_scan_channel_dwell_new", 2*Sage.MILLIS_PER_MIN));
}
catch (Exception e)
{}
// We should do a scan for DTV data every 4 hours, so mark it as done for the next 4 hours
// But round this up to the next hour so we don't do a bunch of incremental scans
// when that timer runs out
long newval = Sage.time() + dataScanPeriod;
newval = (newval - (newval % (Sage.MILLIS_PER_HR))) + Sage.MILLIS_PER_HR;
for (int i = 0; i < currStatList.size(); i++)
{
updateIDMap.put(currStatList.get(i), new Long(newval));
}
newScannedUntil = Math.min(newval, newScannedUntil);
}
if (newScannedUntil < Long.MAX_VALUE)
{
saveUpdateMap();
scannedUntil = newScannedUntil;
}
for (int i = 0; i < cdis.length; i++)
cdis[i].getCaptureDevice().cancelDataScanRequest(cdis[i]);
dataScanRequested = false;
SeekerSelector.getInstance().kick();
}
}
public void processEPGDataMsg(sage.msg.SageMsg msg)
{
if (!dataScanAllowed) return;
/*
* The EPG message data format is as follows:
* EPG-0|major-minor AN/DT|startTimeGPS|durationSeconds|language|title|description|rating|
*/
String msgString;
try
{
msgString = new String((byte[])msg.getData(), Sage.BYTE_CHARSET);
}
catch (java.io.UnsupportedEncodingException e)
{
msgString = new String((byte[])msg.getData());
}
if (((byte[])msg.getData()).length != msgString.length())
throw new InternalError("Byte array length is not the same length as string and we used a byte charset!!!");
if (msgString.length() == 0) return;
try
{
int offset = 0;
java.util.StringTokenizer toker = new java.util.StringTokenizer(msgString, "|", true);
offset += toker.nextToken().length(); // First token is "EPG-0"
offset += toker.nextToken().length(); // delimiter
String chanInfo = toker.nextToken(); // Channel number and DT or AN
offset += chanInfo.length();
String chanNum = chanInfo.substring(0, chanInfo.indexOf(' '));
int stationID = sage.EPG.getInstance().guessStationIDFromPhysicalChannel(providerID, chanNum, chanNum.indexOf('-') != -1);
if (stationID == 0)
stationID = sage.EPG.getInstance().guessStationID(providerID, chanNum);
if (stationID > 10000)
{
// It has TMS EPG data, so do NOT overwrite it with what we have found here
// For TVTV they're station IDs overlap with the generated ones so don't take anything if using their data
//if (sage.Sage.DBG) System.out.println("Skipping EPG data message because we have that channel's EPG data from a better source");
return;
}
if (stationID == 0)
{
//if (sage.Sage.DBG) System.out.println("Skipping EPG data message because we don't have a station ID for this channel");
return;
}
offset += toker.nextToken().length(); // delimiter
String timeStr = toker.nextToken();
offset += timeStr.length();
long startTime;
try
{
if (timeStr.startsWith("GPS:"))
{
startTime = Long.parseLong(timeStr.substring(4)) * 1000;
startTime += GPS_OFFSET;
// Fix issues with leap second differences between GPS & UTC time
startTime -= startTime % 60000;
}
else if (timeStr.startsWith("UTC:"))
{
startTime = utcDateFormat.parse(timeStr.substring(4)).getTime();
}
else if (timeStr.startsWith("LOCAL:"))
{
localDateFormat.setTimeZone(java.util.TimeZone.getDefault());
startTime = localDateFormat.parse(timeStr.substring(6)).getTime();
}
else
startTime = Long.parseLong(timeStr) * 1000;
}
catch (Exception e)
{
System.out.println("ERROR parsing EPG message start time of:" + e);
return;
}
offset += toker.nextToken().length(); // delimiter
String durStr = toker.nextToken();
offset += durStr.length();
int duration = Integer.parseInt(durStr); // duration
offset += toker.nextToken().length(); // delimiter
String language = toker.nextToken();
offset += language.length();
if (!"|".equals(language))
offset += toker.nextToken().length(); // delimiter
else
language = "";
if (language.length() > 0)
{
if ("eng".equalsIgnoreCase(language))
language = "English";
else if ("spa".equalsIgnoreCase(language))
language = "Spanish";
else if ("dan".equalsIgnoreCase(language))
language = "Danish";
else if ("swe".equalsIgnoreCase(language))
language = "Swedish";
else if ("fra".equalsIgnoreCase(language))
language = "French";
}
// Now we need to check for alternate character sets which means we'd need to switch to the byte arrays
String title="", description="";
for (int i = 0; i < 2 && offset < msgString.length(); i++)
{
if (msgString.charAt(offset) != '[')
{
if (i == 0)
{
title = toker.nextToken(); // title
offset += title.length();
if ("|".equals(title))
title = "";
else if (toker.hasMoreTokens())
offset += toker.nextToken().length(); // delimiter
}
else
{
description = toker.nextToken(); // description
offset += description.length();
if ("|".equals(description))
description = "";
else if (toker.hasMoreTokens())
offset += toker.nextToken().length(); // delimiter
}
}
else
{
String charset = Sage.BYTE_CHARSET;
int len = msgString.indexOf('|', offset + 1) - offset;
int fullLen = len;
int baseOffset = offset;
do
{
int brack1 = offset;
do
{
int brack2 = msgString.indexOf(']', brack1);
if (brack2 == -1)
break;
int eqIdx = msgString.indexOf('=', brack1);
if (eqIdx > brack2 || eqIdx == -1)
break;
String attName = msgString.substring(brack1 + 1, eqIdx);
String attValue = msgString.substring(eqIdx + 1, brack2);
if ("set".equals(attName))
charset = attValue;
else if ("len".equals(attName))
{
try
{
len = Integer.parseInt(attValue);
}
catch (NumberFormatException e){
if (Sage.DBG) System.out.println("Formatting error with EPG data:" + e);
}
}
offset += brack2 - offset + 1;
brack1 = msgString.indexOf('[', brack2);
} while (brack1 != -1 && brack1 < offset + len);
try
{
if (i == 0)
title += new String((byte[])msg.getData(), offset, len, charset);
else
description += new String((byte[])msg.getData(), offset, len, charset);
}
catch (java.io.UnsupportedEncodingException e)
{
if (Sage.DBG) System.out.println("Unsupported encoding for EPG data of:" + charset + " err=" + e);
if (i == 0)
title += new String((byte[])msg.getData(), offset, len);
else
description += new String((byte[])msg.getData(), offset, len);
}
//if (Sage.DBG) System.out.println("Parsing EPG data w/ charset=" + charset + " len=" + len + ((i == 0) ? (" title=" + title) : (" desc=" + description)));
offset += len + 1;
} while (baseOffset + fullLen > offset);
do
{
baseOffset += toker.nextToken().length();
} while (baseOffset < offset);
}
}
String rating = (toker.hasMoreTokens() ? toker.nextToken() : "");
byte prByte = (byte)0;
String[] ers = null;
String rated = null;
if (rating.length() > 0)
{
if (rating.indexOf("PG-13") != -1)
rated = "PG-13";
else if (rating.indexOf("NC-17") != -1)
rated = "NC-17";
// Extract the portion of interest
int pidx1 = rating.indexOf('(');
int pidx2 = rating.indexOf(')');
if (pidx1 != -1 && pidx2 > pidx1)
{
// Break down the rating information into the parts we care about.
java.util.StringTokenizer ratToker = new java.util.StringTokenizer(rating.substring(pidx1 + 1, pidx2), "-;");
if (ratToker.countTokens() > 1)
{
String tvRating = ratToker.nextToken() + ratToker.nextToken();
for (int i = 1; i < sage.Airing.PR_NAMES.length; i++)
{
if (tvRating.equalsIgnoreCase(sage.Airing.PR_NAMES[i]))
{
prByte = (byte) i;
break;
}
}
java.util.ArrayList erList = Pooler.getPooledArrayList();
while (ratToker.hasMoreTokens())
{
// Now extract the other specific rating information
String currRate = ratToker.nextToken();
if ("V".equals(currRate))
{
if (prByte == Airing.TVMA_VALUE)
erList.add("Graphic Violence");
else if (prByte == Airing.TV14_VALUE)
erList.add("Violence");
else
erList.add("Mild Violence");
}
else if ("S".equals(currRate))
{
if (prByte == Airing.TVMA_VALUE)
erList.add("Strong Sexual Content");
else if (!erList.contains("Adult Situations"))
erList.add("Adult Situations");
}
else if ("D".equals(currRate))
{
if (!erList.contains("Adult Situations"))
erList.add("Adult Situations");
if (!erList.contains("Language"))
erList.add("Language");
}
else if ("L".equals(currRate))
{
if (!erList.contains("Language"))
erList.add("Language");
}
else if (rated == null && ("G".equals(currRate) || "PG".equals(currRate) || "R".equals(currRate)))
rated = currRate;
else if (rated == null && "X".equals(currRate))
rated = "AO";
else if (rated == null && "NR".equals(currRate))
rated = "NR";
}
if (!erList.isEmpty())
ers = (String[]) erList.toArray(Pooler.EMPTY_STRING_ARRAY);
Pooler.returnPooledArrayList(erList);
}
}
}
if (!"|".equals(rating) && toker.hasMoreTokens())
toker.nextToken(); // delimiter
String category = (toker.hasMoreTokens() ? toker.nextToken() : null);
String subcategory = null;
if ("|".equals(category))
category = null;
if (category != null)
{
int idx = category.indexOf('/');
if (idx != -1)
{
subcategory = category.substring(idx + 1);
category = category.substring(0, idx);
}
}
title = title.trim();
description = description.trim();
String extID = "DT" + Math.abs((title + "-" + duration + "-" + description).hashCode());
String[] categories = new String[(category == null ? 0 : 1) + (subcategory == null ? 0 : 1)];
if (category != null)
categories[0] = category;
if (subcategory != null)
categories[1] = subcategory;
sage.Show myShow = sage.Wizard.getInstance().addShow(title, null, null, description, 0, categories, null, null, rated, ers, null, null, null,
extID, language, 0, DBObject.MEDIA_MASK_TV, (short)0, (short)0, false, (byte)0, (byte)0, (byte)0, (byte)0, (byte)0, (byte)0, (byte)0, (byte)0);
//System.out.println("Added show:" + myShow);
sage.Airing myAir = sage.Wizard.getInstance().addAiring(extID, stationID, startTime, duration*1000L, (byte)0, (byte)0, prByte,
DBObject.MEDIA_MASK_TV);
//System.out.println("Added air:" + myAir + " start=" + sage.Sage.dfFull(myAir.getStartTime()));
}
catch (RuntimeException re)
{
if (Sage.DBG) System.out.println("ERROR processing EPG data message \"" + msgString + "\" of:" + re);
if (Sage.DBG) re.printStackTrace();
}
}
public String getName()
{
return name;
}
public void setName(String s)
{
if (s == null) s = "";
name = s;
Sage.put(prefsRoot + EPG_NAME, name);
}
public final long getLastRun()
{
return lastRun;
}
public boolean usesPlugin()
{
return EPG.getInstance().hasEPGPlugin() && !Sage.getBoolean(prefsRoot + "disable_plugin", false);
}
public long getExpandedUntil()
{
return expandedUntil;
}
protected void setExpandedUntil(long x)
{
expandedUntil = x;
Sage.putLong(prefsRoot + EXPANDED_UNTIL, expandedUntil);
}
public void reset()
{
setExpandedUntil(0);
lastRun = 0;
chanDownloadComplete = false;
Sage.putLong(prefsRoot + LAST_RUN, 0);
}
public final void setEnabled(boolean x)
{
enabled = x;
Sage.putBoolean(prefsRoot + ENABLED, enabled);
}
public final boolean getEnabled()
{
return enabled;
}
public final long getProviderID()
{
return providerID;
}
public final void setProviderID(long id)
{
Sage.putLong(prefsRoot + PROVIDER_ID, providerID = id);
}
public void abortUpdate()
{
abort = true;
}
public final void clearAbort()
{
abort = false;
}
// Formerly abstract
protected boolean extractGuide(long guideTime)
{
int defaultStationID = Long.toString(providerID).hashCode();
if (defaultStationID > 0)
defaultStationID *= -1;
boolean[] didAdd = new boolean[1];
MMC mmc = MMC.getInstance();
CaptureDeviceInput cdi = mmc.getInputForProvider(providerID);
// We're no longer needed, we'll get cleaned up soon.
if (cdi == null) return true;
// Don't automatically insert the default channels for digital tuners; let them
// be found from a scan instead
if (cdi.getType() == CaptureDeviceInput.DIGITAL_TUNER_CROSSBAR_INDEX)
{
// We still need to put empty maps in there so it thinks there's actually lineup
// data for this source...and there is in the overrides.
EPG.getInstance().setLineup(providerID, new java.util.HashMap<Integer, String[]>());
EPG.getInstance().setServiceLevels(providerID, new java.util.HashMap<Integer, Integer>());
return true;
}
int minChan = cdi.getMinChannel();
int maxChan = cdi.getMaxChannel();
if ((cdi.getType() != 1 || cdi.weirdRF()) && Sage.getBoolean("epg/dont_create_full_channel_list_for_non_tuner_inputs", true))
{
// Not a tv tuner, so just set the min and max equal so it only creates a single channel
maxChan = minChan;
}
java.util.HashMap<Integer, String[]> lineMap = new java.util.HashMap<Integer, String[]>();
for (int i = minChan; i <= maxChan; i++)
{
wiz.addChannel(cdi.getCrossName(), name, null, defaultStationID + i, 0, didAdd);
if (didAdd[0])
wiz.resetAirings(defaultStationID + i);
lineMap.put(new Integer(defaultStationID + i), new String[] { Integer.toString(i) });
}
EPG.getInstance().setLineup(providerID, lineMap);
EPG.getInstance().setServiceLevels(providerID, new java.util.HashMap<Integer, Integer>());
return true;
}
public final boolean expand()
{
String arf = "expand called on " + getName() + " at " + Sage.df() +
" expandedUntil=" + Sage.df(expandedUntil) + " scannedUntil=" + Sage.df(scannedUntil);
if (Sage.DBG) System.out.println(arf);
errorText += arf + "\r\n";
if (!enabled || (getTimeTillUpdate() > 0))
{
return true;
}
else if (abort) return false;
lastRun = Sage.time();
Sage.putLong(prefsRoot + LAST_RUN, lastRun);
// Reload this info so we cna figure out who needs a scan
initDataScanInfo();
if ((getTimeTillExpand() == 0) && !abort && enabled)
{
if (Sage.DBG) System.out.println("EPG Expanding " + getName() + " at " + Sage.df());
errorText += "EPG Expanding " + getName() + " at " + Sage.df() + "\r\n";
// We're expanded into the present at least
boolean needsExpand = expandedUntil < Sage.time();
if (needsExpand)
setExpandedUntil(Math.max(Sage.time(), expandedUntil));
// Log our request for a data scan if we need one
if (dataScanAllowed && scannedUntil <= Sage.time() && !Sage.client)
{
CaptureDeviceInput[] cdis = MMC.getInstance().getInputsForProvider(providerID);
boolean foundOne = false;
for (int i = 0; i < cdis.length; i++)
{
if (cdis[i].getCaptureDevice().requestDataScan(cdis[i]))
foundOne = true;
}
if (foundOne)
{
dataScanRequested = true;
SeekerSelector.getInstance().kick();
}
}
if (Sage.client || !needsExpand || extractGuide(expandedUntil))
{
Sage.putBoolean(prefsRoot + CHAN_DOWNLOAD_COMPLETE, chanDownloadComplete = true);
if (!abort && enabled && needsExpand) setExpandedUntil(expandedUntil + getGuideWidth());
if (!abort && enabled && !Sage.client && scannedUntil <= Sage.time() && dataScanAllowed)
doDataScan();
}
else
{
if (!abort && enabled && scannedUntil <= Sage.time() && dataScanAllowed)
doDataScan();
return false;
}
}
return true;
}
// Formerly abstract
protected long getGuideWidth()
{
return Sage.MILLIS_PER_DAY;
}
// Formerly abstract
protected long getDesiredExpand()
{
return 0;
}
public final long getTimeTillUpdate()
{
return getTimeTillExpand();
}
public long getTimeTillExpand()
{
if (!enabled) return Long.MAX_VALUE;
// We only factor in the scanning time if the device is available for scanning,
// or if we haven't submitted the scan request to the device yet
if (dataScanAllowed)
{
CaptureDeviceInput[] cdis = MMC.getInstance().getInputsForProvider(providerID);
for (int i = 0; i < cdis.length; i++)
{
if ((cdis[i].isActive() && cdis[i].getCaptureDevice().isDataScanning()) || (cdis[i].doesDataScanning() && !dataScanRequested))
{
return Math.max(0, Math.min(expandedUntil - Sage.time(), scannedUntil - Sage.time()));
}
}
}
return Math.max(0, expandedUntil - Sage.time());
}
public String getErrorText()
{
return errorText;
}
protected void appendExceptionError(Throwable t)
{
java.io.StringWriter sw = new java.io.StringWriter();
java.io.PrintWriter pw = new java.io.PrintWriter(sw);
if (Sage.DBG) t.printStackTrace(pw);
pw.flush();
errorText += sw.toString();
}
public final int getEPGSourceID()
{
return epgSourceID;
}
protected String getNewErrorText()
{
if (errTextPos < errorText.length())
{
String rv = errorText.substring(errTextPos);
errTextPos = errorText.length();
return rv;
}
else return "";
}
/*public int[] getUnavailableStations()
{
int[] rv = new int[unavailStations.size()];
java.util.Iterator walker = unavailStations.iterator();
int idx = 0;
while (walker.hasNext())
rv[idx++] = ((Integer) walker.next()).intValue();
return rv;
}*/
public boolean canViewStation(int x)
{
return !unavailStations.contains(new Integer(x));
}
public boolean canViewStationOnChannel(int statID, String chanNum)
{
return !unavailStations.contains(new Integer(statID)) &&
!unavailChanNums.contains(chanNum);
}
public void setCanViewStation(int stationID, boolean good)
{
int startSize = unavailStations.size();
if (good)
unavailStations.remove(new Integer(stationID));
else
unavailStations.add(new Integer(stationID));
if (startSize != unavailStations.size())
{
Sage.put(prefsRoot + UNAVAILABLE_STATIONS, Sage.createCommaDelimSetString(unavailStations));
if (good)
setExpandedUntil(0);
synchronized (updateIDMap)
{
if (updateIDMap.keySet().removeAll(unavailStations))
{
saveUpdateMap();
}
}
NetworkClient.distributeRecursivePropertyChange(EPG.EPG_DATA_SOURCES_KEY);
EPG.getInstance().resetViewableStationsCache();
}
}
public void setCanViewStationOnChannel(int stationID, String chanNum, boolean good)
{
String[] possChans = EPG.getInstance().getChannels(providerID, stationID);
int startSize1 = unavailStations.size();
int startSize2 = unavailChanNums.size();
if (possChans.length <= 1)
{
if (good)
unavailStations.remove(new Integer(stationID));
else
unavailStations.add(new Integer(stationID));
if (possChans.length == 1)
unavailChanNums.remove(possChans[0]);
}
else if (good)
{
if (unavailStations.contains(new Integer(stationID)))
{
// All chans were bad for this station, now we're marking one of them good
unavailStations.remove(new Integer(stationID));
for (int i = 0; i < possChans.length; i++)
{
if (chanNum.equals(possChans[i]))
{
if (i != 0)
{
possChans[i] = possChans[0];
possChans[0] = chanNum;
// This changes the actual storage array, so we can just update it
EPG.getInstance().setLineup(providerID, EPG.getInstance().getLineup(providerID));
}
}
else
unavailChanNums.add(possChans[i]);
}
}
else // Just remove this one from the bad num list
unavailChanNums.remove(chanNum);
}
else
{
if (!unavailStations.contains(new Integer(stationID)) && !unavailChanNums.contains(chanNum))
{
// Not all were bad before, they may be now so check it out
int goodChanIdx = -1;
for (int i = 0; i < possChans.length; i++)
{
if (!chanNum.equals(possChans[i]) && !unavailChanNums.contains(possChans[i]))
{
goodChanIdx = i;
break;
}
}
if (goodChanIdx != -1)
{
String swap = possChans[0];
possChans[0] = possChans[goodChanIdx];
possChans[goodChanIdx] = swap;
unavailChanNums.add(chanNum);
}
else
{
for (int i = 0; i < possChans.length; i++)
unavailChanNums.remove(possChans[i]);
unavailStations.add(new Integer(stationID));
}
}
}
if (startSize1 != unavailStations.size())
{
Sage.put(prefsRoot + UNAVAILABLE_STATIONS, Sage.createCommaDelimSetString(unavailStations));
if (good)
setExpandedUntil(0);
synchronized (updateIDMap)
{
if (updateIDMap.keySet().removeAll(unavailStations))
{
saveUpdateMap();
}
}
}
if (startSize2 != unavailChanNums.size())
Sage.put(prefsRoot + UNAVAILABLE_CHANNEL_NUMS, Sage.createCommaDelimSetString(unavailChanNums));
if (startSize1 != unavailStations.size() || startSize2 != unavailChanNums.size())
{
NetworkClient.distributeRecursivePropertyChange(EPG.EPG_DATA_SOURCES_KEY);
EPG.getInstance().resetViewableStationsCache();
}
}
public void applyServiceLevel(int newLevel)
{
if (appliedServiceLevel == newLevel)
return;
java.util.Set<Integer> badStations = new java.util.HashSet<Integer>();
EPG epg = EPG.getInstance();
int[] stations = epg.getAllStations(providerID);
for (int i = 0; i < stations.length; i++)
{
if (epg.getServiceLevel(providerID, stations[i]) > newLevel)
badStations.add(new Integer(stations[i]));
}
unavailStations = badStations;
Sage.put(prefsRoot + UNAVAILABLE_STATIONS, Sage.createCommaDelimSetString(unavailStations));
Sage.putInt(prefsRoot + APPLIED_SERVICE_LEVEL, appliedServiceLevel = newLevel);
setExpandedUntil(0);
synchronized (updateIDMap)
{
if (updateIDMap.keySet().removeAll(unavailStations))
{
saveUpdateMap();
}
}
NetworkClient.distributeRecursivePropertyChange(EPG.EPG_DATA_SOURCES_KEY);
EPG.getInstance().resetViewableStationsCache();
}
protected void saveUpdateMap()
{
java.util.Iterator<java.util.Map.Entry<Integer, Long>> walker = updateIDMap.entrySet().iterator();
StringBuilder sb = new StringBuilder();
while (walker.hasNext())
{
java.util.Map.Entry ent = (java.util.Map.Entry) walker.next();
sb.append(ent.getKey());
sb.append(',');
sb.append(ent.getValue());
sb.append(';');
}
Sage.put(prefsRoot + SERVER_UPDATE_ID, sb.toString());
}
public boolean isChanDownloadComplete()
{
return chanDownloadComplete;
}
public int getAppliedServiceLevel() { return appliedServiceLevel; }
protected String prefsRoot;
protected final int epgSourceID;
protected Wizard wiz;
protected boolean enabled;
protected String errorText = "";
private int errTextPos;
protected String name;
protected boolean abort;
protected String dumpDir;
protected long providerID;
private long lastRun;
private long expandedUntil;
private long scannedUntil;
protected int appliedServiceLevel;
protected boolean chanDownloadComplete;
protected java.util.Set<Integer> unavailStations;
protected java.util.Set<String> unavailChanNums;
protected java.util.Map<Integer, Long> updateIDMap;
protected boolean dataScanAllowed;
protected boolean dataScanRequested;
/**
* Called when removing data source from the EPG
*/
public void destroySelf() {
// do nothing by default.
}
/**
* wake up this data source to perform any background updates
*/
public void kick() {
// do nothing by default
}
/*
* Get the type of Maintenance that Wizard should apply
* based on this EPG update
*/
public MaintenanceType getRequiredMaintenanceType() {
// Use the default daily timing for full maintenance.
return MaintenanceType.NONE;
}
}
|
apache/flink | 36,739 | flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.api.operators;
import org.apache.flink.annotation.Internal;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.eventtime.WatermarkAlignmentParams;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.typeutils.base.array.BytePrimitiveArraySerializer;
import org.apache.flink.api.connector.source.ReaderOutput;
import org.apache.flink.api.connector.source.RichSourceReaderContext;
import org.apache.flink.api.connector.source.SourceEvent;
import org.apache.flink.api.connector.source.SourceReader;
import org.apache.flink.api.connector.source.SourceReaderContext;
import org.apache.flink.api.connector.source.SourceSplit;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.MetricOptions;
import org.apache.flink.core.io.InputStatus;
import org.apache.flink.core.io.SimpleVersionedSerializer;
import org.apache.flink.metrics.groups.SourceReaderMetricGroup;
import org.apache.flink.runtime.event.WatermarkEvent;
import org.apache.flink.runtime.io.AvailabilityProvider;
import org.apache.flink.runtime.io.network.api.StopMode;
import org.apache.flink.runtime.metrics.groups.InternalSourceReaderMetricGroup;
import org.apache.flink.runtime.metrics.groups.InternalSourceSplitMetricGroup;
import org.apache.flink.runtime.metrics.groups.TaskIOMetricGroup;
import org.apache.flink.runtime.operators.coordination.OperatorEvent;
import org.apache.flink.runtime.operators.coordination.OperatorEventGateway;
import org.apache.flink.runtime.operators.coordination.OperatorEventHandler;
import org.apache.flink.runtime.source.event.AddSplitEvent;
import org.apache.flink.runtime.source.event.IsProcessingBacklogEvent;
import org.apache.flink.runtime.source.event.NoMoreSplitsEvent;
import org.apache.flink.runtime.source.event.ReaderRegistrationEvent;
import org.apache.flink.runtime.source.event.ReportedWatermarkEvent;
import org.apache.flink.runtime.source.event.RequestSplitEvent;
import org.apache.flink.runtime.source.event.SourceEventWrapper;
import org.apache.flink.runtime.source.event.WatermarkAlignmentEvent;
import org.apache.flink.runtime.state.StateInitializationContext;
import org.apache.flink.runtime.state.StateSnapshotContext;
import org.apache.flink.streaming.api.graph.StreamConfig;
import org.apache.flink.streaming.api.operators.source.TimestampsAndWatermarks;
import org.apache.flink.streaming.api.operators.util.PausableRelativeClock;
import org.apache.flink.streaming.api.operators.util.SimpleVersionedListState;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.runtime.io.DataInputStatus;
import org.apache.flink.streaming.runtime.io.MultipleFuturesAvailabilityHelper;
import org.apache.flink.streaming.runtime.io.PushingAsyncDataInput;
import org.apache.flink.streaming.runtime.streamrecord.RecordAttributesBuilder;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import org.apache.flink.streaming.runtime.tasks.ProcessingTimeService;
import org.apache.flink.streaming.runtime.tasks.StreamTask;
import org.apache.flink.streaming.runtime.tasks.StreamTask.CanEmitBatchOfRecordsChecker;
import org.apache.flink.util.CollectionUtil;
import org.apache.flink.util.FlinkRuntimeException;
import org.apache.flink.util.UserCodeClassLoader;
import org.apache.flink.util.function.FunctionWithException;
import javax.annotation.Nullable;
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.Set;
import java.util.concurrent.CompletableFuture;
import static org.apache.flink.configuration.PipelineOptions.ALLOW_UNALIGNED_SOURCE_SPLITS;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;
/**
* Base source operator only used for integrating the source reader which is proposed by FLIP-27. It
* implements the interface of {@link PushingAsyncDataInput} which is naturally compatible with one
* input processing in runtime stack.
*
* <p><b>Important Note on Serialization:</b> The SourceOperator inherits the {@link
* java.io.Serializable} interface from the StreamOperator, but is in fact NOT serializable. The
* operator must only be instantiated in the StreamTask from its factory.
*
* @param <OUT> The output type of the operator.
*/
@Internal
public class SourceOperator<OUT, SplitT extends SourceSplit> extends AbstractStreamOperator<OUT>
implements OperatorEventHandler,
PushingAsyncDataInput<OUT>,
TimestampsAndWatermarks.WatermarkUpdateListener {
private static final long serialVersionUID = 1405537676017904695L;
// Package private for unit test.
static final ListStateDescriptor<byte[]> SPLITS_STATE_DESC =
new ListStateDescriptor<>("SourceReaderState", BytePrimitiveArraySerializer.INSTANCE);
/**
* The factory for the source reader. This is a workaround, because currently the SourceReader
* must be lazily initialized, which is mainly because the metrics groups that the reader relies
* on is lazily initialized.
*/
private final FunctionWithException<SourceReaderContext, SourceReader<OUT, SplitT>, Exception>
readerFactory;
/**
* The serializer for the splits, applied to the split types before storing them in the reader
* state.
*/
private final SimpleVersionedSerializer<SplitT> splitSerializer;
/** The event gateway through which this operator talks to its coordinator. */
private final OperatorEventGateway operatorEventGateway;
/** The factory for timestamps and watermark generators. */
private final WatermarkStrategy<OUT> watermarkStrategy;
private final WatermarkAlignmentParams watermarkAlignmentParams;
/** The Flink configuration. */
private final Configuration configuration;
/**
* Host name of the machine where the operator runs, to support locality aware work assignment.
*/
private final String localHostname;
/** Whether to emit intermediate watermarks or only one final watermark at the end of input. */
private final boolean emitProgressiveWatermarks;
// ---- lazily initialized fields (these fields are the "hot" fields) ----
/** The source reader that does most of the work. */
private SourceReader<OUT, SplitT> sourceReader;
private ReaderOutput<OUT> currentMainOutput;
private DataOutput<OUT> lastInvokedOutput;
private long latestWatermark = Watermark.UNINITIALIZED.getTimestamp();
private boolean idle = false;
/** The state that holds the currently assigned splits. */
private ListState<SplitT> readerState;
/**
* The event time and watermarking logic. Ideally this would be eagerly passed into this
* operator, but we currently need to instantiate this lazily, because the metric groups exist
* only later.
*/
private TimestampsAndWatermarks<OUT> eventTimeLogic;
/** A mode to control the behaviour of the {@link #emitNext(DataOutput)} method. */
private OperatingMode operatingMode;
private final CompletableFuture<Void> finished = new CompletableFuture<>();
private final SourceOperatorAvailabilityHelper availabilityHelper =
new SourceOperatorAvailabilityHelper();
private final List<SplitT> splitsToInitializeOutput = new ArrayList<>();
private final Map<String, Long> splitCurrentWatermarks = new HashMap<>();
private final Set<String> currentlyPausedSplits = new HashSet<>();
private final Map<String, InternalSourceSplitMetricGroup> splitMetricGroups = new HashMap<>();
private enum OperatingMode {
READING,
WAITING_FOR_ALIGNMENT,
OUTPUT_NOT_INITIALIZED,
SOURCE_DRAINED,
SOURCE_STOPPED,
DATA_FINISHED
}
private InternalSourceReaderMetricGroup sourceMetricGroup;
private long currentMaxDesiredWatermark = Watermark.MAX_WATERMARK.getTimestamp();
/** Can be not completed only in {@link OperatingMode#WAITING_FOR_ALIGNMENT} mode. */
private CompletableFuture<Void> waitingForAlignmentFuture =
CompletableFuture.completedFuture(null);
private @Nullable LatencyMarkerEmitter<OUT> latencyMarkerEmitter;
private final boolean allowUnalignedSourceSplits;
private final CanEmitBatchOfRecordsChecker canEmitBatchOfRecords;
/**
* {@link PausableRelativeClock} tracking activity of the operator's main input. It's paused on
* backpressure. Note, each split output has its own independent {@link PausableRelativeClock}.
*/
private transient PausableRelativeClock mainInputActivityClock;
/** Watermark identifier to whether the watermark are aligned. */
private final Map<String, Boolean> watermarkIsAlignedMap;
public SourceOperator(
StreamOperatorParameters<OUT> parameters,
FunctionWithException<SourceReaderContext, SourceReader<OUT, SplitT>, Exception>
readerFactory,
OperatorEventGateway operatorEventGateway,
SimpleVersionedSerializer<SplitT> splitSerializer,
WatermarkStrategy<OUT> watermarkStrategy,
ProcessingTimeService timeService,
Configuration configuration,
String localHostname,
boolean emitProgressiveWatermarks,
CanEmitBatchOfRecordsChecker canEmitBatchOfRecords,
Map<String, Boolean> watermarkIsAlignedMap) {
super(parameters);
this.readerFactory = checkNotNull(readerFactory);
this.operatorEventGateway = checkNotNull(operatorEventGateway);
this.splitSerializer = checkNotNull(splitSerializer);
this.watermarkStrategy = checkNotNull(watermarkStrategy);
this.processingTimeService = timeService;
this.configuration = checkNotNull(configuration);
this.localHostname = checkNotNull(localHostname);
this.emitProgressiveWatermarks = emitProgressiveWatermarks;
this.operatingMode = OperatingMode.OUTPUT_NOT_INITIALIZED;
this.watermarkAlignmentParams = watermarkStrategy.getAlignmentParameters();
this.allowUnalignedSourceSplits = configuration.get(ALLOW_UNALIGNED_SOURCE_SPLITS);
this.canEmitBatchOfRecords = checkNotNull(canEmitBatchOfRecords);
this.watermarkIsAlignedMap = watermarkIsAlignedMap;
}
@Override
protected void setup(
StreamTask<?, ?> containingTask,
StreamConfig config,
Output<StreamRecord<OUT>> output) {
super.setup(containingTask, config, output);
initSourceMetricGroup();
// Metric "numRecordsIn" & "numBytesIn" is defined as the total number of records/bytes
// read from the external system in FLIP-33, reuse them for task to account for traffic
// with external system
this.metrics.getIOMetricGroup().reuseInputMetricsForTask();
this.metrics.getIOMetricGroup().reuseBytesInputMetricsForTask();
}
@VisibleForTesting
protected void initSourceMetricGroup() {
sourceMetricGroup = InternalSourceReaderMetricGroup.wrap(getMetricGroup());
}
/**
* Initializes the reader. The code from this method should ideally happen in the constructor or
* in the operator factory even. It has to happen here at a slightly later stage, because of the
* lazy metric initialization.
*
* <p>Calling this method explicitly is an optional way to have the reader initialization a bit
* earlier than in open(), as needed by the {@link
* org.apache.flink.streaming.runtime.tasks.SourceOperatorStreamTask}
*
* <p>This code should move to the constructor once the metric groups are available at task
* setup time.
*/
public void initReader() throws Exception {
if (sourceReader != null) {
return;
}
StreamingRuntimeContext runtimeContext = getRuntimeContext();
final int subtaskIndex = runtimeContext.getTaskInfo().getIndexOfThisSubtask();
final RichSourceReaderContext context =
new RichSourceReaderContext() {
@Override
public SourceReaderMetricGroup metricGroup() {
return sourceMetricGroup;
}
@Override
public Configuration getConfiguration() {
return configuration;
}
@Override
public String getLocalHostName() {
return localHostname;
}
@Override
public int getIndexOfSubtask() {
return subtaskIndex;
}
@Override
public void sendSplitRequest() {
operatorEventGateway.sendEventToCoordinator(
new RequestSplitEvent(getLocalHostName()));
}
@Override
public void sendSourceEventToCoordinator(SourceEvent event) {
operatorEventGateway.sendEventToCoordinator(new SourceEventWrapper(event));
}
@Override
public UserCodeClassLoader getUserCodeClassLoader() {
return new UserCodeClassLoader() {
@Override
public ClassLoader asClassLoader() {
return getRuntimeContext().getUserCodeClassLoader();
}
@Override
public void registerReleaseHookIfAbsent(
String releaseHookName, Runnable releaseHook) {
getRuntimeContext()
.registerUserCodeClassLoaderReleaseHookIfAbsent(
releaseHookName, releaseHook);
}
};
}
@Override
public int currentParallelism() {
return getRuntimeContext().getTaskInfo().getNumberOfParallelSubtasks();
}
@Override
public void emitWatermark(
org.apache.flink.api.common.watermark.Watermark watermark) {
checkState(watermarkIsAlignedMap.containsKey(watermark.getIdentifier()));
output.emitWatermark(
new WatermarkEvent(
watermark,
watermarkIsAlignedMap.get(watermark.getIdentifier())));
}
@Override
public RuntimeContext getRuntimeContext() {
return runtimeContext;
}
};
sourceReader = readerFactory.apply(context);
}
public InternalSourceReaderMetricGroup getSourceMetricGroup() {
return sourceMetricGroup;
}
protected InternalSourceSplitMetricGroup getOrCreateSplitMetricGroup(String splitId) {
if (!this.splitMetricGroups.containsKey(splitId)) {
InternalSourceSplitMetricGroup splitMetricGroup =
InternalSourceSplitMetricGroup.wrap(
getMetricGroup(),
splitId,
() ->
splitCurrentWatermarks.getOrDefault(
splitId, Watermark.UNINITIALIZED.getTimestamp()));
splitMetricGroup.markSplitStart();
this.splitMetricGroups.put(splitId, splitMetricGroup);
}
return this.splitMetricGroups.get(splitId);
}
@VisibleForTesting
public InternalSourceSplitMetricGroup getSplitMetricGroup(String splitId) {
return this.splitMetricGroups.get(splitId);
}
@Override
public void open() throws Exception {
mainInputActivityClock = new PausableRelativeClock(getProcessingTimeService().getClock());
TaskIOMetricGroup taskIOMetricGroup =
getContainingTask().getEnvironment().getMetricGroup().getIOMetricGroup();
taskIOMetricGroup.registerBackPressureListener(mainInputActivityClock);
initReader();
// in the future when we this one is migrated to the "eager initialization" operator
// (StreamOperatorV2), then we should evaluate this during operator construction.
if (emitProgressiveWatermarks) {
eventTimeLogic =
TimestampsAndWatermarks.createProgressiveEventTimeLogic(
watermarkStrategy,
sourceMetricGroup,
getProcessingTimeService(),
getExecutionConfig().getAutoWatermarkInterval(),
mainInputActivityClock,
getProcessingTimeService().getClock(),
taskIOMetricGroup);
} else {
eventTimeLogic =
TimestampsAndWatermarks.createNoOpEventTimeLogic(
watermarkStrategy, sourceMetricGroup, mainInputActivityClock);
}
// restore the state if necessary.
final List<SplitT> splits = CollectionUtil.iterableToList(readerState.get());
if (!splits.isEmpty()) {
LOG.info("Restoring state for {} split(s) to reader.", splits.size());
for (SplitT s : splits) {
getOrCreateSplitMetricGroup(s.splitId());
}
splitsToInitializeOutput.addAll(splits);
sourceReader.addSplits(splits);
}
// Register the reader to the coordinator.
registerReader();
sourceMetricGroup.idlingStarted();
// Start the reader after registration, sending messages in start is allowed.
sourceReader.start();
eventTimeLogic.startPeriodicWatermarkEmits();
}
@Override
public void finish() throws Exception {
stopInternalServices();
super.finish();
finished.complete(null);
}
private void stopInternalServices() {
if (eventTimeLogic != null) {
eventTimeLogic.stopPeriodicWatermarkEmits();
}
if (latencyMarkerEmitter != null) {
latencyMarkerEmitter.close();
}
}
public CompletableFuture<Void> stop(StopMode mode) {
switch (operatingMode) {
case WAITING_FOR_ALIGNMENT:
case OUTPUT_NOT_INITIALIZED:
case READING:
this.operatingMode =
mode == StopMode.DRAIN
? OperatingMode.SOURCE_DRAINED
: OperatingMode.SOURCE_STOPPED;
availabilityHelper.forceStop();
if (this.operatingMode == OperatingMode.SOURCE_STOPPED) {
stopInternalServices();
finished.complete(null);
return finished;
}
break;
}
return finished;
}
@Override
public void close() throws Exception {
getContainingTask()
.getEnvironment()
.getMetricGroup()
.getIOMetricGroup()
.unregisterBackPressureListener(mainInputActivityClock);
if (sourceReader != null) {
sourceReader.close();
}
super.close();
}
@Override
public DataInputStatus emitNext(DataOutput<OUT> output) throws Exception {
// guarding an assumptions we currently make due to the fact that certain classes
// assume a constant output, this assumption does not need to stand if we emitted all
// records. In that case the output will change to FinishedDataOutput
assert lastInvokedOutput == output
|| lastInvokedOutput == null
|| this.operatingMode == OperatingMode.DATA_FINISHED;
// short circuit the hot path. Without this short circuit (READING handled in the
// switch/case) InputBenchmark.mapSink was showing a performance regression.
if (operatingMode != OperatingMode.READING) {
return emitNextNotReading(output);
}
InputStatus status;
do {
status = sourceReader.pollNext(currentMainOutput);
} while (status == InputStatus.MORE_AVAILABLE
&& canEmitBatchOfRecords.check()
&& !shouldWaitForAlignment());
return convertToInternalStatus(status);
}
private DataInputStatus emitNextNotReading(DataOutput<OUT> output) throws Exception {
switch (operatingMode) {
case OUTPUT_NOT_INITIALIZED:
if (watermarkAlignmentParams.isEnabled()) {
// Only wrap the output when watermark alignment is enabled, as otherwise this
// introduces a small performance regression (probably because of an extra
// virtual call)
processingTimeService.scheduleWithFixedDelay(
time -> emitLatestWatermark(),
watermarkAlignmentParams.getUpdateInterval(),
watermarkAlignmentParams.getUpdateInterval());
}
initializeMainOutput(output);
return convertToInternalStatus(sourceReader.pollNext(currentMainOutput));
case SOURCE_STOPPED:
this.operatingMode = OperatingMode.DATA_FINISHED;
sourceMetricGroup.idlingStarted();
return DataInputStatus.STOPPED;
case SOURCE_DRAINED:
this.operatingMode = OperatingMode.DATA_FINISHED;
sourceMetricGroup.idlingStarted();
return DataInputStatus.END_OF_DATA;
case DATA_FINISHED:
if (watermarkAlignmentParams.isEnabled()) {
latestWatermark = Watermark.MAX_WATERMARK.getTimestamp();
emitLatestWatermark();
}
sourceMetricGroup.idlingStarted();
return DataInputStatus.END_OF_INPUT;
case WAITING_FOR_ALIGNMENT:
checkState(!waitingForAlignmentFuture.isDone());
checkState(shouldWaitForAlignment());
return convertToInternalStatus(InputStatus.NOTHING_AVAILABLE);
case READING:
default:
throw new IllegalStateException("Unknown operating mode: " + operatingMode);
}
}
private void initializeMainOutput(DataOutput<OUT> output) {
currentMainOutput = eventTimeLogic.createMainOutput(output, this);
initializeLatencyMarkerEmitter(output);
lastInvokedOutput = output;
// Create per-split output for pending splits added before main output is initialized
createOutputForSplits(splitsToInitializeOutput);
this.operatingMode = OperatingMode.READING;
}
private void initializeLatencyMarkerEmitter(DataOutput<OUT> output) {
long latencyTrackingInterval =
getExecutionConfig().isLatencyTrackingConfigured()
? getExecutionConfig().getLatencyTrackingInterval()
: getContainingTask()
.getEnvironment()
.getTaskManagerInfo()
.getConfiguration()
.get(MetricOptions.LATENCY_INTERVAL)
.toMillis();
if (latencyTrackingInterval > 0) {
latencyMarkerEmitter =
new LatencyMarkerEmitter<>(
getProcessingTimeService(),
output::emitLatencyMarker,
latencyTrackingInterval,
getOperatorID(),
getRuntimeContext().getTaskInfo().getIndexOfThisSubtask());
}
}
private DataInputStatus convertToInternalStatus(InputStatus inputStatus) {
switch (inputStatus) {
case MORE_AVAILABLE:
return DataInputStatus.MORE_AVAILABLE;
case NOTHING_AVAILABLE:
sourceMetricGroup.idlingStarted();
return DataInputStatus.NOTHING_AVAILABLE;
case END_OF_INPUT:
this.operatingMode = OperatingMode.DATA_FINISHED;
sourceMetricGroup.idlingStarted();
return DataInputStatus.END_OF_DATA;
default:
throw new IllegalArgumentException("Unknown input status: " + inputStatus);
}
}
private void emitLatestWatermark() {
checkState(currentMainOutput != null);
if (latestWatermark == Watermark.UNINITIALIZED.getTimestamp()) {
return;
}
operatorEventGateway.sendEventToCoordinator(
new ReportedWatermarkEvent(
idle ? Watermark.MAX_WATERMARK.getTimestamp() : latestWatermark));
}
@Override
public void snapshotState(StateSnapshotContext context) throws Exception {
long checkpointId = context.getCheckpointId();
LOG.debug("Taking a snapshot for checkpoint {}", checkpointId);
readerState.update(sourceReader.snapshotState(checkpointId));
}
@Override
public CompletableFuture<?> getAvailableFuture() {
switch (operatingMode) {
case WAITING_FOR_ALIGNMENT:
return availabilityHelper.update(waitingForAlignmentFuture);
case OUTPUT_NOT_INITIALIZED:
case READING:
return availabilityHelper.update(sourceReader.isAvailable());
case SOURCE_STOPPED:
case SOURCE_DRAINED:
case DATA_FINISHED:
return AvailabilityProvider.AVAILABLE;
default:
throw new IllegalStateException("Unknown operating mode: " + operatingMode);
}
}
@Override
public void initializeState(StateInitializationContext context) throws Exception {
super.initializeState(context);
final ListState<byte[]> rawState =
context.getOperatorStateStore().getListState(SPLITS_STATE_DESC);
readerState = new SimpleVersionedListState<>(rawState, splitSerializer);
}
@Override
public void notifyCheckpointComplete(long checkpointId) throws Exception {
super.notifyCheckpointComplete(checkpointId);
sourceReader.notifyCheckpointComplete(checkpointId);
}
@Override
public void notifyCheckpointAborted(long checkpointId) throws Exception {
super.notifyCheckpointAborted(checkpointId);
sourceReader.notifyCheckpointAborted(checkpointId);
}
@SuppressWarnings("unchecked")
public void handleOperatorEvent(OperatorEvent event) {
if (event instanceof WatermarkAlignmentEvent) {
updateMaxDesiredWatermark((WatermarkAlignmentEvent) event);
checkWatermarkAlignment();
checkSplitWatermarkAlignment();
} else if (event instanceof AddSplitEvent) {
handleAddSplitsEvent(((AddSplitEvent<SplitT>) event));
} else if (event instanceof SourceEventWrapper) {
sourceReader.handleSourceEvents(((SourceEventWrapper) event).getSourceEvent());
} else if (event instanceof NoMoreSplitsEvent) {
sourceReader.notifyNoMoreSplits();
} else if (event instanceof IsProcessingBacklogEvent) {
if (eventTimeLogic != null) {
eventTimeLogic.emitImmediateWatermark(System.currentTimeMillis());
}
output.emitRecordAttributes(
new RecordAttributesBuilder(Collections.emptyList())
.setBacklog(((IsProcessingBacklogEvent) event).isProcessingBacklog())
.build());
} else {
throw new IllegalStateException("Received unexpected operator event " + event);
}
}
private void handleAddSplitsEvent(AddSplitEvent<SplitT> event) {
try {
List<SplitT> newSplits = event.splits(splitSerializer);
if (operatingMode == OperatingMode.OUTPUT_NOT_INITIALIZED) {
// For splits arrived before the main output is initialized, store them into the
// pending list. Outputs of these splits will be created once the main output is
// ready.
splitsToInitializeOutput.addAll(newSplits);
} else {
// Create output directly for new splits if the main output is already initialized.
createOutputForSplits(newSplits);
}
sourceReader.addSplits(newSplits);
createMetricGroupForSplits(newSplits);
} catch (IOException e) {
throw new FlinkRuntimeException("Failed to deserialize the splits.", e);
}
}
private void createOutputForSplits(List<SplitT> newSplits) {
for (SplitT split : newSplits) {
currentMainOutput.createOutputForSplit(split.splitId());
}
}
private void createMetricGroupForSplits(List<SplitT> newSplits) {
for (SplitT split : newSplits) {
getOrCreateSplitMetricGroup(split.splitId());
}
}
private void updateMaxDesiredWatermark(WatermarkAlignmentEvent event) {
currentMaxDesiredWatermark = event.getMaxWatermark();
sourceMetricGroup.updateMaxDesiredWatermark(currentMaxDesiredWatermark);
}
@Override
public void updateIdle(boolean isIdle) {
this.idle = isIdle;
}
@Override
public void updateCurrentEffectiveWatermark(long watermark) {
latestWatermark = watermark;
checkWatermarkAlignment();
}
@Override
public void updateCurrentSplitWatermark(String splitId, long watermark) {
splitCurrentWatermarks.put(splitId, watermark);
if (watermark > currentMaxDesiredWatermark && !currentlyPausedSplits.contains(splitId)) {
pauseOrResumeSplits(Collections.singletonList(splitId), Collections.emptyList());
currentlyPausedSplits.add(splitId);
}
}
@Override
public void updateCurrentSplitIdle(String splitId, boolean idle) {
if (idle) {
this.getOrCreateSplitMetricGroup(splitId).markIdle();
} else {
this.getOrCreateSplitMetricGroup(splitId).markNotIdle();
}
}
@Override
public void splitFinished(String splitId) {
splitCurrentWatermarks.remove(splitId);
getOrCreateSplitMetricGroup(splitId).onSplitFinished();
this.splitMetricGroups.remove(splitId);
}
/**
* Finds the splits that are beyond the current max watermark and pauses them. At the same time,
* splits that have been paused and where the global watermark caught up are resumed.
*
* <p>Note: This takes effect only if there are multiple splits, otherwise it does nothing.
*/
private void checkSplitWatermarkAlignment() {
Collection<String> splitsToPause = new ArrayList<>();
Collection<String> splitsToResume = new ArrayList<>();
splitCurrentWatermarks.forEach(
(splitId, splitWatermark) -> {
if (splitWatermark > currentMaxDesiredWatermark) {
splitsToPause.add(splitId);
} else if (currentlyPausedSplits.contains(splitId)) {
splitsToResume.add(splitId);
}
});
splitsToPause.removeAll(currentlyPausedSplits);
if (!splitsToPause.isEmpty() || !splitsToResume.isEmpty()) {
pauseOrResumeSplits(splitsToPause, splitsToResume);
currentlyPausedSplits.addAll(splitsToPause);
splitsToResume.forEach(currentlyPausedSplits::remove);
}
}
private void pauseOrResumeSplits(
Collection<String> splitsToPause, Collection<String> splitsToResume) {
try {
sourceReader.pauseOrResumeSplits(splitsToPause, splitsToResume);
eventTimeLogic.pauseOrResumeSplits(splitsToPause, splitsToResume);
reportPausedOrResumed(splitsToPause, splitsToResume);
} catch (UnsupportedOperationException e) {
if (!allowUnalignedSourceSplits) {
throw e;
}
}
}
private void reportPausedOrResumed(
Collection<String> splitsToPause, Collection<String> splitsToResume) {
for (String splitId : splitsToResume) {
getOrCreateSplitMetricGroup(splitId).markNotPaused();
}
for (String splitId : splitsToPause) {
getOrCreateSplitMetricGroup(splitId).markPaused();
}
}
private void checkWatermarkAlignment() {
if (operatingMode == OperatingMode.READING) {
checkState(waitingForAlignmentFuture.isDone());
if (shouldWaitForAlignment()) {
operatingMode = OperatingMode.WAITING_FOR_ALIGNMENT;
waitingForAlignmentFuture = new CompletableFuture<>();
mainInputActivityClock.pause();
}
} else if (operatingMode == OperatingMode.WAITING_FOR_ALIGNMENT) {
checkState(!waitingForAlignmentFuture.isDone());
if (!shouldWaitForAlignment()) {
operatingMode = OperatingMode.READING;
waitingForAlignmentFuture.complete(null);
mainInputActivityClock.unPause();
}
}
}
private boolean shouldWaitForAlignment() {
return currentMaxDesiredWatermark < latestWatermark;
}
private void registerReader() {
operatorEventGateway.sendEventToCoordinator(
new ReaderRegistrationEvent(
getRuntimeContext().getTaskInfo().getIndexOfThisSubtask(), localHostname));
}
// --------------- methods for unit tests ------------
@VisibleForTesting
public SourceReader<OUT, SplitT> getSourceReader() {
return sourceReader;
}
@VisibleForTesting
ListState<SplitT> getReaderState() {
return readerState;
}
private static class SourceOperatorAvailabilityHelper {
private final CompletableFuture<Void> forcedStopFuture = new CompletableFuture<>();
private final MultipleFuturesAvailabilityHelper availabilityHelper;
private SourceOperatorAvailabilityHelper() {
availabilityHelper = new MultipleFuturesAvailabilityHelper(2);
availabilityHelper.anyOf(0, forcedStopFuture);
}
public CompletableFuture<?> update(CompletableFuture<Void> sourceReaderFuture) {
if (sourceReaderFuture == AvailabilityProvider.AVAILABLE
|| sourceReaderFuture.isDone()) {
return AvailabilityProvider.AVAILABLE;
}
availabilityHelper.resetToUnAvailable();
availabilityHelper.anyOf(0, forcedStopFuture);
availabilityHelper.anyOf(1, sourceReaderFuture);
return availabilityHelper.getAvailableFuture();
}
public void forceStop() {
forcedStopFuture.complete(null);
}
}
}
|
apache/hbase | 36,498 | hbase-thrift/src/main/java/org/apache/hadoop/hbase/thrift2/generated/TAppend.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"})
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.14.1)", date = "2025-08-16")
public class TAppend implements org.apache.thrift.TBase<TAppend, TAppend._Fields>, java.io.Serializable, Cloneable, Comparable<TAppend> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TAppend");
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)3);
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)4);
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)5);
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)6);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new TAppendStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new TAppendTupleSchemeFactory();
public @org.apache.thrift.annotation.Nullable java.nio.ByteBuffer row; // required
public @org.apache.thrift.annotation.Nullable java.util.List<TColumnValue> 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)3, "attributes"),
/**
*
* @see TDurability
*/
DURABILITY((short)4, "durability"),
CELL_VISIBILITY((short)5, "cellVisibility"),
RETURN_RESULTS((short)6, "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 3: // ATTRIBUTES
return ATTRIBUTES;
case 4: // DURABILITY
return DURABILITY;
case 5: // CELL_VISIBILITY
return CELL_VISIBILITY;
case 6: // 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, TColumnValue.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(TAppend.class, metaDataMap);
}
public TAppend() {
}
public TAppend(
java.nio.ByteBuffer row,
java.util.List<TColumnValue> columns)
{
this();
this.row = org.apache.thrift.TBaseHelper.copyBinary(row);
this.columns = columns;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public TAppend(TAppend other) {
__isset_bitfield = other.__isset_bitfield;
if (other.isSetRow()) {
this.row = org.apache.thrift.TBaseHelper.copyBinary(other.row);
}
if (other.isSetColumns()) {
java.util.List<TColumnValue> __this__columns = new java.util.ArrayList<TColumnValue>(other.columns.size());
for (TColumnValue other_element : other.columns) {
__this__columns.add(new TColumnValue(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 TAppend deepCopy() {
return new TAppend(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 TAppend setRow(byte[] row) {
this.row = row == null ? (java.nio.ByteBuffer)null : java.nio.ByteBuffer.wrap(row.clone());
return this;
}
public TAppend 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<TColumnValue> getColumnsIterator() {
return (this.columns == null) ? null : this.columns.iterator();
}
public void addToColumns(TColumnValue elem) {
if (this.columns == null) {
this.columns = new java.util.ArrayList<TColumnValue>();
}
this.columns.add(elem);
}
@org.apache.thrift.annotation.Nullable
public java.util.List<TColumnValue> getColumns() {
return this.columns;
}
public TAppend setColumns(@org.apache.thrift.annotation.Nullable java.util.List<TColumnValue> 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 TAppend 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 TAppend 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 TAppend 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 TAppend 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<TColumnValue>)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 TAppend)
return this.equals((TAppend)that);
return false;
}
public boolean equals(TAppend 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(TAppend 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("TAppend(");
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 TAppendStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public TAppendStandardScheme getScheme() {
return new TAppendStandardScheme();
}
}
private static class TAppendStandardScheme extends org.apache.thrift.scheme.StandardScheme<TAppend> {
public void read(org.apache.thrift.protocol.TProtocol iprot, TAppend 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 _list88 = iprot.readListBegin();
struct.columns = new java.util.ArrayList<TColumnValue>(_list88.size);
@org.apache.thrift.annotation.Nullable TColumnValue _elem89;
for (int _i90 = 0; _i90 < _list88.size; ++_i90)
{
_elem89 = new TColumnValue();
_elem89.read(iprot);
struct.columns.add(_elem89);
}
iprot.readListEnd();
}
struct.setColumnsIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // ATTRIBUTES
if (schemeField.type == org.apache.thrift.protocol.TType.MAP) {
{
org.apache.thrift.protocol.TMap _map91 = iprot.readMapBegin();
struct.attributes = new java.util.HashMap<java.nio.ByteBuffer,java.nio.ByteBuffer>(2*_map91.size);
@org.apache.thrift.annotation.Nullable java.nio.ByteBuffer _key92;
@org.apache.thrift.annotation.Nullable java.nio.ByteBuffer _val93;
for (int _i94 = 0; _i94 < _map91.size; ++_i94)
{
_key92 = iprot.readBinary();
_val93 = iprot.readBinary();
struct.attributes.put(_key92, _val93);
}
iprot.readMapEnd();
}
struct.setAttributesIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 4: // 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 5: // 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 6: // 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, TAppend 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 (TColumnValue _iter95 : struct.columns)
{
_iter95.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> _iter96 : struct.attributes.entrySet())
{
oprot.writeBinary(_iter96.getKey());
oprot.writeBinary(_iter96.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 TAppendTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public TAppendTupleScheme getScheme() {
return new TAppendTupleScheme();
}
}
private static class TAppendTupleScheme extends org.apache.thrift.scheme.TupleScheme<TAppend> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, TAppend 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 (TColumnValue _iter97 : struct.columns)
{
_iter97.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> _iter98 : struct.attributes.entrySet())
{
oprot.writeBinary(_iter98.getKey());
oprot.writeBinary(_iter98.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, TAppend 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 _list99 = iprot.readListBegin(org.apache.thrift.protocol.TType.STRUCT);
struct.columns = new java.util.ArrayList<TColumnValue>(_list99.size);
@org.apache.thrift.annotation.Nullable TColumnValue _elem100;
for (int _i101 = 0; _i101 < _list99.size; ++_i101)
{
_elem100 = new TColumnValue();
_elem100.read(iprot);
struct.columns.add(_elem100);
}
}
struct.setColumnsIsSet(true);
java.util.BitSet incoming = iprot.readBitSet(4);
if (incoming.get(0)) {
{
org.apache.thrift.protocol.TMap _map102 = 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*_map102.size);
@org.apache.thrift.annotation.Nullable java.nio.ByteBuffer _key103;
@org.apache.thrift.annotation.Nullable java.nio.ByteBuffer _val104;
for (int _i105 = 0; _i105 < _map102.size; ++_i105)
{
_key103 = iprot.readBinary();
_val104 = iprot.readBinary();
struct.attributes.put(_key103, _val104);
}
}
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();
}
}
|
googleapis/google-cloud-java | 36,412 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/EvaluationDataset.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>
* The dataset used for evaluation.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.EvaluationDataset}
*/
public final class EvaluationDataset extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.EvaluationDataset)
EvaluationDatasetOrBuilder {
private static final long serialVersionUID = 0L;
// Use EvaluationDataset.newBuilder() to construct.
private EvaluationDataset(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private EvaluationDataset() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new EvaluationDataset();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_EvaluationDataset_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_EvaluationDataset_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.EvaluationDataset.class,
com.google.cloud.aiplatform.v1beta1.EvaluationDataset.Builder.class);
}
private int sourceCase_ = 0;
@SuppressWarnings("serial")
private java.lang.Object source_;
public enum SourceCase
implements
com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
GCS_SOURCE(1),
BIGQUERY_SOURCE(2),
SOURCE_NOT_SET(0);
private final int value;
private SourceCase(int value) {
this.value = value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static SourceCase valueOf(int value) {
return forNumber(value);
}
public static SourceCase forNumber(int value) {
switch (value) {
case 1:
return GCS_SOURCE;
case 2:
return BIGQUERY_SOURCE;
case 0:
return SOURCE_NOT_SET;
default:
return null;
}
}
public int getNumber() {
return this.value;
}
};
public SourceCase getSourceCase() {
return SourceCase.forNumber(sourceCase_);
}
public static final int GCS_SOURCE_FIELD_NUMBER = 1;
/**
*
*
* <pre>
* Cloud storage source holds the dataset. Currently only one Cloud Storage
* file path is supported.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.GcsSource gcs_source = 1;</code>
*
* @return Whether the gcsSource field is set.
*/
@java.lang.Override
public boolean hasGcsSource() {
return sourceCase_ == 1;
}
/**
*
*
* <pre>
* Cloud storage source holds the dataset. Currently only one Cloud Storage
* file path is supported.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.GcsSource gcs_source = 1;</code>
*
* @return The gcsSource.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.GcsSource getGcsSource() {
if (sourceCase_ == 1) {
return (com.google.cloud.aiplatform.v1beta1.GcsSource) source_;
}
return com.google.cloud.aiplatform.v1beta1.GcsSource.getDefaultInstance();
}
/**
*
*
* <pre>
* Cloud storage source holds the dataset. Currently only one Cloud Storage
* file path is supported.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.GcsSource gcs_source = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.GcsSourceOrBuilder getGcsSourceOrBuilder() {
if (sourceCase_ == 1) {
return (com.google.cloud.aiplatform.v1beta1.GcsSource) source_;
}
return com.google.cloud.aiplatform.v1beta1.GcsSource.getDefaultInstance();
}
public static final int BIGQUERY_SOURCE_FIELD_NUMBER = 2;
/**
*
*
* <pre>
* BigQuery source holds the dataset.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.BigQuerySource bigquery_source = 2;</code>
*
* @return Whether the bigquerySource field is set.
*/
@java.lang.Override
public boolean hasBigquerySource() {
return sourceCase_ == 2;
}
/**
*
*
* <pre>
* BigQuery source holds the dataset.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.BigQuerySource bigquery_source = 2;</code>
*
* @return The bigquerySource.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.BigQuerySource getBigquerySource() {
if (sourceCase_ == 2) {
return (com.google.cloud.aiplatform.v1beta1.BigQuerySource) source_;
}
return com.google.cloud.aiplatform.v1beta1.BigQuerySource.getDefaultInstance();
}
/**
*
*
* <pre>
* BigQuery source holds the dataset.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.BigQuerySource bigquery_source = 2;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.BigQuerySourceOrBuilder getBigquerySourceOrBuilder() {
if (sourceCase_ == 2) {
return (com.google.cloud.aiplatform.v1beta1.BigQuerySource) source_;
}
return com.google.cloud.aiplatform.v1beta1.BigQuerySource.getDefaultInstance();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (sourceCase_ == 1) {
output.writeMessage(1, (com.google.cloud.aiplatform.v1beta1.GcsSource) source_);
}
if (sourceCase_ == 2) {
output.writeMessage(2, (com.google.cloud.aiplatform.v1beta1.BigQuerySource) source_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (sourceCase_ == 1) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
1, (com.google.cloud.aiplatform.v1beta1.GcsSource) source_);
}
if (sourceCase_ == 2) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
2, (com.google.cloud.aiplatform.v1beta1.BigQuerySource) source_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.aiplatform.v1beta1.EvaluationDataset)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.EvaluationDataset other =
(com.google.cloud.aiplatform.v1beta1.EvaluationDataset) obj;
if (!getSourceCase().equals(other.getSourceCase())) return false;
switch (sourceCase_) {
case 1:
if (!getGcsSource().equals(other.getGcsSource())) return false;
break;
case 2:
if (!getBigquerySource().equals(other.getBigquerySource())) return false;
break;
case 0:
default:
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
switch (sourceCase_) {
case 1:
hash = (37 * hash) + GCS_SOURCE_FIELD_NUMBER;
hash = (53 * hash) + getGcsSource().hashCode();
break;
case 2:
hash = (37 * hash) + BIGQUERY_SOURCE_FIELD_NUMBER;
hash = (53 * hash) + getBigquerySource().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1beta1.EvaluationDataset parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.EvaluationDataset 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.EvaluationDataset parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.EvaluationDataset 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.EvaluationDataset parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.EvaluationDataset 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.EvaluationDataset parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.EvaluationDataset 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.EvaluationDataset parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.EvaluationDataset 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.EvaluationDataset 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.EvaluationDataset 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.EvaluationDataset 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 dataset used for evaluation.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.EvaluationDataset}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.EvaluationDataset)
com.google.cloud.aiplatform.v1beta1.EvaluationDatasetOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_EvaluationDataset_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_EvaluationDataset_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.EvaluationDataset.class,
com.google.cloud.aiplatform.v1beta1.EvaluationDataset.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.EvaluationDataset.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (gcsSourceBuilder_ != null) {
gcsSourceBuilder_.clear();
}
if (bigquerySourceBuilder_ != null) {
bigquerySourceBuilder_.clear();
}
sourceCase_ = 0;
source_ = 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_EvaluationDataset_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.EvaluationDataset getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.EvaluationDataset.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.EvaluationDataset build() {
com.google.cloud.aiplatform.v1beta1.EvaluationDataset result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.EvaluationDataset buildPartial() {
com.google.cloud.aiplatform.v1beta1.EvaluationDataset result =
new com.google.cloud.aiplatform.v1beta1.EvaluationDataset(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
buildPartialOneofs(result);
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.aiplatform.v1beta1.EvaluationDataset result) {
int from_bitField0_ = bitField0_;
}
private void buildPartialOneofs(com.google.cloud.aiplatform.v1beta1.EvaluationDataset result) {
result.sourceCase_ = sourceCase_;
result.source_ = this.source_;
if (sourceCase_ == 1 && gcsSourceBuilder_ != null) {
result.source_ = gcsSourceBuilder_.build();
}
if (sourceCase_ == 2 && bigquerySourceBuilder_ != null) {
result.source_ = bigquerySourceBuilder_.build();
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.aiplatform.v1beta1.EvaluationDataset) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.EvaluationDataset) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.EvaluationDataset other) {
if (other == com.google.cloud.aiplatform.v1beta1.EvaluationDataset.getDefaultInstance())
return this;
switch (other.getSourceCase()) {
case GCS_SOURCE:
{
mergeGcsSource(other.getGcsSource());
break;
}
case BIGQUERY_SOURCE:
{
mergeBigquerySource(other.getBigquerySource());
break;
}
case SOURCE_NOT_SET:
{
break;
}
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(getGcsSourceFieldBuilder().getBuilder(), extensionRegistry);
sourceCase_ = 1;
break;
} // case 10
case 18:
{
input.readMessage(getBigquerySourceFieldBuilder().getBuilder(), extensionRegistry);
sourceCase_ = 2;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int sourceCase_ = 0;
private java.lang.Object source_;
public SourceCase getSourceCase() {
return SourceCase.forNumber(sourceCase_);
}
public Builder clearSource() {
sourceCase_ = 0;
source_ = null;
onChanged();
return this;
}
private int bitField0_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.GcsSource,
com.google.cloud.aiplatform.v1beta1.GcsSource.Builder,
com.google.cloud.aiplatform.v1beta1.GcsSourceOrBuilder>
gcsSourceBuilder_;
/**
*
*
* <pre>
* Cloud storage source holds the dataset. Currently only one Cloud Storage
* file path is supported.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.GcsSource gcs_source = 1;</code>
*
* @return Whether the gcsSource field is set.
*/
@java.lang.Override
public boolean hasGcsSource() {
return sourceCase_ == 1;
}
/**
*
*
* <pre>
* Cloud storage source holds the dataset. Currently only one Cloud Storage
* file path is supported.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.GcsSource gcs_source = 1;</code>
*
* @return The gcsSource.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.GcsSource getGcsSource() {
if (gcsSourceBuilder_ == null) {
if (sourceCase_ == 1) {
return (com.google.cloud.aiplatform.v1beta1.GcsSource) source_;
}
return com.google.cloud.aiplatform.v1beta1.GcsSource.getDefaultInstance();
} else {
if (sourceCase_ == 1) {
return gcsSourceBuilder_.getMessage();
}
return com.google.cloud.aiplatform.v1beta1.GcsSource.getDefaultInstance();
}
}
/**
*
*
* <pre>
* Cloud storage source holds the dataset. Currently only one Cloud Storage
* file path is supported.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.GcsSource gcs_source = 1;</code>
*/
public Builder setGcsSource(com.google.cloud.aiplatform.v1beta1.GcsSource value) {
if (gcsSourceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
source_ = value;
onChanged();
} else {
gcsSourceBuilder_.setMessage(value);
}
sourceCase_ = 1;
return this;
}
/**
*
*
* <pre>
* Cloud storage source holds the dataset. Currently only one Cloud Storage
* file path is supported.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.GcsSource gcs_source = 1;</code>
*/
public Builder setGcsSource(
com.google.cloud.aiplatform.v1beta1.GcsSource.Builder builderForValue) {
if (gcsSourceBuilder_ == null) {
source_ = builderForValue.build();
onChanged();
} else {
gcsSourceBuilder_.setMessage(builderForValue.build());
}
sourceCase_ = 1;
return this;
}
/**
*
*
* <pre>
* Cloud storage source holds the dataset. Currently only one Cloud Storage
* file path is supported.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.GcsSource gcs_source = 1;</code>
*/
public Builder mergeGcsSource(com.google.cloud.aiplatform.v1beta1.GcsSource value) {
if (gcsSourceBuilder_ == null) {
if (sourceCase_ == 1
&& source_ != com.google.cloud.aiplatform.v1beta1.GcsSource.getDefaultInstance()) {
source_ =
com.google.cloud.aiplatform.v1beta1.GcsSource.newBuilder(
(com.google.cloud.aiplatform.v1beta1.GcsSource) source_)
.mergeFrom(value)
.buildPartial();
} else {
source_ = value;
}
onChanged();
} else {
if (sourceCase_ == 1) {
gcsSourceBuilder_.mergeFrom(value);
} else {
gcsSourceBuilder_.setMessage(value);
}
}
sourceCase_ = 1;
return this;
}
/**
*
*
* <pre>
* Cloud storage source holds the dataset. Currently only one Cloud Storage
* file path is supported.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.GcsSource gcs_source = 1;</code>
*/
public Builder clearGcsSource() {
if (gcsSourceBuilder_ == null) {
if (sourceCase_ == 1) {
sourceCase_ = 0;
source_ = null;
onChanged();
}
} else {
if (sourceCase_ == 1) {
sourceCase_ = 0;
source_ = null;
}
gcsSourceBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Cloud storage source holds the dataset. Currently only one Cloud Storage
* file path is supported.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.GcsSource gcs_source = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.GcsSource.Builder getGcsSourceBuilder() {
return getGcsSourceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Cloud storage source holds the dataset. Currently only one Cloud Storage
* file path is supported.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.GcsSource gcs_source = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.GcsSourceOrBuilder getGcsSourceOrBuilder() {
if ((sourceCase_ == 1) && (gcsSourceBuilder_ != null)) {
return gcsSourceBuilder_.getMessageOrBuilder();
} else {
if (sourceCase_ == 1) {
return (com.google.cloud.aiplatform.v1beta1.GcsSource) source_;
}
return com.google.cloud.aiplatform.v1beta1.GcsSource.getDefaultInstance();
}
}
/**
*
*
* <pre>
* Cloud storage source holds the dataset. Currently only one Cloud Storage
* file path is supported.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.GcsSource gcs_source = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.GcsSource,
com.google.cloud.aiplatform.v1beta1.GcsSource.Builder,
com.google.cloud.aiplatform.v1beta1.GcsSourceOrBuilder>
getGcsSourceFieldBuilder() {
if (gcsSourceBuilder_ == null) {
if (!(sourceCase_ == 1)) {
source_ = com.google.cloud.aiplatform.v1beta1.GcsSource.getDefaultInstance();
}
gcsSourceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.GcsSource,
com.google.cloud.aiplatform.v1beta1.GcsSource.Builder,
com.google.cloud.aiplatform.v1beta1.GcsSourceOrBuilder>(
(com.google.cloud.aiplatform.v1beta1.GcsSource) source_,
getParentForChildren(),
isClean());
source_ = null;
}
sourceCase_ = 1;
onChanged();
return gcsSourceBuilder_;
}
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.BigQuerySource,
com.google.cloud.aiplatform.v1beta1.BigQuerySource.Builder,
com.google.cloud.aiplatform.v1beta1.BigQuerySourceOrBuilder>
bigquerySourceBuilder_;
/**
*
*
* <pre>
* BigQuery source holds the dataset.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.BigQuerySource bigquery_source = 2;</code>
*
* @return Whether the bigquerySource field is set.
*/
@java.lang.Override
public boolean hasBigquerySource() {
return sourceCase_ == 2;
}
/**
*
*
* <pre>
* BigQuery source holds the dataset.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.BigQuerySource bigquery_source = 2;</code>
*
* @return The bigquerySource.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.BigQuerySource getBigquerySource() {
if (bigquerySourceBuilder_ == null) {
if (sourceCase_ == 2) {
return (com.google.cloud.aiplatform.v1beta1.BigQuerySource) source_;
}
return com.google.cloud.aiplatform.v1beta1.BigQuerySource.getDefaultInstance();
} else {
if (sourceCase_ == 2) {
return bigquerySourceBuilder_.getMessage();
}
return com.google.cloud.aiplatform.v1beta1.BigQuerySource.getDefaultInstance();
}
}
/**
*
*
* <pre>
* BigQuery source holds the dataset.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.BigQuerySource bigquery_source = 2;</code>
*/
public Builder setBigquerySource(com.google.cloud.aiplatform.v1beta1.BigQuerySource value) {
if (bigquerySourceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
source_ = value;
onChanged();
} else {
bigquerySourceBuilder_.setMessage(value);
}
sourceCase_ = 2;
return this;
}
/**
*
*
* <pre>
* BigQuery source holds the dataset.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.BigQuerySource bigquery_source = 2;</code>
*/
public Builder setBigquerySource(
com.google.cloud.aiplatform.v1beta1.BigQuerySource.Builder builderForValue) {
if (bigquerySourceBuilder_ == null) {
source_ = builderForValue.build();
onChanged();
} else {
bigquerySourceBuilder_.setMessage(builderForValue.build());
}
sourceCase_ = 2;
return this;
}
/**
*
*
* <pre>
* BigQuery source holds the dataset.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.BigQuerySource bigquery_source = 2;</code>
*/
public Builder mergeBigquerySource(com.google.cloud.aiplatform.v1beta1.BigQuerySource value) {
if (bigquerySourceBuilder_ == null) {
if (sourceCase_ == 2
&& source_ != com.google.cloud.aiplatform.v1beta1.BigQuerySource.getDefaultInstance()) {
source_ =
com.google.cloud.aiplatform.v1beta1.BigQuerySource.newBuilder(
(com.google.cloud.aiplatform.v1beta1.BigQuerySource) source_)
.mergeFrom(value)
.buildPartial();
} else {
source_ = value;
}
onChanged();
} else {
if (sourceCase_ == 2) {
bigquerySourceBuilder_.mergeFrom(value);
} else {
bigquerySourceBuilder_.setMessage(value);
}
}
sourceCase_ = 2;
return this;
}
/**
*
*
* <pre>
* BigQuery source holds the dataset.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.BigQuerySource bigquery_source = 2;</code>
*/
public Builder clearBigquerySource() {
if (bigquerySourceBuilder_ == null) {
if (sourceCase_ == 2) {
sourceCase_ = 0;
source_ = null;
onChanged();
}
} else {
if (sourceCase_ == 2) {
sourceCase_ = 0;
source_ = null;
}
bigquerySourceBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* BigQuery source holds the dataset.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.BigQuerySource bigquery_source = 2;</code>
*/
public com.google.cloud.aiplatform.v1beta1.BigQuerySource.Builder getBigquerySourceBuilder() {
return getBigquerySourceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* BigQuery source holds the dataset.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.BigQuerySource bigquery_source = 2;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.BigQuerySourceOrBuilder
getBigquerySourceOrBuilder() {
if ((sourceCase_ == 2) && (bigquerySourceBuilder_ != null)) {
return bigquerySourceBuilder_.getMessageOrBuilder();
} else {
if (sourceCase_ == 2) {
return (com.google.cloud.aiplatform.v1beta1.BigQuerySource) source_;
}
return com.google.cloud.aiplatform.v1beta1.BigQuerySource.getDefaultInstance();
}
}
/**
*
*
* <pre>
* BigQuery source holds the dataset.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.BigQuerySource bigquery_source = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.BigQuerySource,
com.google.cloud.aiplatform.v1beta1.BigQuerySource.Builder,
com.google.cloud.aiplatform.v1beta1.BigQuerySourceOrBuilder>
getBigquerySourceFieldBuilder() {
if (bigquerySourceBuilder_ == null) {
if (!(sourceCase_ == 2)) {
source_ = com.google.cloud.aiplatform.v1beta1.BigQuerySource.getDefaultInstance();
}
bigquerySourceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.BigQuerySource,
com.google.cloud.aiplatform.v1beta1.BigQuerySource.Builder,
com.google.cloud.aiplatform.v1beta1.BigQuerySourceOrBuilder>(
(com.google.cloud.aiplatform.v1beta1.BigQuerySource) source_,
getParentForChildren(),
isClean());
source_ = null;
}
sourceCase_ = 2;
onChanged();
return bigquerySourceBuilder_;
}
@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.EvaluationDataset)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.EvaluationDataset)
private static final com.google.cloud.aiplatform.v1beta1.EvaluationDataset DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.EvaluationDataset();
}
public static com.google.cloud.aiplatform.v1beta1.EvaluationDataset getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<EvaluationDataset> PARSER =
new com.google.protobuf.AbstractParser<EvaluationDataset>() {
@java.lang.Override
public EvaluationDataset 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<EvaluationDataset> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<EvaluationDataset> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.EvaluationDataset getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,375 | java-scheduler/proto-google-cloud-scheduler-v1/src/main/java/com/google/cloud/scheduler/v1/ListJobsResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/scheduler/v1/cloudscheduler.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.scheduler.v1;
/**
*
*
* <pre>
* Response message for listing jobs using
* [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs].
* </pre>
*
* Protobuf type {@code google.cloud.scheduler.v1.ListJobsResponse}
*/
public final class ListJobsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.scheduler.v1.ListJobsResponse)
ListJobsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListJobsResponse.newBuilder() to construct.
private ListJobsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListJobsResponse() {
jobs_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListJobsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.scheduler.v1.SchedulerProto
.internal_static_google_cloud_scheduler_v1_ListJobsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.scheduler.v1.SchedulerProto
.internal_static_google_cloud_scheduler_v1_ListJobsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.scheduler.v1.ListJobsResponse.class,
com.google.cloud.scheduler.v1.ListJobsResponse.Builder.class);
}
public static final int JOBS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.scheduler.v1.Job> jobs_;
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.scheduler.v1.Job> getJobsList() {
return jobs_;
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.scheduler.v1.JobOrBuilder>
getJobsOrBuilderList() {
return jobs_;
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
@java.lang.Override
public int getJobsCount() {
return jobs_.size();
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
@java.lang.Override
public com.google.cloud.scheduler.v1.Job getJobs(int index) {
return jobs_.get(index);
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
@java.lang.Override
public com.google.cloud.scheduler.v1.JobOrBuilder getJobsOrBuilder(int index) {
return jobs_.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 this value in the
* [page_token][google.cloud.scheduler.v1.ListJobsRequest.page_token] field in
* the subsequent call to
* [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs] to retrieve
* the next page of results. If this is empty it indicates that there are no
* more results through which to paginate.
*
* 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. Pass this value in the
* [page_token][google.cloud.scheduler.v1.ListJobsRequest.page_token] field in
* the subsequent call to
* [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs] to retrieve
* the next page of results. If this is empty it indicates that there are no
* more results through which to paginate.
*
* 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 < jobs_.size(); i++) {
output.writeMessage(1, jobs_.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 < jobs_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, jobs_.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.scheduler.v1.ListJobsResponse)) {
return super.equals(obj);
}
com.google.cloud.scheduler.v1.ListJobsResponse other =
(com.google.cloud.scheduler.v1.ListJobsResponse) obj;
if (!getJobsList().equals(other.getJobsList())) 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 (getJobsCount() > 0) {
hash = (37 * hash) + JOBS_FIELD_NUMBER;
hash = (53 * hash) + getJobsList().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.scheduler.v1.ListJobsResponse parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.scheduler.v1.ListJobsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.scheduler.v1.ListJobsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.scheduler.v1.ListJobsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.scheduler.v1.ListJobsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.scheduler.v1.ListJobsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.scheduler.v1.ListJobsResponse parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.scheduler.v1.ListJobsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.scheduler.v1.ListJobsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.scheduler.v1.ListJobsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.scheduler.v1.ListJobsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.scheduler.v1.ListJobsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.scheduler.v1.ListJobsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response message for listing jobs using
* [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs].
* </pre>
*
* Protobuf type {@code google.cloud.scheduler.v1.ListJobsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.scheduler.v1.ListJobsResponse)
com.google.cloud.scheduler.v1.ListJobsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.scheduler.v1.SchedulerProto
.internal_static_google_cloud_scheduler_v1_ListJobsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.scheduler.v1.SchedulerProto
.internal_static_google_cloud_scheduler_v1_ListJobsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.scheduler.v1.ListJobsResponse.class,
com.google.cloud.scheduler.v1.ListJobsResponse.Builder.class);
}
// Construct using com.google.cloud.scheduler.v1.ListJobsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (jobsBuilder_ == null) {
jobs_ = java.util.Collections.emptyList();
} else {
jobs_ = null;
jobsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.scheduler.v1.SchedulerProto
.internal_static_google_cloud_scheduler_v1_ListJobsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.scheduler.v1.ListJobsResponse getDefaultInstanceForType() {
return com.google.cloud.scheduler.v1.ListJobsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.scheduler.v1.ListJobsResponse build() {
com.google.cloud.scheduler.v1.ListJobsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.scheduler.v1.ListJobsResponse buildPartial() {
com.google.cloud.scheduler.v1.ListJobsResponse result =
new com.google.cloud.scheduler.v1.ListJobsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(com.google.cloud.scheduler.v1.ListJobsResponse result) {
if (jobsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
jobs_ = java.util.Collections.unmodifiableList(jobs_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.jobs_ = jobs_;
} else {
result.jobs_ = jobsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.scheduler.v1.ListJobsResponse 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.scheduler.v1.ListJobsResponse) {
return mergeFrom((com.google.cloud.scheduler.v1.ListJobsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.scheduler.v1.ListJobsResponse other) {
if (other == com.google.cloud.scheduler.v1.ListJobsResponse.getDefaultInstance()) return this;
if (jobsBuilder_ == null) {
if (!other.jobs_.isEmpty()) {
if (jobs_.isEmpty()) {
jobs_ = other.jobs_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureJobsIsMutable();
jobs_.addAll(other.jobs_);
}
onChanged();
}
} else {
if (!other.jobs_.isEmpty()) {
if (jobsBuilder_.isEmpty()) {
jobsBuilder_.dispose();
jobsBuilder_ = null;
jobs_ = other.jobs_;
bitField0_ = (bitField0_ & ~0x00000001);
jobsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getJobsFieldBuilder()
: null;
} else {
jobsBuilder_.addAllMessages(other.jobs_);
}
}
}
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.scheduler.v1.Job m =
input.readMessage(
com.google.cloud.scheduler.v1.Job.parser(), extensionRegistry);
if (jobsBuilder_ == null) {
ensureJobsIsMutable();
jobs_.add(m);
} else {
jobsBuilder_.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.scheduler.v1.Job> jobs_ =
java.util.Collections.emptyList();
private void ensureJobsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
jobs_ = new java.util.ArrayList<com.google.cloud.scheduler.v1.Job>(jobs_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.scheduler.v1.Job,
com.google.cloud.scheduler.v1.Job.Builder,
com.google.cloud.scheduler.v1.JobOrBuilder>
jobsBuilder_;
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public java.util.List<com.google.cloud.scheduler.v1.Job> getJobsList() {
if (jobsBuilder_ == null) {
return java.util.Collections.unmodifiableList(jobs_);
} else {
return jobsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public int getJobsCount() {
if (jobsBuilder_ == null) {
return jobs_.size();
} else {
return jobsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public com.google.cloud.scheduler.v1.Job getJobs(int index) {
if (jobsBuilder_ == null) {
return jobs_.get(index);
} else {
return jobsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public Builder setJobs(int index, com.google.cloud.scheduler.v1.Job value) {
if (jobsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureJobsIsMutable();
jobs_.set(index, value);
onChanged();
} else {
jobsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public Builder setJobs(int index, com.google.cloud.scheduler.v1.Job.Builder builderForValue) {
if (jobsBuilder_ == null) {
ensureJobsIsMutable();
jobs_.set(index, builderForValue.build());
onChanged();
} else {
jobsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public Builder addJobs(com.google.cloud.scheduler.v1.Job value) {
if (jobsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureJobsIsMutable();
jobs_.add(value);
onChanged();
} else {
jobsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public Builder addJobs(int index, com.google.cloud.scheduler.v1.Job value) {
if (jobsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureJobsIsMutable();
jobs_.add(index, value);
onChanged();
} else {
jobsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public Builder addJobs(com.google.cloud.scheduler.v1.Job.Builder builderForValue) {
if (jobsBuilder_ == null) {
ensureJobsIsMutable();
jobs_.add(builderForValue.build());
onChanged();
} else {
jobsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public Builder addJobs(int index, com.google.cloud.scheduler.v1.Job.Builder builderForValue) {
if (jobsBuilder_ == null) {
ensureJobsIsMutable();
jobs_.add(index, builderForValue.build());
onChanged();
} else {
jobsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public Builder addAllJobs(
java.lang.Iterable<? extends com.google.cloud.scheduler.v1.Job> values) {
if (jobsBuilder_ == null) {
ensureJobsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, jobs_);
onChanged();
} else {
jobsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public Builder clearJobs() {
if (jobsBuilder_ == null) {
jobs_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
jobsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public Builder removeJobs(int index) {
if (jobsBuilder_ == null) {
ensureJobsIsMutable();
jobs_.remove(index);
onChanged();
} else {
jobsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public com.google.cloud.scheduler.v1.Job.Builder getJobsBuilder(int index) {
return getJobsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public com.google.cloud.scheduler.v1.JobOrBuilder getJobsOrBuilder(int index) {
if (jobsBuilder_ == null) {
return jobs_.get(index);
} else {
return jobsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public java.util.List<? extends com.google.cloud.scheduler.v1.JobOrBuilder>
getJobsOrBuilderList() {
if (jobsBuilder_ != null) {
return jobsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(jobs_);
}
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public com.google.cloud.scheduler.v1.Job.Builder addJobsBuilder() {
return getJobsFieldBuilder()
.addBuilder(com.google.cloud.scheduler.v1.Job.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public com.google.cloud.scheduler.v1.Job.Builder addJobsBuilder(int index) {
return getJobsFieldBuilder()
.addBuilder(index, com.google.cloud.scheduler.v1.Job.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of jobs.
* </pre>
*
* <code>repeated .google.cloud.scheduler.v1.Job jobs = 1;</code>
*/
public java.util.List<com.google.cloud.scheduler.v1.Job.Builder> getJobsBuilderList() {
return getJobsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.scheduler.v1.Job,
com.google.cloud.scheduler.v1.Job.Builder,
com.google.cloud.scheduler.v1.JobOrBuilder>
getJobsFieldBuilder() {
if (jobsBuilder_ == null) {
jobsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.scheduler.v1.Job,
com.google.cloud.scheduler.v1.Job.Builder,
com.google.cloud.scheduler.v1.JobOrBuilder>(
jobs_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
jobs_ = null;
}
return jobsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token to retrieve next page of results. Pass this value in the
* [page_token][google.cloud.scheduler.v1.ListJobsRequest.page_token] field in
* the subsequent call to
* [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs] to retrieve
* the next page of results. If this is empty it indicates that there are no
* more results through which to paginate.
*
* 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. Pass this value in the
* [page_token][google.cloud.scheduler.v1.ListJobsRequest.page_token] field in
* the subsequent call to
* [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs] to retrieve
* the next page of results. If this is empty it indicates that there are no
* more results through which to paginate.
*
* 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. Pass this value in the
* [page_token][google.cloud.scheduler.v1.ListJobsRequest.page_token] field in
* the subsequent call to
* [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs] to retrieve
* the next page of results. If this is empty it indicates that there are no
* more results through which to paginate.
*
* 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. Pass this value in the
* [page_token][google.cloud.scheduler.v1.ListJobsRequest.page_token] field in
* the subsequent call to
* [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs] to retrieve
* the next page of results. If this is empty it indicates that there are no
* more results through which to paginate.
*
* 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. Pass this value in the
* [page_token][google.cloud.scheduler.v1.ListJobsRequest.page_token] field in
* the subsequent call to
* [ListJobs][google.cloud.scheduler.v1.CloudScheduler.ListJobs] to retrieve
* the next page of results. If this is empty it indicates that there are no
* more results through which to paginate.
*
* 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.scheduler.v1.ListJobsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.scheduler.v1.ListJobsResponse)
private static final com.google.cloud.scheduler.v1.ListJobsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.scheduler.v1.ListJobsResponse();
}
public static com.google.cloud.scheduler.v1.ListJobsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListJobsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListJobsResponse>() {
@java.lang.Override
public ListJobsResponse 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<ListJobsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListJobsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.scheduler.v1.ListJobsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/xmlgraphics-batik | 36,652 | batik-gvt/src/main/java/org/apache/batik/gvt/font/AWTGVTGlyphVector.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.batik.gvt.font;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphJustificationInfo;
import java.awt.font.GlyphMetrics;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.text.AttributedCharacterIterator;
import java.text.CharacterIterator;
import org.apache.batik.gvt.text.ArabicTextHandler;
import org.apache.batik.gvt.text.GVTAttributedCharacterIterator;
import org.apache.batik.gvt.text.TextPaintInfo;
import org.apache.batik.util.Platform;
/**
* This is a wrapper class for a java.awt.font.GlyphVector instance.
*
* @author <a href="mailto:bella.robinson@cmis.csiro.au">Bella Robinson</a>
* @version $Id$
*/
public class AWTGVTGlyphVector implements GVTGlyphVector {
public static final AttributedCharacterIterator.Attribute PAINT_INFO
= GVTAttributedCharacterIterator.TextAttribute.PAINT_INFO;
private GlyphVector awtGlyphVector;
private AWTGVTFont gvtFont;
private CharacterIterator ci;
// This contains the glyphPostions after doing a performDefaultLayout
private Point2D [] defaultGlyphPositions;
private Point2D.Float[] glyphPositions;
// need to keep track of the glyphTransforms since GlyphVector doesn't
// seem to
private AffineTransform[] glyphTransforms;
// these are for caching the glyph outlines
private Shape[] glyphOutlines;
private Shape[] glyphVisualBounds;
private Shape[] glyphLogicalBounds;
private boolean[] glyphVisible;
private GVTGlyphMetrics [] glyphMetrics;
private GeneralPath outline;
private Rectangle2D visualBounds;
private Rectangle2D logicalBounds;
private Rectangle2D bounds2D;
private double scaleFactor;
private float ascent;
private float descent;
private TextPaintInfo cacheTPI;
/**
* Creates and new AWTGVTGlyphVector from the specified GlyphVector and
* AWTGVTFont objects.
*
* @param glyphVector The glyph vector that this one will be based upon.
* @param font The font that is creating this glyph vector.
* @param scaleFactor The scale factor to apply to the glyph vector.
* IMPORTANT: This is only required because the GlyphVector class doesn't
* handle font sizes less than 1 correctly. By using the scale factor we
* can use a GlyphVector created by a larger font and then scale it down to
* the correct size.
* @param ci The character string that this glyph vector represents.
*/
public AWTGVTGlyphVector(GlyphVector glyphVector,
AWTGVTFont font,
double scaleFactor,
CharacterIterator ci) {
this.awtGlyphVector = glyphVector;
this.gvtFont = font;
this.scaleFactor = scaleFactor;
this.ci = ci;
GVTLineMetrics lineMetrics = gvtFont.getLineMetrics
("By", awtGlyphVector.getFontRenderContext());
ascent = lineMetrics.getAscent();
descent = lineMetrics.getDescent();
outline = null;
visualBounds = null;
logicalBounds = null;
bounds2D = null;
int numGlyphs = glyphVector.getNumGlyphs();
glyphPositions = new Point2D.Float [numGlyphs+1];
glyphTransforms = new AffineTransform[numGlyphs];
glyphOutlines = new Shape [numGlyphs];
glyphVisualBounds = new Shape [numGlyphs];
glyphLogicalBounds = new Shape [numGlyphs];
glyphVisible = new boolean [numGlyphs];
glyphMetrics = new GVTGlyphMetrics[numGlyphs];
for (int i = 0; i < numGlyphs; i++) {
glyphVisible[i] = true;
}
}
/**
* Returns the GVTFont associated with this GVTGlyphVector.
*/
public GVTFont getFont() {
return gvtFont;
}
/**
* Returns the FontRenderContext associated with this GlyphVector.
*/
public FontRenderContext getFontRenderContext() {
return awtGlyphVector.getFontRenderContext();
}
/**
* Returns the glyphcode of the specified glyph.
*/
public int getGlyphCode(int glyphIndex) {
return awtGlyphVector.getGlyphCode(glyphIndex);
}
/**
* Returns an array of glyphcodes for the specified glyphs.
*/
public int[] getGlyphCodes(int beginGlyphIndex, int numEntries,
int[] codeReturn) {
return awtGlyphVector.getGlyphCodes(beginGlyphIndex, numEntries,
codeReturn);
}
/**
* Returns the justification information for the glyph at the specified
* index into this GlyphVector.
*/
public GlyphJustificationInfo getGlyphJustificationInfo(int glyphIndex) {
return awtGlyphVector.getGlyphJustificationInfo(glyphIndex);
}
/**
* Returns a tight bounds on the GlyphVector including stroking.
*/
public Rectangle2D getBounds2D(AttributedCharacterIterator aci) {
aci.first();
TextPaintInfo tpi = (TextPaintInfo)aci.getAttribute(PAINT_INFO);
if ((bounds2D != null) &&
TextPaintInfo.equivilent(tpi, cacheTPI))
return bounds2D;
if (tpi == null)
return null;
if (!tpi.visible)
return null;
cacheTPI = new TextPaintInfo(tpi);
Shape outline = null;
if (tpi.fillPaint != null) {
outline = getOutline();
bounds2D = outline.getBounds2D();
}
// check if we need to include the
// outline of this glyph
Stroke stroke = tpi.strokeStroke;
Paint paint = tpi.strokePaint;
if ((stroke != null) && (paint != null)) {
if (outline == null)
outline = getOutline();
Rectangle2D strokeBounds
= stroke.createStrokedShape(outline).getBounds2D();
if (bounds2D == null)
bounds2D = strokeBounds;
else
// bounds2D = bounds2D.createUnion(strokeBounds);
bounds2D.add(strokeBounds);
}
if (bounds2D == null)
return null;
if ((bounds2D.getWidth() == 0) ||
(bounds2D.getHeight() == 0))
bounds2D = null;
return bounds2D;
}
/**
* Returns the logical bounds of this GlyphVector.
* This is a bound useful for hit detection and highlighting.
*/
public Rectangle2D getLogicalBounds() {
if (logicalBounds == null) {
// This fills in logicalBounds...
computeGlyphLogicalBounds();
}
return logicalBounds;
}
/**
* Returns the logical bounds of the specified glyph within this
* GlyphVector.
*/
public Shape getGlyphLogicalBounds(int glyphIndex) {
if (glyphLogicalBounds[glyphIndex] == null &&
glyphVisible[glyphIndex]) {
computeGlyphLogicalBounds();
}
return glyphLogicalBounds[glyphIndex];
}
/**
* Calculates the logical bounds for each glyph. The logical
* bounds are what is used for highlighting the glyphs when
* selected.
*/
private void computeGlyphLogicalBounds() {
Shape[] tempLogicalBounds = new Shape[getNumGlyphs()];
boolean[] rotated = new boolean[getNumGlyphs()];
double maxWidth = -1.0;
double maxHeight = -1.0;
for (int i = 0; i < getNumGlyphs(); i++) {
if (!glyphVisible[i]) {
// the glyph is not drawn
tempLogicalBounds[i] = null;
continue;
}
AffineTransform glyphTransform = getGlyphTransform(i);
GVTGlyphMetrics glyphMetrics = getGlyphMetrics(i);
float glyphX = 0.0f;
float glyphY = (float)(-ascent/scaleFactor);
float glyphWidth = (float)(glyphMetrics.getHorizontalAdvance()/
scaleFactor);
float glyphHeight = (float)(glyphMetrics.getVerticalAdvance()/
scaleFactor);
Rectangle2D glyphBounds = new Rectangle2D.Double(glyphX,
glyphY,
glyphWidth,
glyphHeight);
if (glyphBounds.isEmpty()) {
if (i > 0) {
// can't tell if rotated or not, make it the same as
// the previous glyph
rotated [i] = rotated [i-1];
} else {
rotated [i] = true;
}
} else {
// get three corner points so we can determine
// whether the glyph is rotated
Point2D p1 = new Point2D.Double(glyphBounds.getMinX(),
glyphBounds.getMinY());
Point2D p2 = new Point2D.Double(glyphBounds.getMaxX(),
glyphBounds.getMinY());
Point2D p3 = new Point2D.Double(glyphBounds.getMinX(),
glyphBounds.getMaxY());
Point2D gpos = getGlyphPosition(i);
AffineTransform tr = AffineTransform.getTranslateInstance
(gpos.getX(), gpos.getY());
if (glyphTransform != null)
tr.concatenate(glyphTransform);
tr.scale(scaleFactor, scaleFactor);
tempLogicalBounds[i] = tr.createTransformedShape(glyphBounds);
Point2D tp1 = new Point2D.Double();
Point2D tp2 = new Point2D.Double();
Point2D tp3 = new Point2D.Double();
tr.transform(p1, tp1);
tr.transform(p2, tp2);
tr.transform(p3, tp3);
double tdx12 = tp1.getX()-tp2.getX();
double tdx13 = tp1.getX()-tp3.getX();
double tdy12 = tp1.getY()-tp2.getY();
double tdy13 = tp1.getY()-tp3.getY();
if (((Math.abs(tdx12) < 0.001) && (Math.abs(tdy13) < 0.001)) ||
((Math.abs(tdx13) < 0.001) && (Math.abs(tdy12) < 0.001))) {
// If either of these are zero then it is axially aligned
rotated[i] = false;
} else {
rotated [i] = true;
}
Rectangle2D rectBounds;
rectBounds = tempLogicalBounds[i].getBounds2D();
if (rectBounds.getWidth() > maxWidth)
maxWidth = rectBounds.getWidth();
if (rectBounds.getHeight() > maxHeight)
maxHeight = rectBounds.getHeight();
}
}
// if appropriate, join adjacent glyph logical bounds
GeneralPath logicalBoundsPath = new GeneralPath();
for (int i = 0; i < getNumGlyphs(); i++) {
if (tempLogicalBounds[i] != null) {
logicalBoundsPath.append(tempLogicalBounds[i], false);
}
}
logicalBounds = logicalBoundsPath.getBounds2D();
if (logicalBounds.getHeight() < maxHeight*1.5) {
// make all glyphs tops and bottoms the same as the full bounds
for (int i = 0; i < getNumGlyphs(); i++) {
// first make sure that the glyph logical bounds are
// not rotated
if (rotated[i]) continue;
if (tempLogicalBounds[i] == null) continue;
Rectangle2D glyphBounds = tempLogicalBounds[i].getBounds2D();
double x = glyphBounds.getMinX();
double width = glyphBounds.getWidth();
if ((i < getNumGlyphs()-1) &&
(tempLogicalBounds[i+1] != null)) {
// make this glyph extend to the start of the next one
Rectangle2D ngb = tempLogicalBounds[i+1].getBounds2D();
if (ngb.getX() > x) {
double nw = ngb.getX() - x;
if ((nw < width*1.15) && (nw > width*.85)) {
double delta = (nw-width)*.5;
width += delta;
ngb.setRect(ngb.getX()-delta, ngb.getY(),
ngb.getWidth()+delta, ngb.getHeight());
}
}
}
tempLogicalBounds[i] = new Rectangle2D.Double
(x, logicalBounds.getMinY(),
width, logicalBounds.getHeight());
}
} else if (logicalBounds.getWidth() < maxWidth*1.5) {
// make all glyphs left and right edges the same as the full bounds
for (int i = 0; i < getNumGlyphs(); i++) {
// first make sure that the glyph logical bounds are
// not rotated
if (rotated[i]) continue;
if (tempLogicalBounds[i] == null) continue;
Rectangle2D glyphBounds = tempLogicalBounds[i].getBounds2D();
double y = glyphBounds.getMinY();
double height = glyphBounds.getHeight();
if ((i < getNumGlyphs()-1) &&
(tempLogicalBounds[i+1] != null)) {
// make this glyph extend to the start of the next one
Rectangle2D ngb = tempLogicalBounds[i+1].getBounds2D();
if (ngb.getY() > y) { // going top to bottom
double nh = ngb.getY() - y;
if ((nh < height*1.15) && (nh > height*.85)) {
double delta = (nh-height)*.5;
height += delta;
ngb.setRect(ngb.getX(), ngb.getY()-delta,
ngb.getWidth(), ngb.getHeight()+delta);
}
}
}
tempLogicalBounds[i] = new Rectangle2D.Double
(logicalBounds.getMinX(), y,
logicalBounds.getWidth(), height);
}
}
System.arraycopy( tempLogicalBounds, 0, glyphLogicalBounds, 0, getNumGlyphs() );
}
/**
* Returns the metrics of the glyph at the specified index into this
* GVTGlyphVector.
*/
public GVTGlyphMetrics getGlyphMetrics(int glyphIndex) {
if (glyphMetrics[glyphIndex] != null)
return glyphMetrics[glyphIndex];
// -- start glyph cache code --
Point2D glyphPos = defaultGlyphPositions[glyphIndex];
char c = ci.setIndex(ci.getBeginIndex()+glyphIndex);
ci.setIndex(ci.getBeginIndex());
AWTGlyphGeometryCache.Value v = AWTGVTFont.getGlyphGeometry
(gvtFont, c, awtGlyphVector, glyphIndex, glyphPos);
Rectangle2D gmB = v.getBounds2D();
// -- end glyph cache code --
Rectangle2D bounds = new Rectangle2D.Double
(gmB.getX() * scaleFactor, gmB.getY() * scaleFactor,
gmB.getWidth() * scaleFactor, gmB.getHeight() * scaleFactor);
// defaultGlyphPositions has one more entry than glyphs
// the last entry stores the total advance for the
// glyphVector.
float adv = (float)(defaultGlyphPositions[glyphIndex+1].getX()-
defaultGlyphPositions[glyphIndex] .getX());
glyphMetrics[glyphIndex] = new GVTGlyphMetrics
((float)(adv*scaleFactor), (ascent+descent),
bounds, GlyphMetrics.STANDARD);
return glyphMetrics[glyphIndex];
}
/**
* Returns a Shape whose interior corresponds to the visual representation
* of the specified glyph within this GlyphVector.
*/
public Shape getGlyphOutline(int glyphIndex) {
if (glyphOutlines[glyphIndex] == null) {
/*
Shape glyphOutline = awtGlyphVector.getGlyphOutline(glyphIndex);
*/
// -- start glyph cache code --
Point2D glyphPos = defaultGlyphPositions[glyphIndex];
char c = ci.setIndex(ci.getBeginIndex()+glyphIndex);
ci.setIndex(ci.getBeginIndex());
AWTGlyphGeometryCache.Value v = AWTGVTFont.getGlyphGeometry
(gvtFont, c, awtGlyphVector, glyphIndex, glyphPos);
Shape glyphOutline = v.getOutline();
// -- end glyph cache code --
AffineTransform tr = AffineTransform.getTranslateInstance
(getGlyphPosition(glyphIndex).getX(),
getGlyphPosition(glyphIndex).getY());
AffineTransform glyphTransform = getGlyphTransform(glyphIndex);
if (glyphTransform != null) {
tr.concatenate(glyphTransform);
}
//
// <!> HACK
//
// GlyphVector.getGlyphOutline behavior changes between 1.3 and 1.4
//
// I've looked at this problem a bit more and the incorrect glyph
// positioning in Batik is definitely due to the change in
// behavior of GlyphVector.getGlyphOutline(glyphIndex). It used to
// return the outline of the glyph at position 0,0 which meant
// that we had to translate it to the actual glyph position before
// drawing it. Now, it returns the outline which has already been
// positioned.
//
// -- Bella
//
/*
if (outlinesPositioned()) {
Point2D glyphPos = defaultGlyphPositions[glyphIndex];
tr.translate(-glyphPos.getX(), -glyphPos.getY());
}
*/
tr.scale(scaleFactor, scaleFactor);
glyphOutlines[glyphIndex]=tr.createTransformedShape(glyphOutline);
}
return glyphOutlines[glyphIndex];
}
// This is true if GlyphVector.getGlyphOutline returns glyph outlines
// that are positioned (if it is false the outlines are always at 0,0).
private static final boolean outlinesPositioned;
// This is true if Graphics2D.drawGlyphVector works for the
// current JDK/OS combination.
private static final boolean drawGlyphVectorWorks;
// This is true if Graphics2D.drawGlyphVector will correctly
// render Glyph Vectors with per glyph transforms.
private static final boolean glyphVectorTransformWorks;
static {
String s = System.getProperty("java.specification.version");
if ("1.6".compareTo(s) <= 0) {
outlinesPositioned = true;
drawGlyphVectorWorks = false; // [GA] not verified; needs further research
glyphVectorTransformWorks = true;
} else if ("1.4".compareTo(s) <= 0) {
// TODO Java 5
outlinesPositioned = true;
drawGlyphVectorWorks = true;
glyphVectorTransformWorks = true;
} else if (Platform.isOSX) {
outlinesPositioned = true;
drawGlyphVectorWorks = false;
glyphVectorTransformWorks = false;
} else {
outlinesPositioned = false;
drawGlyphVectorWorks = true;
glyphVectorTransformWorks = false;
}
}
// Returns true if GlyphVector.getGlyphOutlines returns glyph outlines
// that are positioned (otherwise they are always at 0,0).
static boolean outlinesPositioned() {
return outlinesPositioned;
}
/**
* Returns the bounding box of the specified glyph, considering only the
* glyph's metrics (ascent, descent, advance) rather than the actual glyph
* shape.
*/
public Rectangle2D getGlyphCellBounds(int glyphIndex) {
return getGlyphLogicalBounds(glyphIndex).getBounds2D();
}
/**
* Returns the position of the specified glyph within this GlyphVector.
*/
public Point2D getGlyphPosition(int glyphIndex) {
return glyphPositions[glyphIndex];
}
/**
* Returns an array of glyph positions for the specified glyphs
*/
public float[] getGlyphPositions(int beginGlyphIndex,
int numEntries,
float[] positionReturn) {
if (positionReturn == null) {
positionReturn = new float[numEntries*2];
}
for (int i = beginGlyphIndex; i < (beginGlyphIndex+numEntries); i++) {
Point2D glyphPos = getGlyphPosition(i);
positionReturn[(i-beginGlyphIndex)*2] = (float)glyphPos.getX();
positionReturn[(i-beginGlyphIndex)*2 + 1] = (float)glyphPos.getY();
}
return positionReturn;
}
/**
* Gets the transform of the specified glyph within this GlyphVector.
*/
public AffineTransform getGlyphTransform(int glyphIndex) {
return glyphTransforms[glyphIndex];
}
/**
* Returns the visual bounds of the specified glyph within the GlyphVector.
*/
public Shape getGlyphVisualBounds(int glyphIndex) {
if (glyphVisualBounds[glyphIndex] == null) {
/*
Shape glyphOutline = awtGlyphVector.getGlyphOutline(glyphIndex);
Rectangle2D glyphBounds = glyphOutline.getBounds2D();
*/
// -- start glyph cache code --
Point2D glyphPos = defaultGlyphPositions[glyphIndex];
char c = ci.setIndex(ci.getBeginIndex()+glyphIndex);
ci.setIndex(ci.getBeginIndex());
AWTGlyphGeometryCache.Value v = AWTGVTFont.getGlyphGeometry
(gvtFont, c, awtGlyphVector, glyphIndex, glyphPos);
Rectangle2D glyphBounds = v.getOutlineBounds2D();
// -- end glyph cache code --
AffineTransform tr = AffineTransform.getTranslateInstance
(getGlyphPosition(glyphIndex).getX(),
getGlyphPosition(glyphIndex).getY());
AffineTransform glyphTransform = getGlyphTransform(glyphIndex);
if (glyphTransform != null) {
tr.concatenate(glyphTransform);
}
tr.scale(scaleFactor, scaleFactor);
glyphVisualBounds[glyphIndex] =
tr.createTransformedShape(glyphBounds);
}
return glyphVisualBounds[glyphIndex];
}
/**
* Returns the number of glyphs in this GlyphVector.
*/
public int getNumGlyphs() {
return awtGlyphVector.getNumGlyphs();
}
/**
* Returns a Shape whose interior corresponds to the visual representation
* of this GlyphVector.
*/
public Shape getOutline() {
if (outline != null)
return outline;
outline = new GeneralPath();
for (int i = 0; i < getNumGlyphs(); i++) {
if (glyphVisible[i]) {
Shape glyphOutline = getGlyphOutline(i);
outline.append(glyphOutline, false);
}
}
return outline;
}
/**
* Returns a Shape whose interior corresponds to the visual representation
* of this GlyphVector, offset to x, y.
*/
public Shape getOutline(float x, float y) {
Shape outline = getOutline();
AffineTransform tr = AffineTransform.getTranslateInstance(x,y);
outline = tr.createTransformedShape(outline);
return outline;
}
/**
* Returns the visual bounds of this GlyphVector The visual bounds is the
* tightest rectangle enclosing all non-background pixels in the rendered
* representation of this GlyphVector.
*/
public Rectangle2D getGeometricBounds() {
if (visualBounds == null) {
Shape outline = getOutline();
visualBounds = outline.getBounds2D();
}
return visualBounds;
}
/**
* Assigns default positions to each glyph in this GlyphVector.
*/
public void performDefaultLayout() {
if (defaultGlyphPositions == null) {
awtGlyphVector.performDefaultLayout();
defaultGlyphPositions = new Point2D.Float[getNumGlyphs()+1];
for (int i = 0; i <= getNumGlyphs(); i++)
defaultGlyphPositions[i] = awtGlyphVector.getGlyphPosition(i);
}
outline = null;
visualBounds = null;
logicalBounds = null;
bounds2D = null;
float shiftLeft = 0;
int i=0;
for (; i < getNumGlyphs(); i++) {
glyphTransforms [i] = null;
glyphVisualBounds [i] = null;
glyphLogicalBounds[i] = null;
glyphOutlines [i] = null;
glyphMetrics [i] = null;
Point2D glyphPos = defaultGlyphPositions[i];
float x = (float)((glyphPos.getX() * scaleFactor)-shiftLeft);
float y = (float) (glyphPos.getY() * scaleFactor);
// if c is a transparent arabic char then need to shift the
// following glyphs left so that the current glyph is overwritten
/*char c =*/ ci.setIndex(i + ci.getBeginIndex());
/*
if (ArabicTextHandler.arabicCharTransparent(c)) {
int j;
shiftLeft += getGlyphMetrics(i).getHorizontalAdvance();
for (j=i+1; j<getNumGlyphs(); j++) {
char c2 = ci.setIndex(j+ci.getBeginIndex());
if (!ArabicTextHandler.arabicCharTransparent(c2)) break;
shiftLeft += getGlyphMetrics(j).getHorizontalAdvance();
}
if (j != getNumGlyphs()) {
Point2D glyphPosBase = defaultGlyphPositions[j];
double rEdge = glyphPosBase.getX()+getGlyphMetrics(j).getHorizontalAdvance();
rEdge -= shiftLeft;
for (int k=i; k<j; k++) {
glyphTransforms [k] = null;
glyphVisualBounds [k] = null;
glyphLogicalBounds[k] = null;
glyphOutlines [k] = null;
glyphMetrics [k] = null;
x = (float)rEdge-getGlyphMetrics(k).getHorizontalAdvance();
y = (float) (defaultGlyphPositions[k].getY() * scaleFactor);
if (glyphPositions[k] == null) {
glyphPositions[k] = new Point2D.Float(x,y);
} else {
glyphPositions[k].x = x;
glyphPositions[k].y = y;
}
}
i = j-1;
}
} else {
*/
if (glyphPositions[i] == null) {
glyphPositions[i] = new Point2D.Float(x,y);
} else {
glyphPositions[i].x = x;
glyphPositions[i].y = y;
}
// }
}
// Need glyph pos for point after last char...
Point2D glyphPos = defaultGlyphPositions[i];
glyphPositions[i] = new Point2D.Float
((float)((glyphPos.getX() * scaleFactor)-shiftLeft),
(float) (glyphPos.getY() * scaleFactor));
}
/**
* Sets the position of the specified glyph within this GlyphVector.
*/
public void setGlyphPosition(int glyphIndex, Point2D newPos) {
glyphPositions[glyphIndex].x = (float)newPos.getX();
glyphPositions[glyphIndex].y = (float)newPos.getY();
outline = null;
visualBounds = null;
logicalBounds = null;
bounds2D = null;
if (glyphIndex != getNumGlyphs()) {
glyphVisualBounds [glyphIndex] = null;
glyphLogicalBounds[glyphIndex] = null;
glyphOutlines [glyphIndex] = null;
glyphMetrics [glyphIndex] = null;
}
}
/**
* Sets the transform of the specified glyph within this GlyphVector.
*/
public void setGlyphTransform(int glyphIndex, AffineTransform newTX) {
glyphTransforms[glyphIndex] = newTX;
outline = null;
visualBounds = null;
logicalBounds = null;
bounds2D = null;
glyphVisualBounds [glyphIndex] = null;
glyphLogicalBounds[glyphIndex] = null;
glyphOutlines [glyphIndex] = null;
glyphMetrics [glyphIndex] = null;
}
/**
* Tells the glyph vector whether or not to draw the specified glyph.
*/
public void setGlyphVisible(int glyphIndex, boolean visible) {
if (visible == glyphVisible[glyphIndex])
return;
glyphVisible[glyphIndex] = visible;
outline = null;
visualBounds = null;
logicalBounds = null;
bounds2D = null;
glyphVisualBounds [glyphIndex] = null;
glyphLogicalBounds[glyphIndex] = null;
glyphOutlines [glyphIndex] = null;
glyphMetrics [glyphIndex] = null;
}
/**
* Returns true if specified glyph will be rendered.
*/
public boolean isGlyphVisible(int glyphIndex) {
return glyphVisible[glyphIndex];
}
/**
* Returns the number of chars represented by the glyphs within the
* specified range.
*
* @param startGlyphIndex The index of the first glyph in the range.
* @param endGlyphIndex The index of the last glyph in the range.
* @return The number of chars.
*/
public int getCharacterCount(int startGlyphIndex, int endGlyphIndex) {
if (startGlyphIndex < 0) {
startGlyphIndex = 0;
}
if (endGlyphIndex >= getNumGlyphs()) {
endGlyphIndex = getNumGlyphs()-1;
}
int charCount = 0;
int start = startGlyphIndex+ci.getBeginIndex();
int end = endGlyphIndex+ci.getBeginIndex();
for (char c = ci.setIndex(start); ci.getIndex() <= end; c=ci.next()) {
charCount += ArabicTextHandler.getNumChars(c);
}
return charCount;
}
@Override
public boolean isReversed() {
return false;
}
@Override
public void maybeReverse(boolean mirror) {
}
/**
* Draws this glyph vector.
*/
public void draw(Graphics2D graphics2D,
AttributedCharacterIterator aci) {
int numGlyphs = getNumGlyphs();
aci.first();
TextPaintInfo tpi = (TextPaintInfo)aci.getAttribute
(GVTAttributedCharacterIterator.TextAttribute.PAINT_INFO);
if (tpi == null) return;
if (!tpi.visible) return;
Paint fillPaint = tpi.fillPaint;
Stroke stroke = tpi.strokeStroke;
Paint strokePaint = tpi.strokePaint;
if ((fillPaint == null) && ((strokePaint == null) ||
(stroke == null)))
return;
boolean useHinting = drawGlyphVectorWorks;
if (useHinting && (stroke != null) && (strokePaint != null))
// Can't stroke with drawGlyphVector.
useHinting = false;
if (useHinting &&
(fillPaint != null) && !(fillPaint instanceof Color))
// The coordinate system is different for drawGlyphVector.
// So complex paints aren't positioned properly.
useHinting = false;
if (useHinting) {
Object v1 = graphics2D.getRenderingHint
(RenderingHints.KEY_TEXT_ANTIALIASING);
Object v2 = graphics2D.getRenderingHint
(RenderingHints.KEY_STROKE_CONTROL);
// text-rendering = geometricPrecision so fill shapes.
if ((v1 == RenderingHints.VALUE_TEXT_ANTIALIAS_ON) &&
(v2 == RenderingHints.VALUE_STROKE_PURE))
useHinting = false;
}
final int typeGRot = AffineTransform.TYPE_GENERAL_ROTATION;
final int typeGTrans = AffineTransform.TYPE_GENERAL_TRANSFORM;
if (useHinting) {
// Check if usr->dev transform has general rotation,
// or shear..
AffineTransform at = graphics2D.getTransform();
int type = at.getType();
if (((type & typeGTrans) != 0) || ((type & typeGRot) != 0))
useHinting = false;
}
if (useHinting) {
for (int i=0; i<numGlyphs; i++) {
if (!glyphVisible[i]) {
useHinting = false;
break;
}
AffineTransform at = glyphTransforms[i];
if (at != null) {
int type = at.getType();
if ((type & ~AffineTransform.TYPE_TRANSLATION) == 0) {
// Just translation
} else if (glyphVectorTransformWorks &&
((type & typeGTrans) == 0) &&
((type & typeGRot) == 0)) {
// It's a simple 90Deg rotate, and we can put
// it into the GlyphVector.
} else {
// we can't (or it doesn't make sense
// to use the GlyphVector.
useHinting = false;
break;
}
}
}
}
if (useHinting) {
double sf = scaleFactor;
double [] mat = new double[6];
for (int i=0; i< numGlyphs; i++) {
Point2D pos = glyphPositions[i];
double x = pos.getX();
double y = pos.getY();
AffineTransform at = glyphTransforms[i];
if (at != null) {
// Scale the translate portion of matrix,
// and add it into the position.
at.getMatrix(mat);
x += mat[4];
y += mat[5];
if ((mat[0] != 1) || (mat[1] != 0) ||
(mat[2] != 0) || (mat[3] != 1)) {
// More than just translation.
mat[4] = 0; mat[5] = 0;
at = new AffineTransform(mat);
} else {
at = null;
}
}
pos = new Point2D.Double(x/sf, y/sf);
awtGlyphVector.setGlyphPosition(i, pos);
awtGlyphVector.setGlyphTransform(i, at);
}
graphics2D.scale(sf, sf);
graphics2D.setPaint(fillPaint);
graphics2D.drawGlyphVector(awtGlyphVector, 0.0f, 0.0f);
graphics2D.scale(1.0/sf, 1.0/sf);
for (int i=0; i< numGlyphs; i++) {
Point2D pos = defaultGlyphPositions[i];
awtGlyphVector.setGlyphPosition(i, pos);
awtGlyphVector.setGlyphTransform(i, null);
}
} else {
Shape outline = getOutline();
// check if we need to fill this glyph
if (fillPaint != null) {
graphics2D.setPaint(fillPaint);
graphics2D.fill(outline);
}
// check if we need to draw the outline of this glyph
if (stroke != null && strokePaint != null) {
graphics2D.setStroke(stroke);
graphics2D.setPaint(strokePaint);
graphics2D.draw(outline);
}
}
}
}
|
googleapis/google-cloud-java | 36,598 | java-dialogflow-cx/grpc-google-cloud-dialogflow-cx-v3/src/main/java/com/google/cloud/dialogflow/cx/v3/GeneratorsGrpc.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.dialogflow.cx.v3;
import static io.grpc.MethodDescriptor.generateFullMethodName;
/**
*
*
* <pre>
* Service for managing [Generators][google.cloud.dialogflow.cx.v3.Generator]
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler",
comments = "Source: google/cloud/dialogflow/cx/v3/generator.proto")
@io.grpc.stub.annotations.GrpcGenerated
public final class GeneratorsGrpc {
private GeneratorsGrpc() {}
public static final java.lang.String SERVICE_NAME = "google.cloud.dialogflow.cx.v3.Generators";
// Static method descriptors that strictly reflect the proto.
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.cx.v3.ListGeneratorsRequest,
com.google.cloud.dialogflow.cx.v3.ListGeneratorsResponse>
getListGeneratorsMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "ListGenerators",
requestType = com.google.cloud.dialogflow.cx.v3.ListGeneratorsRequest.class,
responseType = com.google.cloud.dialogflow.cx.v3.ListGeneratorsResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.cx.v3.ListGeneratorsRequest,
com.google.cloud.dialogflow.cx.v3.ListGeneratorsResponse>
getListGeneratorsMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.cx.v3.ListGeneratorsRequest,
com.google.cloud.dialogflow.cx.v3.ListGeneratorsResponse>
getListGeneratorsMethod;
if ((getListGeneratorsMethod = GeneratorsGrpc.getListGeneratorsMethod) == null) {
synchronized (GeneratorsGrpc.class) {
if ((getListGeneratorsMethod = GeneratorsGrpc.getListGeneratorsMethod) == null) {
GeneratorsGrpc.getListGeneratorsMethod =
getListGeneratorsMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.cx.v3.ListGeneratorsRequest,
com.google.cloud.dialogflow.cx.v3.ListGeneratorsResponse>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "ListGenerators"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.cx.v3.ListGeneratorsRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.cx.v3.ListGeneratorsResponse
.getDefaultInstance()))
.setSchemaDescriptor(new GeneratorsMethodDescriptorSupplier("ListGenerators"))
.build();
}
}
}
return getListGeneratorsMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.cx.v3.GetGeneratorRequest,
com.google.cloud.dialogflow.cx.v3.Generator>
getGetGeneratorMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "GetGenerator",
requestType = com.google.cloud.dialogflow.cx.v3.GetGeneratorRequest.class,
responseType = com.google.cloud.dialogflow.cx.v3.Generator.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.cx.v3.GetGeneratorRequest,
com.google.cloud.dialogflow.cx.v3.Generator>
getGetGeneratorMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.cx.v3.GetGeneratorRequest,
com.google.cloud.dialogflow.cx.v3.Generator>
getGetGeneratorMethod;
if ((getGetGeneratorMethod = GeneratorsGrpc.getGetGeneratorMethod) == null) {
synchronized (GeneratorsGrpc.class) {
if ((getGetGeneratorMethod = GeneratorsGrpc.getGetGeneratorMethod) == null) {
GeneratorsGrpc.getGetGeneratorMethod =
getGetGeneratorMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.cx.v3.GetGeneratorRequest,
com.google.cloud.dialogflow.cx.v3.Generator>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetGenerator"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.cx.v3.GetGeneratorRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.cx.v3.Generator.getDefaultInstance()))
.setSchemaDescriptor(new GeneratorsMethodDescriptorSupplier("GetGenerator"))
.build();
}
}
}
return getGetGeneratorMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.cx.v3.CreateGeneratorRequest,
com.google.cloud.dialogflow.cx.v3.Generator>
getCreateGeneratorMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "CreateGenerator",
requestType = com.google.cloud.dialogflow.cx.v3.CreateGeneratorRequest.class,
responseType = com.google.cloud.dialogflow.cx.v3.Generator.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.cx.v3.CreateGeneratorRequest,
com.google.cloud.dialogflow.cx.v3.Generator>
getCreateGeneratorMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.cx.v3.CreateGeneratorRequest,
com.google.cloud.dialogflow.cx.v3.Generator>
getCreateGeneratorMethod;
if ((getCreateGeneratorMethod = GeneratorsGrpc.getCreateGeneratorMethod) == null) {
synchronized (GeneratorsGrpc.class) {
if ((getCreateGeneratorMethod = GeneratorsGrpc.getCreateGeneratorMethod) == null) {
GeneratorsGrpc.getCreateGeneratorMethod =
getCreateGeneratorMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.cx.v3.CreateGeneratorRequest,
com.google.cloud.dialogflow.cx.v3.Generator>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "CreateGenerator"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.cx.v3.CreateGeneratorRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.cx.v3.Generator.getDefaultInstance()))
.setSchemaDescriptor(
new GeneratorsMethodDescriptorSupplier("CreateGenerator"))
.build();
}
}
}
return getCreateGeneratorMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.cx.v3.UpdateGeneratorRequest,
com.google.cloud.dialogflow.cx.v3.Generator>
getUpdateGeneratorMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "UpdateGenerator",
requestType = com.google.cloud.dialogflow.cx.v3.UpdateGeneratorRequest.class,
responseType = com.google.cloud.dialogflow.cx.v3.Generator.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.cx.v3.UpdateGeneratorRequest,
com.google.cloud.dialogflow.cx.v3.Generator>
getUpdateGeneratorMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.cx.v3.UpdateGeneratorRequest,
com.google.cloud.dialogflow.cx.v3.Generator>
getUpdateGeneratorMethod;
if ((getUpdateGeneratorMethod = GeneratorsGrpc.getUpdateGeneratorMethod) == null) {
synchronized (GeneratorsGrpc.class) {
if ((getUpdateGeneratorMethod = GeneratorsGrpc.getUpdateGeneratorMethod) == null) {
GeneratorsGrpc.getUpdateGeneratorMethod =
getUpdateGeneratorMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.cx.v3.UpdateGeneratorRequest,
com.google.cloud.dialogflow.cx.v3.Generator>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "UpdateGenerator"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.cx.v3.UpdateGeneratorRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.cx.v3.Generator.getDefaultInstance()))
.setSchemaDescriptor(
new GeneratorsMethodDescriptorSupplier("UpdateGenerator"))
.build();
}
}
}
return getUpdateGeneratorMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.cx.v3.DeleteGeneratorRequest, com.google.protobuf.Empty>
getDeleteGeneratorMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "DeleteGenerator",
requestType = com.google.cloud.dialogflow.cx.v3.DeleteGeneratorRequest.class,
responseType = com.google.protobuf.Empty.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.cx.v3.DeleteGeneratorRequest, com.google.protobuf.Empty>
getDeleteGeneratorMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.cx.v3.DeleteGeneratorRequest, com.google.protobuf.Empty>
getDeleteGeneratorMethod;
if ((getDeleteGeneratorMethod = GeneratorsGrpc.getDeleteGeneratorMethod) == null) {
synchronized (GeneratorsGrpc.class) {
if ((getDeleteGeneratorMethod = GeneratorsGrpc.getDeleteGeneratorMethod) == null) {
GeneratorsGrpc.getDeleteGeneratorMethod =
getDeleteGeneratorMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.cx.v3.DeleteGeneratorRequest,
com.google.protobuf.Empty>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "DeleteGenerator"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.cx.v3.DeleteGeneratorRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.protobuf.Empty.getDefaultInstance()))
.setSchemaDescriptor(
new GeneratorsMethodDescriptorSupplier("DeleteGenerator"))
.build();
}
}
}
return getDeleteGeneratorMethod;
}
/** Creates a new async stub that supports all call types for the service */
public static GeneratorsStub newStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<GeneratorsStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<GeneratorsStub>() {
@java.lang.Override
public GeneratorsStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GeneratorsStub(channel, callOptions);
}
};
return GeneratorsStub.newStub(factory, channel);
}
/** Creates a new blocking-style stub that supports all types of calls on the service */
public static GeneratorsBlockingV2Stub newBlockingV2Stub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<GeneratorsBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<GeneratorsBlockingV2Stub>() {
@java.lang.Override
public GeneratorsBlockingV2Stub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GeneratorsBlockingV2Stub(channel, callOptions);
}
};
return GeneratorsBlockingV2Stub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static GeneratorsBlockingStub newBlockingStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<GeneratorsBlockingStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<GeneratorsBlockingStub>() {
@java.lang.Override
public GeneratorsBlockingStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GeneratorsBlockingStub(channel, callOptions);
}
};
return GeneratorsBlockingStub.newStub(factory, channel);
}
/** Creates a new ListenableFuture-style stub that supports unary calls on the service */
public static GeneratorsFutureStub newFutureStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<GeneratorsFutureStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<GeneratorsFutureStub>() {
@java.lang.Override
public GeneratorsFutureStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GeneratorsFutureStub(channel, callOptions);
}
};
return GeneratorsFutureStub.newStub(factory, channel);
}
/**
*
*
* <pre>
* Service for managing [Generators][google.cloud.dialogflow.cx.v3.Generator]
* </pre>
*/
public interface AsyncService {
/**
*
*
* <pre>
* Returns the list of all generators in the specified agent.
* </pre>
*/
default void listGenerators(
com.google.cloud.dialogflow.cx.v3.ListGeneratorsRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.cx.v3.ListGeneratorsResponse>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getListGeneratorsMethod(), responseObserver);
}
/**
*
*
* <pre>
* Retrieves the specified generator.
* </pre>
*/
default void getGenerator(
com.google.cloud.dialogflow.cx.v3.GetGeneratorRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.cx.v3.Generator> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getGetGeneratorMethod(), responseObserver);
}
/**
*
*
* <pre>
* Creates a generator in the specified agent.
* </pre>
*/
default void createGenerator(
com.google.cloud.dialogflow.cx.v3.CreateGeneratorRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.cx.v3.Generator> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getCreateGeneratorMethod(), responseObserver);
}
/**
*
*
* <pre>
* Update the specified generator.
* </pre>
*/
default void updateGenerator(
com.google.cloud.dialogflow.cx.v3.UpdateGeneratorRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.cx.v3.Generator> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getUpdateGeneratorMethod(), responseObserver);
}
/**
*
*
* <pre>
* Deletes the specified generators.
* </pre>
*/
default void deleteGenerator(
com.google.cloud.dialogflow.cx.v3.DeleteGeneratorRequest request,
io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getDeleteGeneratorMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service Generators.
*
* <pre>
* Service for managing [Generators][google.cloud.dialogflow.cx.v3.Generator]
* </pre>
*/
public abstract static class GeneratorsImplBase implements io.grpc.BindableService, AsyncService {
@java.lang.Override
public final io.grpc.ServerServiceDefinition bindService() {
return GeneratorsGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service Generators.
*
* <pre>
* Service for managing [Generators][google.cloud.dialogflow.cx.v3.Generator]
* </pre>
*/
public static final class GeneratorsStub extends io.grpc.stub.AbstractAsyncStub<GeneratorsStub> {
private GeneratorsStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected GeneratorsStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GeneratorsStub(channel, callOptions);
}
/**
*
*
* <pre>
* Returns the list of all generators in the specified agent.
* </pre>
*/
public void listGenerators(
com.google.cloud.dialogflow.cx.v3.ListGeneratorsRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.cx.v3.ListGeneratorsResponse>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getListGeneratorsMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Retrieves the specified generator.
* </pre>
*/
public void getGenerator(
com.google.cloud.dialogflow.cx.v3.GetGeneratorRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.cx.v3.Generator> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getGetGeneratorMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Creates a generator in the specified agent.
* </pre>
*/
public void createGenerator(
com.google.cloud.dialogflow.cx.v3.CreateGeneratorRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.cx.v3.Generator> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getCreateGeneratorMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Update the specified generator.
* </pre>
*/
public void updateGenerator(
com.google.cloud.dialogflow.cx.v3.UpdateGeneratorRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.cx.v3.Generator> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getUpdateGeneratorMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Deletes the specified generators.
* </pre>
*/
public void deleteGenerator(
com.google.cloud.dialogflow.cx.v3.DeleteGeneratorRequest request,
io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getDeleteGeneratorMethod(), getCallOptions()),
request,
responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service Generators.
*
* <pre>
* Service for managing [Generators][google.cloud.dialogflow.cx.v3.Generator]
* </pre>
*/
public static final class GeneratorsBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<GeneratorsBlockingV2Stub> {
private GeneratorsBlockingV2Stub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected GeneratorsBlockingV2Stub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GeneratorsBlockingV2Stub(channel, callOptions);
}
/**
*
*
* <pre>
* Returns the list of all generators in the specified agent.
* </pre>
*/
public com.google.cloud.dialogflow.cx.v3.ListGeneratorsResponse listGenerators(
com.google.cloud.dialogflow.cx.v3.ListGeneratorsRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getListGeneratorsMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Retrieves the specified generator.
* </pre>
*/
public com.google.cloud.dialogflow.cx.v3.Generator getGenerator(
com.google.cloud.dialogflow.cx.v3.GetGeneratorRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetGeneratorMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Creates a generator in the specified agent.
* </pre>
*/
public com.google.cloud.dialogflow.cx.v3.Generator createGenerator(
com.google.cloud.dialogflow.cx.v3.CreateGeneratorRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCreateGeneratorMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Update the specified generator.
* </pre>
*/
public com.google.cloud.dialogflow.cx.v3.Generator updateGenerator(
com.google.cloud.dialogflow.cx.v3.UpdateGeneratorRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUpdateGeneratorMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Deletes the specified generators.
* </pre>
*/
public com.google.protobuf.Empty deleteGenerator(
com.google.cloud.dialogflow.cx.v3.DeleteGeneratorRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getDeleteGeneratorMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do limited synchronous rpc calls to service Generators.
*
* <pre>
* Service for managing [Generators][google.cloud.dialogflow.cx.v3.Generator]
* </pre>
*/
public static final class GeneratorsBlockingStub
extends io.grpc.stub.AbstractBlockingStub<GeneratorsBlockingStub> {
private GeneratorsBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected GeneratorsBlockingStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GeneratorsBlockingStub(channel, callOptions);
}
/**
*
*
* <pre>
* Returns the list of all generators in the specified agent.
* </pre>
*/
public com.google.cloud.dialogflow.cx.v3.ListGeneratorsResponse listGenerators(
com.google.cloud.dialogflow.cx.v3.ListGeneratorsRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getListGeneratorsMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Retrieves the specified generator.
* </pre>
*/
public com.google.cloud.dialogflow.cx.v3.Generator getGenerator(
com.google.cloud.dialogflow.cx.v3.GetGeneratorRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetGeneratorMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Creates a generator in the specified agent.
* </pre>
*/
public com.google.cloud.dialogflow.cx.v3.Generator createGenerator(
com.google.cloud.dialogflow.cx.v3.CreateGeneratorRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCreateGeneratorMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Update the specified generator.
* </pre>
*/
public com.google.cloud.dialogflow.cx.v3.Generator updateGenerator(
com.google.cloud.dialogflow.cx.v3.UpdateGeneratorRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUpdateGeneratorMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Deletes the specified generators.
* </pre>
*/
public com.google.protobuf.Empty deleteGenerator(
com.google.cloud.dialogflow.cx.v3.DeleteGeneratorRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getDeleteGeneratorMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service Generators.
*
* <pre>
* Service for managing [Generators][google.cloud.dialogflow.cx.v3.Generator]
* </pre>
*/
public static final class GeneratorsFutureStub
extends io.grpc.stub.AbstractFutureStub<GeneratorsFutureStub> {
private GeneratorsFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected GeneratorsFutureStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GeneratorsFutureStub(channel, callOptions);
}
/**
*
*
* <pre>
* Returns the list of all generators in the specified agent.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.dialogflow.cx.v3.ListGeneratorsResponse>
listGenerators(com.google.cloud.dialogflow.cx.v3.ListGeneratorsRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getListGeneratorsMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Retrieves the specified generator.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.dialogflow.cx.v3.Generator>
getGenerator(com.google.cloud.dialogflow.cx.v3.GetGeneratorRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getGetGeneratorMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Creates a generator in the specified agent.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.dialogflow.cx.v3.Generator>
createGenerator(com.google.cloud.dialogflow.cx.v3.CreateGeneratorRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getCreateGeneratorMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Update the specified generator.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.dialogflow.cx.v3.Generator>
updateGenerator(com.google.cloud.dialogflow.cx.v3.UpdateGeneratorRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getUpdateGeneratorMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Deletes the specified generators.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.google.protobuf.Empty>
deleteGenerator(com.google.cloud.dialogflow.cx.v3.DeleteGeneratorRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getDeleteGeneratorMethod(), getCallOptions()), request);
}
}
private static final int METHODID_LIST_GENERATORS = 0;
private static final int METHODID_GET_GENERATOR = 1;
private static final int METHODID_CREATE_GENERATOR = 2;
private static final int METHODID_UPDATE_GENERATOR = 3;
private static final int METHODID_DELETE_GENERATOR = 4;
private static final class MethodHandlers<Req, Resp>
implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final AsyncService serviceImpl;
private final int methodId;
MethodHandlers(AsyncService serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_LIST_GENERATORS:
serviceImpl.listGenerators(
(com.google.cloud.dialogflow.cx.v3.ListGeneratorsRequest) request,
(io.grpc.stub.StreamObserver<
com.google.cloud.dialogflow.cx.v3.ListGeneratorsResponse>)
responseObserver);
break;
case METHODID_GET_GENERATOR:
serviceImpl.getGenerator(
(com.google.cloud.dialogflow.cx.v3.GetGeneratorRequest) request,
(io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.cx.v3.Generator>)
responseObserver);
break;
case METHODID_CREATE_GENERATOR:
serviceImpl.createGenerator(
(com.google.cloud.dialogflow.cx.v3.CreateGeneratorRequest) request,
(io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.cx.v3.Generator>)
responseObserver);
break;
case METHODID_UPDATE_GENERATOR:
serviceImpl.updateGenerator(
(com.google.cloud.dialogflow.cx.v3.UpdateGeneratorRequest) request,
(io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.cx.v3.Generator>)
responseObserver);
break;
case METHODID_DELETE_GENERATOR:
serviceImpl.deleteGenerator(
(com.google.cloud.dialogflow.cx.v3.DeleteGeneratorRequest) request,
(io.grpc.stub.StreamObserver<com.google.protobuf.Empty>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getListGeneratorsMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.cx.v3.ListGeneratorsRequest,
com.google.cloud.dialogflow.cx.v3.ListGeneratorsResponse>(
service, METHODID_LIST_GENERATORS)))
.addMethod(
getGetGeneratorMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.cx.v3.GetGeneratorRequest,
com.google.cloud.dialogflow.cx.v3.Generator>(service, METHODID_GET_GENERATOR)))
.addMethod(
getCreateGeneratorMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.cx.v3.CreateGeneratorRequest,
com.google.cloud.dialogflow.cx.v3.Generator>(
service, METHODID_CREATE_GENERATOR)))
.addMethod(
getUpdateGeneratorMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.cx.v3.UpdateGeneratorRequest,
com.google.cloud.dialogflow.cx.v3.Generator>(
service, METHODID_UPDATE_GENERATOR)))
.addMethod(
getDeleteGeneratorMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.cx.v3.DeleteGeneratorRequest,
com.google.protobuf.Empty>(service, METHODID_DELETE_GENERATOR)))
.build();
}
private abstract static class GeneratorsBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoFileDescriptorSupplier,
io.grpc.protobuf.ProtoServiceDescriptorSupplier {
GeneratorsBaseDescriptorSupplier() {}
@java.lang.Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return com.google.cloud.dialogflow.cx.v3.GeneratorProto.getDescriptor();
}
@java.lang.Override
public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() {
return getFileDescriptor().findServiceByName("Generators");
}
}
private static final class GeneratorsFileDescriptorSupplier
extends GeneratorsBaseDescriptorSupplier {
GeneratorsFileDescriptorSupplier() {}
}
private static final class GeneratorsMethodDescriptorSupplier
extends GeneratorsBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
private final java.lang.String methodName;
GeneratorsMethodDescriptorSupplier(java.lang.String methodName) {
this.methodName = methodName;
}
@java.lang.Override
public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() {
return getServiceDescriptor().findMethodByName(methodName);
}
}
private static volatile io.grpc.ServiceDescriptor serviceDescriptor;
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (GeneratorsGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor =
result =
io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new GeneratorsFileDescriptorSupplier())
.addMethod(getListGeneratorsMethod())
.addMethod(getGetGeneratorMethod())
.addMethod(getCreateGeneratorMethod())
.addMethod(getUpdateGeneratorMethod())
.addMethod(getDeleteGeneratorMethod())
.build();
}
}
}
return result;
}
}
|
googleapis/google-cloud-java | 36,360 | java-meet/proto-google-cloud-meet-v2beta/src/main/java/com/google/apps/meet/v2beta/ListParticipantsRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/apps/meet/v2beta/service.proto
// Protobuf Java Version: 3.25.8
package com.google.apps.meet.v2beta;
/**
*
*
* <pre>
* Request to fetch list of participants per conference.
* </pre>
*
* Protobuf type {@code google.apps.meet.v2beta.ListParticipantsRequest}
*/
public final class ListParticipantsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.apps.meet.v2beta.ListParticipantsRequest)
ListParticipantsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListParticipantsRequest.newBuilder() to construct.
private ListParticipantsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListParticipantsRequest() {
parent_ = "";
pageToken_ = "";
filter_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListParticipantsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.apps.meet.v2beta.ServiceProto
.internal_static_google_apps_meet_v2beta_ListParticipantsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.apps.meet.v2beta.ServiceProto
.internal_static_google_apps_meet_v2beta_ListParticipantsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.apps.meet.v2beta.ListParticipantsRequest.class,
com.google.apps.meet.v2beta.ListParticipantsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Format: `conferenceRecords/{conference_record}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Format: `conferenceRecords/{conference_record}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* Maximum number of participants to return. The service might return fewer
* than this value.
* If unspecified, at most 100 participants are returned.
* The maximum value is 250; values above 250 are coerced to 250.
* Maximum might change in the future.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Page token returned from previous List Call.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Page token returned from previous List Call.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Optional. User specified filtering condition in [EBNF
* format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form).
* The following are the filterable fields:
*
* * `earliest_start_time`
* * `latest_end_time`
*
* For example, `latest_end_time IS NULL` returns active participants in
* the conference.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. User specified filtering condition in [EBNF
* format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form).
* The following are the filterable fields:
*
* * `earliest_start_time`
* * `latest_end_time`
*
* For example, `latest_end_time IS NULL` returns active participants in
* the conference.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.apps.meet.v2beta.ListParticipantsRequest)) {
return super.equals(obj);
}
com.google.apps.meet.v2beta.ListParticipantsRequest other =
(com.google.apps.meet.v2beta.ListParticipantsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.apps.meet.v2beta.ListParticipantsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.apps.meet.v2beta.ListParticipantsRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.apps.meet.v2beta.ListParticipantsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.apps.meet.v2beta.ListParticipantsRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.apps.meet.v2beta.ListParticipantsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.apps.meet.v2beta.ListParticipantsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.apps.meet.v2beta.ListParticipantsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.apps.meet.v2beta.ListParticipantsRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.apps.meet.v2beta.ListParticipantsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.apps.meet.v2beta.ListParticipantsRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.apps.meet.v2beta.ListParticipantsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.apps.meet.v2beta.ListParticipantsRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.apps.meet.v2beta.ListParticipantsRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request to fetch list of participants per conference.
* </pre>
*
* Protobuf type {@code google.apps.meet.v2beta.ListParticipantsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.apps.meet.v2beta.ListParticipantsRequest)
com.google.apps.meet.v2beta.ListParticipantsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.apps.meet.v2beta.ServiceProto
.internal_static_google_apps_meet_v2beta_ListParticipantsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.apps.meet.v2beta.ServiceProto
.internal_static_google_apps_meet_v2beta_ListParticipantsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.apps.meet.v2beta.ListParticipantsRequest.class,
com.google.apps.meet.v2beta.ListParticipantsRequest.Builder.class);
}
// Construct using com.google.apps.meet.v2beta.ListParticipantsRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
filter_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.apps.meet.v2beta.ServiceProto
.internal_static_google_apps_meet_v2beta_ListParticipantsRequest_descriptor;
}
@java.lang.Override
public com.google.apps.meet.v2beta.ListParticipantsRequest getDefaultInstanceForType() {
return com.google.apps.meet.v2beta.ListParticipantsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.apps.meet.v2beta.ListParticipantsRequest build() {
com.google.apps.meet.v2beta.ListParticipantsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.apps.meet.v2beta.ListParticipantsRequest buildPartial() {
com.google.apps.meet.v2beta.ListParticipantsRequest result =
new com.google.apps.meet.v2beta.ListParticipantsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.apps.meet.v2beta.ListParticipantsRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.filter_ = filter_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.apps.meet.v2beta.ListParticipantsRequest) {
return mergeFrom((com.google.apps.meet.v2beta.ListParticipantsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.apps.meet.v2beta.ListParticipantsRequest other) {
if (other == com.google.apps.meet.v2beta.ListParticipantsRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000008;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Format: `conferenceRecords/{conference_record}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Format: `conferenceRecords/{conference_record}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Format: `conferenceRecords/{conference_record}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Format: `conferenceRecords/{conference_record}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Format: `conferenceRecords/{conference_record}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Maximum number of participants to return. The service might return fewer
* than this value.
* If unspecified, at most 100 participants are returned.
* The maximum value is 250; values above 250 are coerced to 250.
* Maximum might change in the future.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Maximum number of participants to return. The service might return fewer
* than this value.
* If unspecified, at most 100 participants are returned.
* The maximum value is 250; values above 250 are coerced to 250.
* Maximum might change in the future.
* </pre>
*
* <code>int32 page_size = 2;</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>
* Maximum number of participants to return. The service might return fewer
* than this value.
* If unspecified, at most 100 participants are returned.
* The maximum value is 250; values above 250 are coerced to 250.
* Maximum might change in the future.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Page token returned from previous List Call.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Page token returned from previous List Call.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Page token returned from previous List Call.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Page token returned from previous List Call.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Page token returned from previous List Call.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Optional. User specified filtering condition in [EBNF
* format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form).
* The following are the filterable fields:
*
* * `earliest_start_time`
* * `latest_end_time`
*
* For example, `latest_end_time IS NULL` returns active participants in
* the conference.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. User specified filtering condition in [EBNF
* format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form).
* The following are the filterable fields:
*
* * `earliest_start_time`
* * `latest_end_time`
*
* For example, `latest_end_time IS NULL` returns active participants in
* the conference.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. User specified filtering condition in [EBNF
* format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form).
* The following are the filterable fields:
*
* * `earliest_start_time`
* * `latest_end_time`
*
* For example, `latest_end_time IS NULL` returns active participants in
* the conference.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. User specified filtering condition in [EBNF
* format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form).
* The following are the filterable fields:
*
* * `earliest_start_time`
* * `latest_end_time`
*
* For example, `latest_end_time IS NULL` returns active participants in
* the conference.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. User specified filtering condition in [EBNF
* format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form).
* The following are the filterable fields:
*
* * `earliest_start_time`
* * `latest_end_time`
*
* For example, `latest_end_time IS NULL` returns active participants in
* the conference.
* </pre>
*
* <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.apps.meet.v2beta.ListParticipantsRequest)
}
// @@protoc_insertion_point(class_scope:google.apps.meet.v2beta.ListParticipantsRequest)
private static final com.google.apps.meet.v2beta.ListParticipantsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.apps.meet.v2beta.ListParticipantsRequest();
}
public static com.google.apps.meet.v2beta.ListParticipantsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListParticipantsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListParticipantsRequest>() {
@java.lang.Override
public ListParticipantsRequest 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<ListParticipantsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListParticipantsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.apps.meet.v2beta.ListParticipantsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/hadoop | 36,509 | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSDirRenameOp.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.util.Preconditions;
import org.apache.hadoop.fs.FileAlreadyExistsException;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.InvalidPathException;
import org.apache.hadoop.fs.Options;
import org.apache.hadoop.fs.ParentNotDirectoryException;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.protocol.QuotaExceededException;
import org.apache.hadoop.hdfs.protocol.SnapshotException;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockStoragePolicySuite;
import org.apache.hadoop.hdfs.server.namenode.FSDirectory.DirOp;
import org.apache.hadoop.hdfs.server.namenode.INode.BlocksMapUpdateInfo;
import org.apache.hadoop.hdfs.server.namenode.snapshot.Snapshot;
import org.apache.hadoop.hdfs.server.namenode.snapshot.SnapshotManager;
import org.apache.hadoop.hdfs.util.ReadOnlyList;
import org.apache.hadoop.util.ChunkedArrayList;
import org.apache.hadoop.util.Time;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.apache.hadoop.hdfs.protocol.FSLimitException.MaxDirectoryItemsExceededException;
import static org.apache.hadoop.hdfs.protocol.FSLimitException.PathComponentTooLongException;
class FSDirRenameOp {
@Deprecated
static RenameResult renameToInt(
FSDirectory fsd, FSPermissionChecker pc, final String src,
final String dst, boolean logRetryCache) throws IOException {
if (NameNode.stateChangeLog.isDebugEnabled()) {
NameNode.stateChangeLog.debug("DIR* NameSystem.renameTo: " + src +
" to " + dst);
}
// Rename does not operate on link targets
// Do not resolveLink when checking permissions of src and dst
INodesInPath srcIIP = fsd.resolvePath(pc, src, DirOp.WRITE_LINK);
INodesInPath dstIIP = fsd.resolvePath(pc, dst, DirOp.CREATE_LINK);
dstIIP = dstForRenameTo(srcIIP, dstIIP);
return renameTo(fsd, pc, srcIIP, dstIIP, logRetryCache);
}
/**
* Verify quota for rename operation where srcInodes[srcInodes.length-1] moves
* dstInodes[dstInodes.length-1]
*/
private static Pair<Optional<QuotaCounts>, Optional<QuotaCounts>> verifyQuotaForRename(
FSDirectory fsd, INodesInPath src, INodesInPath dst) throws QuotaExceededException {
Optional<QuotaCounts> srcDelta = Optional.empty();
Optional<QuotaCounts> dstDelta = Optional.empty();
if (!fsd.getFSNamesystem().isImageLoaded() || fsd.shouldSkipQuotaChecks()) {
// Do not check quota if edits log is still being processed
return Pair.of(srcDelta, dstDelta);
}
int i = 0;
while (src.getINode(i) == dst.getINode(i)) {
i++;
}
// src[i - 1] is the last common ancestor.
BlockStoragePolicySuite bsps = fsd.getBlockStoragePolicySuite();
// Assume dstParent existence check done by callers.
INode dstParent = dst.getINode(-2);
// Use the destination parent's storage policy for quota delta verify.
final boolean isSrcSetSp = src.getLastINode().isSetStoragePolicy();
final byte storagePolicyID = isSrcSetSp ?
src.getLastINode().getLocalStoragePolicyID() :
dstParent.getStoragePolicyID();
final QuotaCounts delta = src.getLastINode()
.computeQuotaUsage(bsps, storagePolicyID, false,
Snapshot.CURRENT_STATE_ID);
QuotaCounts srcQuota = new QuotaCounts.Builder().quotaCount(delta).build();
srcDelta = Optional.of(srcQuota);
// Reduce the required quota by dst that is being removed
final INode dstINode = dst.getLastINode();
if (dstINode != null) {
QuotaCounts counts = dstINode.computeQuotaUsage(bsps);
QuotaCounts dstQuota = new QuotaCounts.Builder().quotaCount(counts).build();
dstDelta = Optional.of(dstQuota);
delta.subtract(counts);
}
FSDirectory.verifyQuota(dst, dst.length() - 1, delta, src.getINode(i - 1));
return Pair.of(srcDelta, dstDelta);
}
/**
* Checks file system limits (max component length and max directory items)
* during a rename operation.
*/
static void verifyFsLimitsForRename(FSDirectory fsd, INodesInPath srcIIP,
INodesInPath dstIIP)
throws PathComponentTooLongException, MaxDirectoryItemsExceededException {
byte[] dstChildName = dstIIP.getLastLocalName();
final String parentPath = dstIIP.getParentPath();
fsd.verifyMaxComponentLength(dstChildName, parentPath);
// Do not enforce max directory items if renaming within same directory.
if (srcIIP.getINode(-2) != dstIIP.getINode(-2)) {
fsd.verifyMaxDirItems(dstIIP.getINode(-2).asDirectory(), parentPath);
}
}
/**
* <br>
* Note: This is to be used by {@link FSEditLogLoader} only.
* <br>
*/
@Deprecated
static INodesInPath renameForEditLog(FSDirectory fsd, String src, String dst,
long timestamp) throws IOException {
final INodesInPath srcIIP = fsd.getINodesInPath(src, DirOp.WRITE_LINK);
INodesInPath dstIIP = fsd.getINodesInPath(dst, DirOp.WRITE_LINK);
// this is wrong but accidentally works. the edit contains the full path
// so the following will do nothing, but shouldn't change due to backward
// compatibility when maybe full path wasn't logged.
dstIIP = dstForRenameTo(srcIIP, dstIIP);
return unprotectedRenameTo(fsd, srcIIP, dstIIP, timestamp);
}
// if destination is a directory, append source child's name, else return
// iip as-is.
private static INodesInPath dstForRenameTo(
INodesInPath srcIIP, INodesInPath dstIIP) throws IOException {
INode dstINode = dstIIP.getLastINode();
if (dstINode != null && dstINode.isDirectory()) {
byte[] childName = srcIIP.getLastLocalName();
// new dest might exist so look it up.
INode childINode = dstINode.asDirectory().getChild(
childName, dstIIP.getPathSnapshotId());
dstIIP = INodesInPath.append(dstIIP, childINode, childName);
}
return dstIIP;
}
/**
* Change a path name
*
* @param fsd FSDirectory
* @param srcIIP source path
* @param dstIIP destination path
* @return true INodesInPath if rename succeeds; null otherwise
* @deprecated See {@link #renameToInt(FSDirectory, FSPermissionChecker,
* String, String, boolean, Options.Rename...)}
*/
@Deprecated
static INodesInPath unprotectedRenameTo(FSDirectory fsd,
final INodesInPath srcIIP, final INodesInPath dstIIP, long timestamp)
throws IOException {
assert fsd.hasWriteLock();
final INode srcInode = srcIIP.getLastINode();
List<INodeDirectory> snapshottableDirs = new ArrayList<>();
try {
validateRenameSource(fsd, srcIIP, snapshottableDirs);
} catch (SnapshotException e) {
throw e;
} catch (IOException ignored) {
return null;
}
String src = srcIIP.getPath();
String dst = dstIIP.getPath();
// validate the destination
if (dst.equals(src)) {
return dstIIP;
}
try {
validateDestination(src, dst, srcInode);
} catch (IOException ignored) {
return null;
}
if (dstIIP.getLastINode() != null) {
NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: " +
"failed to rename " + src + " to " + dst + " because destination " +
"exists");
return null;
}
INode dstParent = dstIIP.getINode(-2);
if (dstParent == null) {
NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: " +
"failed to rename " + src + " to " + dst + " because destination's " +
"parent does not exist");
return null;
}
validateNestSnapshot(fsd, src, dstParent.asDirectory(), snapshottableDirs);
checkUnderSameSnapshottableRoot(fsd, srcIIP, dstIIP);
fsd.ezManager.checkMoveValidity(srcIIP, dstIIP);
// Ensure dst has quota to accommodate rename
verifyFsLimitsForRename(fsd, srcIIP, dstIIP);
Pair<Optional<QuotaCounts>, Optional<QuotaCounts>> countPair =
verifyQuotaForRename(fsd, srcIIP, dstIIP);
RenameOperation tx = new RenameOperation(fsd, srcIIP, dstIIP, countPair);
boolean added = false;
INodesInPath renamedIIP = null;
try {
// remove src
if (!tx.removeSrc4OldRename()) {
return null;
}
renamedIIP = tx.addSourceToDestination();
added = (renamedIIP != null);
if (added) {
if (NameNode.stateChangeLog.isDebugEnabled()) {
NameNode.stateChangeLog.debug("DIR* FSDirectory" +
".unprotectedRenameTo: " + src + " is renamed to " + dst);
}
tx.updateMtimeAndLease(timestamp);
tx.updateQuotasInSourceTree(fsd.getBlockStoragePolicySuite());
return renamedIIP;
}
} finally {
if (!added) {
tx.restoreSource();
}
}
NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: " +
"failed to rename " + src + " to " + dst);
return null;
}
/**
* The new rename which has the POSIX semantic.
*/
static RenameResult renameToInt(
FSDirectory fsd, FSPermissionChecker pc, final String srcArg,
final String dstArg, boolean logRetryCache, Options.Rename... options)
throws IOException {
String src = srcArg;
String dst = dstArg;
if (NameNode.stateChangeLog.isDebugEnabled()) {
NameNode.stateChangeLog.debug("DIR* NameSystem.renameTo: with options={} {} to {}",
Arrays.toString(options), src, dst);
}
BlocksMapUpdateInfo collectedBlocks = new BlocksMapUpdateInfo();
// returns resolved path
return renameTo(fsd, pc, src, dst, collectedBlocks, logRetryCache, options);
}
/**
* @see {@link #unprotectedRenameTo(FSDirectory, INodesInPath, INodesInPath,
* long, BlocksMapUpdateInfo, Options.Rename...)}
*/
static RenameResult renameTo(FSDirectory fsd, FSPermissionChecker pc,
String src, String dst, BlocksMapUpdateInfo collectedBlocks,
boolean logRetryCache,Options.Rename... options)
throws IOException {
final INodesInPath srcIIP = fsd.resolvePath(pc, src, DirOp.WRITE_LINK);
final INodesInPath dstIIP = fsd.resolvePath(pc, dst, DirOp.CREATE_LINK);
if(fsd.isNonEmptyDirectory(srcIIP)) {
DFSUtil.checkProtectedDescendants(fsd, srcIIP);
}
if (fsd.isPermissionEnabled()) {
boolean renameToTrash = false;
if (null != options &&
Arrays.asList(options).
contains(Options.Rename.TO_TRASH)) {
renameToTrash = true;
}
if(renameToTrash) {
// if destination is the trash directory,
// besides the permission check on "rename"
// we need to enforce the check for "delete"
// otherwise, it would expose a
// security hole that stuff moved to trash
// will be deleted by superuser
fsd.checkPermission(pc, srcIIP, false, null, FsAction.WRITE, null,
FsAction.ALL, true);
} else {
// Rename does not operate on link targets
// Do not resolveLink when checking permissions of src and dst
// Check write access to parent of src
fsd.checkPermission(pc, srcIIP, false, null, FsAction.WRITE, null,
null, false);
}
// Check write access to ancestor of dst
fsd.checkPermission(pc, dstIIP, false, FsAction.WRITE, null, null, null,
false);
}
if (NameNode.stateChangeLog.isDebugEnabled()) {
NameNode.stateChangeLog.debug("DIR* FSDirectory.renameTo: " + src + " to "
+ dst);
}
final long mtime = Time.now();
fsd.writeLock();
final RenameResult result;
try {
result = unprotectedRenameTo(fsd, srcIIP, dstIIP, mtime,
collectedBlocks, options);
if (result.filesDeleted) {
FSDirDeleteOp.incrDeletedFileCount(1);
}
} finally {
fsd.writeUnlock();
}
fsd.getEditLog().logRename(
srcIIP.getPath(), dstIIP.getPath(), mtime, logRetryCache, options);
return result;
}
/**
* Rename src to dst.
* <br>
* Note: This is to be used by {@link org.apache.hadoop.hdfs.server
* .namenode.FSEditLogLoader} only.
* <br>
*
* @param fsd FSDirectory
* @param src source path
* @param dst destination path
* @param timestamp modification time
* @param options Rename options
*/
static void renameForEditLog(
FSDirectory fsd, String src, String dst, long timestamp,
Options.Rename... options)
throws IOException {
BlocksMapUpdateInfo collectedBlocks = new BlocksMapUpdateInfo();
final INodesInPath srcIIP = fsd.getINodesInPath(src, DirOp.WRITE_LINK);
final INodesInPath dstIIP = fsd.getINodesInPath(dst, DirOp.WRITE_LINK);
unprotectedRenameTo(fsd, srcIIP, dstIIP, timestamp,
collectedBlocks, options);
if (!collectedBlocks.getToDeleteList().isEmpty()) {
fsd.getFSNamesystem().getBlockManager()
.removeBlocksAndUpdateSafemodeTotal(collectedBlocks);
}
}
/**
* Rename src to dst.
* See {@link DistributedFileSystem#rename(Path, Path, Options.Rename...)}
* for details related to rename semantics and exceptions.
*
* @param fsd FSDirectory
* @param srcIIP source path
* @param dstIIP destination path
* @param timestamp modification time
* @param collectedBlocks blocks to be removed
* @param options Rename options
* @return whether a file/directory gets overwritten in the dst path
*/
static RenameResult unprotectedRenameTo(FSDirectory fsd,
final INodesInPath srcIIP, final INodesInPath dstIIP, long timestamp,
BlocksMapUpdateInfo collectedBlocks, Options.Rename... options)
throws IOException {
assert fsd.hasWriteLock();
boolean overwrite = options != null
&& Arrays.asList(options).contains(Options.Rename.OVERWRITE);
final String src = srcIIP.getPath();
final String dst = dstIIP.getPath();
final String error;
final INode srcInode = srcIIP.getLastINode();
List<INodeDirectory> srcSnapshottableDirs = new ArrayList<>();
validateRenameSource(fsd, srcIIP, srcSnapshottableDirs);
// validate the destination
if (dst.equals(src)) {
throw new FileAlreadyExistsException("The source " + src +
" and destination " + dst + " are the same");
}
validateDestination(src, dst, srcInode);
if (dstIIP.length() == 1) {
error = "rename destination cannot be the root";
NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: " +
error);
throw new IOException(error);
}
BlockStoragePolicySuite bsps = fsd.getBlockStoragePolicySuite();
fsd.ezManager.checkMoveValidity(srcIIP, dstIIP);
final INode dstInode = dstIIP.getLastINode();
List<INodeDirectory> dstSnapshottableDirs = new ArrayList<>();
if (dstInode != null) { // Destination exists
validateOverwrite(src, dst, overwrite, srcInode, dstInode);
FSDirSnapshotOp.checkSnapshot(fsd, dstIIP, dstSnapshottableDirs);
}
INode dstParent = dstIIP.getINode(-2);
if (dstParent == null) {
error = "rename destination parent " + dst + " not found.";
NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: " +
error);
throw new FileNotFoundException(error);
}
if (!dstParent.isDirectory()) {
error = "rename destination parent " + dst + " is a file.";
NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: " +
error);
throw new ParentNotDirectoryException(error);
}
validateNestSnapshot(fsd, src,
dstParent.asDirectory(), srcSnapshottableDirs);
checkUnderSameSnapshottableRoot(fsd, srcIIP, dstIIP);
// Ensure dst has quota to accommodate rename
verifyFsLimitsForRename(fsd, srcIIP, dstIIP);
Pair<Optional<QuotaCounts>, Optional<QuotaCounts>> quotaPair =
verifyQuotaForRename(fsd, srcIIP, dstIIP);
RenameOperation tx = new RenameOperation(fsd, srcIIP, dstIIP, quotaPair);
boolean undoRemoveSrc = true;
tx.removeSrc();
boolean undoRemoveDst = false;
long removedNum = 0;
try {
if (dstInode != null) { // dst exists, remove it
removedNum = tx.removeDst();
if (removedNum != -1) {
undoRemoveDst = true;
}
}
// add src as dst to complete rename
INodesInPath renamedIIP = tx.addSourceToDestination();
if (renamedIIP != null) {
undoRemoveSrc = false;
if (NameNode.stateChangeLog.isDebugEnabled()) {
NameNode.stateChangeLog.debug("DIR* FSDirectory.unprotectedRenameTo: "
+ src + " is renamed to " + dst);
}
tx.updateMtimeAndLease(timestamp);
// Collect the blocks and remove the lease for previous dst
boolean filesDeleted = false;
if (undoRemoveDst) {
undoRemoveDst = false;
if (removedNum > 0) {
filesDeleted = tx.cleanDst(bsps, collectedBlocks);
}
}
if (dstSnapshottableDirs.size() > 0) {
// There are snapshottable directories (without snapshots) to be
// deleted. Need to update the SnapshotManager.
fsd.getFSNamesystem().removeSnapshottableDirs(dstSnapshottableDirs);
}
tx.updateQuotasInSourceTree(bsps);
return createRenameResult(
fsd, renamedIIP, filesDeleted, collectedBlocks);
}
} finally {
if (undoRemoveSrc) {
tx.restoreSource();
}
if (undoRemoveDst) { // Rename failed - restore dst
tx.restoreDst(bsps);
}
}
NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: " +
"failed to rename " + src + " to " + dst);
throw new IOException("rename from " + src + " to " + dst + " failed.");
}
/**
* @deprecated Use {@link #renameToInt(FSDirectory, FSPermissionChecker,
* String, String, boolean, Options.Rename...)}
*/
@Deprecated
private static RenameResult renameTo(FSDirectory fsd, FSPermissionChecker pc,
INodesInPath srcIIP, INodesInPath dstIIP, boolean logRetryCache)
throws IOException {
if(fsd.isNonEmptyDirectory(srcIIP)) {
DFSUtil.checkProtectedDescendants(fsd, srcIIP);
}
if (fsd.isPermissionEnabled()) {
// Check write access to parent of src
fsd.checkPermission(pc, srcIIP, false, null, FsAction.WRITE, null, null,
false);
// Check write access to ancestor of dst
fsd.checkPermission(pc, dstIIP, false, FsAction.WRITE, null, null,
null, false);
}
if (NameNode.stateChangeLog.isDebugEnabled()) {
NameNode.stateChangeLog.debug("DIR* FSDirectory.renameTo: " +
srcIIP.getPath() + " to " + dstIIP.getPath());
}
final long mtime = Time.now();
INodesInPath renameIIP;
fsd.writeLock();
try {
renameIIP = unprotectedRenameTo(fsd, srcIIP, dstIIP, mtime);
} finally {
fsd.writeUnlock();
}
if (renameIIP != null) {
fsd.getEditLog().logRename(
srcIIP.getPath(), dstIIP.getPath(), mtime, logRetryCache);
}
// this rename never overwrites the dest so files deleted and collected
// are irrelevant.
return createRenameResult(fsd, renameIIP, false, null);
}
private static void validateDestination(
String src, String dst, INode srcInode)
throws IOException {
String error;
if (srcInode.isSymlink() &&
dst.equals(srcInode.asSymlink().getSymlinkString())) {
throw new FileAlreadyExistsException("Cannot rename symlink " + src
+ " to its target " + dst);
}
// dst cannot be a directory or a file under src
if (dst.startsWith(src)
&& dst.charAt(src.length()) == Path.SEPARATOR_CHAR) {
error = "Rename destination " + dst
+ " is a directory or file under source " + src;
NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
+ error);
throw new IOException(error);
}
if (FSDirectory.isExactReservedName(src)
|| FSDirectory.isExactReservedName(dst)) {
error = "Cannot rename to or from /.reserved";
throw new InvalidPathException(error);
}
}
private static void validateOverwrite(
String src, String dst, boolean overwrite, INode srcInode, INode dstInode)
throws IOException {
String error;// It's OK to rename a file to a symlink and vice versa
if (dstInode.isDirectory() != srcInode.isDirectory()) {
error = "Source " + src + " and destination " + dst
+ " must both be directories";
NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
+ error);
throw new IOException(error);
}
if (!overwrite) { // If destination exists, overwrite flag must be true
error = "rename destination " + dst + " already exists";
NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
+ error);
throw new FileAlreadyExistsException(error);
}
if (dstInode.isDirectory()) {
final ReadOnlyList<INode> children = dstInode.asDirectory()
.getChildrenList(Snapshot.CURRENT_STATE_ID);
if (!children.isEmpty()) {
error = "rename destination directory is not empty: " + dst;
NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
+ error);
throw new IOException(error);
}
}
}
private static void validateRenameSource(FSDirectory fsd,
INodesInPath srcIIP, List<INodeDirectory> snapshottableDirs)
throws IOException {
String error;
final INode srcInode = srcIIP.getLastINode();
// validate source
if (srcInode == null) {
error = "rename source " + srcIIP.getPath() + " is not found.";
NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
+ error);
throw new FileNotFoundException(error);
}
if (srcIIP.length() == 1) {
error = "rename source cannot be the root";
NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
+ error);
throw new IOException(error);
}
// srcInode and its subtree cannot contain snapshottable directories with
// snapshots
FSDirSnapshotOp.checkSnapshot(fsd, srcIIP, snapshottableDirs);
}
private static void validateNestSnapshot(FSDirectory fsd, String srcPath,
INodeDirectory dstParent, List<INodeDirectory> snapshottableDirs)
throws SnapshotException {
if (fsd.getFSNamesystem().getSnapshotManager().isAllowNestedSnapshots()) {
return;
}
/*
* snapshottableDirs is a list of snapshottable directory (child of rename
* src) which do not have snapshots yet. If this list is not empty, that
* means rename src has snapshottable descendant directories.
*/
if (snapshottableDirs != null && snapshottableDirs.size() > 0) {
if (fsd.getFSNamesystem().getSnapshotManager()
.isDescendantOfSnapshotRoot(dstParent)) {
String dstPath = dstParent.getFullPathName();
throw new SnapshotException("Unable to rename because " + srcPath
+ " has snapshottable descendant directories and " + dstPath
+ " is a descent of a snapshottable directory, and HDFS does"
+ " not support nested snapshottable directory.");
}
}
}
private static class RenameOperation {
private final FSDirectory fsd;
private INodesInPath srcIIP;
private final INodesInPath srcParentIIP;
private INodesInPath dstIIP;
private final INodesInPath dstParentIIP;
private final INodeReference.WithCount withCount;
private final int srcRefDstSnapshot;
private final INodeDirectory srcParent;
private final byte[] srcChildName;
private final boolean isSrcInSnapshot;
private final boolean srcChildIsReference;
private final QuotaCounts oldSrcCountsInSnapshot;
private final boolean sameStoragePolicy;
private final Optional<QuotaCounts> srcSubTreeCount;
private final Optional<QuotaCounts> dstSubTreeCount;
private INode srcChild;
private INode oldDstChild;
RenameOperation(FSDirectory fsd, INodesInPath srcIIP, INodesInPath dstIIP,
Pair<Optional<QuotaCounts>, Optional<QuotaCounts>> quotaPair) {
this.fsd = fsd;
this.srcIIP = srcIIP;
this.dstIIP = dstIIP;
this.srcParentIIP = srcIIP.getParentINodesInPath();
this.dstParentIIP = dstIIP.getParentINodesInPath();
this.sameStoragePolicy = isSameStoragePolicy();
BlockStoragePolicySuite bsps = fsd.getBlockStoragePolicySuite();
srcChild = this.srcIIP.getLastINode();
srcChildName = srcChild.getLocalNameBytes();
final int srcLatestSnapshotId = srcIIP.getLatestSnapshotId();
isSrcInSnapshot = srcChild.isInLatestSnapshot(srcLatestSnapshotId);
srcChildIsReference = srcChild.isReference();
srcParent = this.srcIIP.getINode(-2).asDirectory();
// Record the snapshot on srcChild. After the rename, before any new
// snapshot is taken on the dst tree, changes will be recorded in the
// latest snapshot of the src tree.
if (isSrcInSnapshot) {
if (srcChild.isFile()) {
INodeFile file = srcChild.asFile();
file.recordModification(srcLatestSnapshotId, true);
} else {
srcChild.recordModification(srcLatestSnapshotId);
}
}
// check srcChild for reference
srcRefDstSnapshot = srcChildIsReference ?
srcChild.asReference().getDstSnapshotId() : Snapshot.CURRENT_STATE_ID;
oldSrcCountsInSnapshot = new QuotaCounts.Builder().build();
if (isSrcInSnapshot) {
final INodeReference.WithName withName = srcParent
.replaceChild4ReferenceWithName(srcChild, srcLatestSnapshotId);
withCount = (INodeReference.WithCount) withName.getReferredINode();
srcChild = withName;
this.srcIIP = INodesInPath.replace(srcIIP, srcIIP.length() - 1,
srcChild);
// get the counts before rename
oldSrcCountsInSnapshot.add(withCount.getReferredINode().computeQuotaUsage(bsps));
} else if (srcChildIsReference) {
// srcChild is reference but srcChild is not in latest snapshot
withCount = (INodeReference.WithCount) srcChild.asReference()
.getReferredINode();
} else {
withCount = null;
}
// Set quota for src and dst, ignore src is in Snapshot or is Reference
this.srcSubTreeCount = withCount == null ?
quotaPair.getLeft() : Optional.empty();
this.dstSubTreeCount = quotaPair.getRight();
}
boolean isSameStoragePolicy() {
final INode src = srcIIP.getLastINode();
final INode dst = dstIIP.getLastINode();
// If the source INode has a storagePolicyID, we should use
// its storagePolicyId to update dst`s quota usage.
if (src.isSetStoragePolicy()) {
return true;
}
final byte srcSp;
final byte dstSp;
if (dst == null) {
dstSp = dstIIP.getINode(-2).getStoragePolicyID();
} else if (dst.isSymlink()) {
dstSp = HdfsConstants.BLOCK_STORAGE_POLICY_ID_UNSPECIFIED;
} else {
dstSp = dst.getStoragePolicyID();
}
if (src.isSymlink()) {
srcSp = HdfsConstants.BLOCK_STORAGE_POLICY_ID_UNSPECIFIED;
} else {
// Update src should use src·s storage policyID
srcSp = src.getStoragePolicyID();
}
return srcSp == dstSp;
}
long removeSrc() throws IOException {
long removedNum = fsd.removeLastINode(srcIIP);
if (removedNum == -1) {
String error = "Failed to rename " + srcIIP.getPath() + " to " +
dstIIP.getPath() + " because the source can not be removed";
NameNode.stateChangeLog.warn("DIR* FSDirRenameOp.unprotectedRenameTo:" +
error);
throw new IOException(error);
} else {
// update the quota count if necessary
Optional<QuotaCounts> countOp = sameStoragePolicy ?
srcSubTreeCount : Optional.empty();
fsd.updateCountForDelete(srcChild, srcIIP, countOp);
srcIIP = INodesInPath.replace(srcIIP, srcIIP.length() - 1, null);
return removedNum;
}
}
boolean removeSrc4OldRename() {
final long removedSrc = fsd.removeLastINode(srcIIP);
if (removedSrc == -1) {
NameNode.stateChangeLog.warn("DIR* FSDirRenameOp.unprotectedRenameTo: "
+ "failed to rename " + srcIIP.getPath() + " to "
+ dstIIP.getPath() + " because the source can not be removed");
return false;
} else {
// update the quota count if necessary
Optional<QuotaCounts> countOp = sameStoragePolicy ?
srcSubTreeCount : Optional.empty();
fsd.updateCountForDelete(srcChild, srcIIP, countOp);
srcIIP = INodesInPath.replace(srcIIP, srcIIP.length() - 1, null);
return true;
}
}
long removeDst() {
long removedNum = fsd.removeLastINode(dstIIP);
if (removedNum != -1) {
oldDstChild = dstIIP.getLastINode();
// update the quota count if necessary
fsd.updateCountForDelete(oldDstChild, dstIIP, dstSubTreeCount);
dstIIP = INodesInPath.replace(dstIIP, dstIIP.length() - 1, null);
}
return removedNum;
}
INodesInPath addSourceToDestination() {
final INode dstParent = dstParentIIP.getLastINode();
final byte[] dstChildName = dstIIP.getLastLocalName();
final INode toDst;
if (withCount == null) {
srcChild.setLocalName(dstChildName);
toDst = srcChild;
} else {
withCount.getReferredINode().setLocalName(dstChildName);
toDst = new INodeReference.DstReference(dstParent.asDirectory(),
withCount, dstIIP.getLatestSnapshotId());
}
return fsd.addLastINodeNoQuotaCheck(dstParentIIP, toDst, srcSubTreeCount);
}
void updateMtimeAndLease(long timestamp) {
srcParent.updateModificationTime(timestamp, srcIIP.getLatestSnapshotId());
final INode dstParent = dstParentIIP.getLastINode();
dstParent.updateModificationTime(timestamp, dstIIP.getLatestSnapshotId());
}
void restoreSource() {
// Rename failed - restore src
final INode oldSrcChild = srcChild;
// put it back
if (withCount == null) {
srcChild.setLocalName(srcChildName);
} else if (!srcChildIsReference) { // src must be in snapshot
// the withCount node will no longer be used thus no need to update
// its reference number here
srcChild = withCount.getReferredINode();
srcChild.setLocalName(srcChildName);
} else {
withCount.removeReference(oldSrcChild.asReference());
srcChild = new INodeReference.DstReference(srcParent, withCount,
srcRefDstSnapshot);
withCount.getReferredINode().setLocalName(srcChildName);
}
if (isSrcInSnapshot) {
srcParent.undoRename4ScrParent(oldSrcChild.asReference(), srcChild);
} else {
// srcParent is not an INodeDirectoryWithSnapshot, we only need to add
// the srcChild back
Optional<QuotaCounts> countOp = sameStoragePolicy ?
srcSubTreeCount : Optional.empty();
fsd.addLastINodeNoQuotaCheck(srcParentIIP, srcChild, countOp);
}
}
void restoreDst(BlockStoragePolicySuite bsps) {
Preconditions.checkState(oldDstChild != null);
final INodeDirectory dstParent = dstParentIIP.getLastINode().asDirectory();
if (dstParent.isWithSnapshot()) {
dstParent.undoRename4DstParent(bsps, oldDstChild, dstIIP.getLatestSnapshotId());
} else {
fsd.addLastINodeNoQuotaCheck(dstParentIIP, oldDstChild, dstSubTreeCount);
}
if (oldDstChild != null && oldDstChild.isReference()) {
final INodeReference removedDstRef = oldDstChild.asReference();
final INodeReference.WithCount wc = (INodeReference.WithCount)
removedDstRef.getReferredINode().asReference();
wc.addReference(removedDstRef);
}
}
boolean cleanDst(
BlockStoragePolicySuite bsps, BlocksMapUpdateInfo collectedBlocks) {
Preconditions.checkState(oldDstChild != null);
List<INode> removedINodes = new ChunkedArrayList<>();
List<Long> removedUCFiles = new ChunkedArrayList<>();
INode.ReclaimContext context = new INode.ReclaimContext(
bsps, collectedBlocks, removedINodes, removedUCFiles);
final boolean filesDeleted;
if (!oldDstChild.isInLatestSnapshot(dstIIP.getLatestSnapshotId())) {
oldDstChild.destroyAndCollectBlocks(context);
filesDeleted = true;
} else {
oldDstChild.cleanSubtree(context, Snapshot.CURRENT_STATE_ID,
dstIIP.getLatestSnapshotId());
filesDeleted = context.quotaDelta().getNsDelta() >= 0;
}
fsd.updateReplicationFactor(context.collectedBlocks()
.toUpdateReplicationInfo());
fsd.getFSNamesystem().removeLeasesAndINodes(
removedUCFiles, removedINodes, false);
return filesDeleted;
}
void updateQuotasInSourceTree(BlockStoragePolicySuite bsps) {
// update the quota usage in src tree
if (isSrcInSnapshot) {
// get the counts after rename
QuotaCounts newSrcCounts = srcChild.computeQuotaUsage(bsps, false);
newSrcCounts.subtract(oldSrcCountsInSnapshot);
srcParent.addSpaceConsumed(newSrcCounts);
}
}
}
private static void checkUnderSameSnapshottableRoot(
FSDirectory fsd, INodesInPath srcIIP, INodesInPath dstIIP)
throws IOException {
// Ensure rename out of a snapshottable root is not permitted if ordered
// snapshot deletion feature is enabled
SnapshotManager snapshotManager = fsd.getFSNamesystem().
getSnapshotManager();
if (snapshotManager.isSnapshotDeletionOrdered() && fsd.getFSNamesystem()
.isSnapshotTrashRootEnabled()) {
INodeDirectory srcRoot = snapshotManager.
getSnapshottableAncestorDir(srcIIP);
INodeDirectory dstRoot = snapshotManager.
getSnapshottableAncestorDir(dstIIP);
// Ensure snapshoottable root for both src and dest are same.
if (srcRoot != dstRoot) {
String errMsg = "Source " + srcIIP.getPath() +
" and dest " + dstIIP.getPath() + " are not under " +
"the same snapshot root.";
throw new SnapshotException(errMsg);
}
}
}
private static RenameResult createRenameResult(FSDirectory fsd,
INodesInPath dst, boolean filesDeleted,
BlocksMapUpdateInfo collectedBlocks) throws IOException {
boolean success = (dst != null);
FileStatus auditStat = success ? fsd.getAuditFileInfo(dst) : null;
return new RenameResult(
success, auditStat, filesDeleted, collectedBlocks);
}
static class RenameResult {
final boolean success;
final FileStatus auditStat;
final boolean filesDeleted;
final BlocksMapUpdateInfo collectedBlocks;
RenameResult(boolean success, FileStatus auditStat,
boolean filesDeleted, BlocksMapUpdateInfo collectedBlocks) {
this.success = success;
this.auditStat = auditStat;
this.filesDeleted = filesDeleted;
this.collectedBlocks = collectedBlocks;
}
}
}
|
googleapis/google-cloud-java | 36,322 | java-shopping-merchant-accounts/proto-google-shopping-merchant-accounts-v1beta/src/main/java/com/google/shopping/merchant/accounts/v1beta/CustomerService.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/shopping/merchant/accounts/v1beta/customerservice.proto
// Protobuf Java Version: 3.25.8
package com.google.shopping.merchant.accounts.v1beta;
/**
*
*
* <pre>
* Customer service information.
* </pre>
*
* Protobuf type {@code google.shopping.merchant.accounts.v1beta.CustomerService}
*/
public final class CustomerService extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.shopping.merchant.accounts.v1beta.CustomerService)
CustomerServiceOrBuilder {
private static final long serialVersionUID = 0L;
// Use CustomerService.newBuilder() to construct.
private CustomerService(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CustomerService() {
uri_ = "";
email_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CustomerService();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.shopping.merchant.accounts.v1beta.CustomerServiceProto
.internal_static_google_shopping_merchant_accounts_v1beta_CustomerService_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.shopping.merchant.accounts.v1beta.CustomerServiceProto
.internal_static_google_shopping_merchant_accounts_v1beta_CustomerService_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.shopping.merchant.accounts.v1beta.CustomerService.class,
com.google.shopping.merchant.accounts.v1beta.CustomerService.Builder.class);
}
private int bitField0_;
public static final int URI_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object uri_ = "";
/**
*
*
* <pre>
* Optional. The URI where customer service may be found.
* </pre>
*
* <code>optional string uri = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the uri field is set.
*/
@java.lang.Override
public boolean hasUri() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Optional. The URI where customer service may be found.
* </pre>
*
* <code>optional string uri = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The uri.
*/
@java.lang.Override
public java.lang.String getUri() {
java.lang.Object ref = uri_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
uri_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. The URI where customer service may be found.
* </pre>
*
* <code>optional string uri = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for uri.
*/
@java.lang.Override
public com.google.protobuf.ByteString getUriBytes() {
java.lang.Object ref = uri_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
uri_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int EMAIL_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object email_ = "";
/**
*
*
* <pre>
* Optional. The email address where customer service may be reached.
* </pre>
*
* <code>optional string email = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the email field is set.
*/
@java.lang.Override
public boolean hasEmail() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Optional. The email address where customer service may be reached.
* </pre>
*
* <code>optional string email = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The email.
*/
@java.lang.Override
public java.lang.String getEmail() {
java.lang.Object ref = email_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
email_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. The email address where customer service may be reached.
* </pre>
*
* <code>optional string email = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for email.
*/
@java.lang.Override
public com.google.protobuf.ByteString getEmailBytes() {
java.lang.Object ref = email_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
email_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PHONE_FIELD_NUMBER = 3;
private com.google.type.PhoneNumber phone_;
/**
*
*
* <pre>
* Optional. The phone number where customer service may be called.
* </pre>
*
* <code>optional .google.type.PhoneNumber phone = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the phone field is set.
*/
@java.lang.Override
public boolean hasPhone() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* Optional. The phone number where customer service may be called.
* </pre>
*
* <code>optional .google.type.PhoneNumber phone = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The phone.
*/
@java.lang.Override
public com.google.type.PhoneNumber getPhone() {
return phone_ == null ? com.google.type.PhoneNumber.getDefaultInstance() : phone_;
}
/**
*
*
* <pre>
* Optional. The phone number where customer service may be called.
* </pre>
*
* <code>optional .google.type.PhoneNumber phone = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
@java.lang.Override
public com.google.type.PhoneNumberOrBuilder getPhoneOrBuilder() {
return phone_ == null ? com.google.type.PhoneNumber.getDefaultInstance() : phone_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, uri_);
}
if (((bitField0_ & 0x00000002) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, email_);
}
if (((bitField0_ & 0x00000004) != 0)) {
output.writeMessage(3, getPhone());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, uri_);
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, email_);
}
if (((bitField0_ & 0x00000004) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getPhone());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.shopping.merchant.accounts.v1beta.CustomerService)) {
return super.equals(obj);
}
com.google.shopping.merchant.accounts.v1beta.CustomerService other =
(com.google.shopping.merchant.accounts.v1beta.CustomerService) obj;
if (hasUri() != other.hasUri()) return false;
if (hasUri()) {
if (!getUri().equals(other.getUri())) return false;
}
if (hasEmail() != other.hasEmail()) return false;
if (hasEmail()) {
if (!getEmail().equals(other.getEmail())) return false;
}
if (hasPhone() != other.hasPhone()) return false;
if (hasPhone()) {
if (!getPhone().equals(other.getPhone())) 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 (hasUri()) {
hash = (37 * hash) + URI_FIELD_NUMBER;
hash = (53 * hash) + getUri().hashCode();
}
if (hasEmail()) {
hash = (37 * hash) + EMAIL_FIELD_NUMBER;
hash = (53 * hash) + getEmail().hashCode();
}
if (hasPhone()) {
hash = (37 * hash) + PHONE_FIELD_NUMBER;
hash = (53 * hash) + getPhone().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.shopping.merchant.accounts.v1beta.CustomerService parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.accounts.v1beta.CustomerService parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.shopping.merchant.accounts.v1beta.CustomerService parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.accounts.v1beta.CustomerService parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.shopping.merchant.accounts.v1beta.CustomerService parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.accounts.v1beta.CustomerService parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.shopping.merchant.accounts.v1beta.CustomerService parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.accounts.v1beta.CustomerService parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.shopping.merchant.accounts.v1beta.CustomerService parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.accounts.v1beta.CustomerService parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.shopping.merchant.accounts.v1beta.CustomerService parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.accounts.v1beta.CustomerService parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.shopping.merchant.accounts.v1beta.CustomerService 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>
* Customer service information.
* </pre>
*
* Protobuf type {@code google.shopping.merchant.accounts.v1beta.CustomerService}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.shopping.merchant.accounts.v1beta.CustomerService)
com.google.shopping.merchant.accounts.v1beta.CustomerServiceOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.shopping.merchant.accounts.v1beta.CustomerServiceProto
.internal_static_google_shopping_merchant_accounts_v1beta_CustomerService_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.shopping.merchant.accounts.v1beta.CustomerServiceProto
.internal_static_google_shopping_merchant_accounts_v1beta_CustomerService_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.shopping.merchant.accounts.v1beta.CustomerService.class,
com.google.shopping.merchant.accounts.v1beta.CustomerService.Builder.class);
}
// Construct using com.google.shopping.merchant.accounts.v1beta.CustomerService.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getPhoneFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
uri_ = "";
email_ = "";
phone_ = null;
if (phoneBuilder_ != null) {
phoneBuilder_.dispose();
phoneBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.shopping.merchant.accounts.v1beta.CustomerServiceProto
.internal_static_google_shopping_merchant_accounts_v1beta_CustomerService_descriptor;
}
@java.lang.Override
public com.google.shopping.merchant.accounts.v1beta.CustomerService
getDefaultInstanceForType() {
return com.google.shopping.merchant.accounts.v1beta.CustomerService.getDefaultInstance();
}
@java.lang.Override
public com.google.shopping.merchant.accounts.v1beta.CustomerService build() {
com.google.shopping.merchant.accounts.v1beta.CustomerService result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.shopping.merchant.accounts.v1beta.CustomerService buildPartial() {
com.google.shopping.merchant.accounts.v1beta.CustomerService result =
new com.google.shopping.merchant.accounts.v1beta.CustomerService(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.shopping.merchant.accounts.v1beta.CustomerService result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.uri_ = uri_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.email_ = email_;
to_bitField0_ |= 0x00000002;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.phone_ = phoneBuilder_ == null ? phone_ : phoneBuilder_.build();
to_bitField0_ |= 0x00000004;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.shopping.merchant.accounts.v1beta.CustomerService) {
return mergeFrom((com.google.shopping.merchant.accounts.v1beta.CustomerService) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.shopping.merchant.accounts.v1beta.CustomerService other) {
if (other
== com.google.shopping.merchant.accounts.v1beta.CustomerService.getDefaultInstance())
return this;
if (other.hasUri()) {
uri_ = other.uri_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasEmail()) {
email_ = other.email_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasPhone()) {
mergePhone(other.getPhone());
}
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:
{
uri_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
email_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
input.readMessage(getPhoneFieldBuilder().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 uri_ = "";
/**
*
*
* <pre>
* Optional. The URI where customer service may be found.
* </pre>
*
* <code>optional string uri = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the uri field is set.
*/
public boolean hasUri() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Optional. The URI where customer service may be found.
* </pre>
*
* <code>optional string uri = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The uri.
*/
public java.lang.String getUri() {
java.lang.Object ref = uri_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
uri_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. The URI where customer service may be found.
* </pre>
*
* <code>optional string uri = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for uri.
*/
public com.google.protobuf.ByteString getUriBytes() {
java.lang.Object ref = uri_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
uri_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. The URI where customer service may be found.
* </pre>
*
* <code>optional string uri = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The uri to set.
* @return This builder for chaining.
*/
public Builder setUri(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
uri_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The URI where customer service may be found.
* </pre>
*
* <code>optional string uri = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearUri() {
uri_ = getDefaultInstance().getUri();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The URI where customer service may be found.
* </pre>
*
* <code>optional string uri = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for uri to set.
* @return This builder for chaining.
*/
public Builder setUriBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
uri_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object email_ = "";
/**
*
*
* <pre>
* Optional. The email address where customer service may be reached.
* </pre>
*
* <code>optional string email = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the email field is set.
*/
public boolean hasEmail() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Optional. The email address where customer service may be reached.
* </pre>
*
* <code>optional string email = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The email.
*/
public java.lang.String getEmail() {
java.lang.Object ref = email_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
email_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. The email address where customer service may be reached.
* </pre>
*
* <code>optional string email = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for email.
*/
public com.google.protobuf.ByteString getEmailBytes() {
java.lang.Object ref = email_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
email_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. The email address where customer service may be reached.
* </pre>
*
* <code>optional string email = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The email to set.
* @return This builder for chaining.
*/
public Builder setEmail(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
email_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The email address where customer service may be reached.
* </pre>
*
* <code>optional string email = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearEmail() {
email_ = getDefaultInstance().getEmail();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The email address where customer service may be reached.
* </pre>
*
* <code>optional string email = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for email to set.
* @return This builder for chaining.
*/
public Builder setEmailBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
email_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.type.PhoneNumber phone_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.type.PhoneNumber,
com.google.type.PhoneNumber.Builder,
com.google.type.PhoneNumberOrBuilder>
phoneBuilder_;
/**
*
*
* <pre>
* Optional. The phone number where customer service may be called.
* </pre>
*
* <code>optional .google.type.PhoneNumber phone = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the phone field is set.
*/
public boolean hasPhone() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* Optional. The phone number where customer service may be called.
* </pre>
*
* <code>optional .google.type.PhoneNumber phone = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The phone.
*/
public com.google.type.PhoneNumber getPhone() {
if (phoneBuilder_ == null) {
return phone_ == null ? com.google.type.PhoneNumber.getDefaultInstance() : phone_;
} else {
return phoneBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Optional. The phone number where customer service may be called.
* </pre>
*
* <code>optional .google.type.PhoneNumber phone = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setPhone(com.google.type.PhoneNumber value) {
if (phoneBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
phone_ = value;
} else {
phoneBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The phone number where customer service may be called.
* </pre>
*
* <code>optional .google.type.PhoneNumber phone = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setPhone(com.google.type.PhoneNumber.Builder builderForValue) {
if (phoneBuilder_ == null) {
phone_ = builderForValue.build();
} else {
phoneBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The phone number where customer service may be called.
* </pre>
*
* <code>optional .google.type.PhoneNumber phone = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder mergePhone(com.google.type.PhoneNumber value) {
if (phoneBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& phone_ != null
&& phone_ != com.google.type.PhoneNumber.getDefaultInstance()) {
getPhoneBuilder().mergeFrom(value);
} else {
phone_ = value;
}
} else {
phoneBuilder_.mergeFrom(value);
}
if (phone_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Optional. The phone number where customer service may be called.
* </pre>
*
* <code>optional .google.type.PhoneNumber phone = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder clearPhone() {
bitField0_ = (bitField0_ & ~0x00000004);
phone_ = null;
if (phoneBuilder_ != null) {
phoneBuilder_.dispose();
phoneBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The phone number where customer service may be called.
* </pre>
*
* <code>optional .google.type.PhoneNumber phone = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.type.PhoneNumber.Builder getPhoneBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getPhoneFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Optional. The phone number where customer service may be called.
* </pre>
*
* <code>optional .google.type.PhoneNumber phone = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.type.PhoneNumberOrBuilder getPhoneOrBuilder() {
if (phoneBuilder_ != null) {
return phoneBuilder_.getMessageOrBuilder();
} else {
return phone_ == null ? com.google.type.PhoneNumber.getDefaultInstance() : phone_;
}
}
/**
*
*
* <pre>
* Optional. The phone number where customer service may be called.
* </pre>
*
* <code>optional .google.type.PhoneNumber phone = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.type.PhoneNumber,
com.google.type.PhoneNumber.Builder,
com.google.type.PhoneNumberOrBuilder>
getPhoneFieldBuilder() {
if (phoneBuilder_ == null) {
phoneBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.type.PhoneNumber,
com.google.type.PhoneNumber.Builder,
com.google.type.PhoneNumberOrBuilder>(
getPhone(), getParentForChildren(), isClean());
phone_ = null;
}
return phoneBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.shopping.merchant.accounts.v1beta.CustomerService)
}
// @@protoc_insertion_point(class_scope:google.shopping.merchant.accounts.v1beta.CustomerService)
private static final com.google.shopping.merchant.accounts.v1beta.CustomerService
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.shopping.merchant.accounts.v1beta.CustomerService();
}
public static com.google.shopping.merchant.accounts.v1beta.CustomerService getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CustomerService> PARSER =
new com.google.protobuf.AbstractParser<CustomerService>() {
@java.lang.Override
public CustomerService 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<CustomerService> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CustomerService> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.shopping.merchant.accounts.v1beta.CustomerService getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,484 | java-asset/proto-google-cloud-asset-v1p2beta1/src/main/java/com/google/cloud/asset/v1p2beta1/UpdateFeedRequest.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/v1p2beta1/asset_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.asset.v1p2beta1;
/**
*
*
* <pre>
* Update asset feed request.
* </pre>
*
* Protobuf type {@code google.cloud.asset.v1p2beta1.UpdateFeedRequest}
*/
public final class UpdateFeedRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.asset.v1p2beta1.UpdateFeedRequest)
UpdateFeedRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateFeedRequest.newBuilder() to construct.
private UpdateFeedRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateFeedRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateFeedRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.asset.v1p2beta1.AssetServiceProto
.internal_static_google_cloud_asset_v1p2beta1_UpdateFeedRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.asset.v1p2beta1.AssetServiceProto
.internal_static_google_cloud_asset_v1p2beta1_UpdateFeedRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.asset.v1p2beta1.UpdateFeedRequest.class,
com.google.cloud.asset.v1p2beta1.UpdateFeedRequest.Builder.class);
}
private int bitField0_;
public static final int FEED_FIELD_NUMBER = 1;
private com.google.cloud.asset.v1p2beta1.Feed feed_;
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1p2beta1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the feed field is set.
*/
@java.lang.Override
public boolean hasFeed() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1p2beta1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The feed.
*/
@java.lang.Override
public com.google.cloud.asset.v1p2beta1.Feed getFeed() {
return feed_ == null ? com.google.cloud.asset.v1p2beta1.Feed.getDefaultInstance() : feed_;
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1p2beta1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.asset.v1p2beta1.FeedOrBuilder getFeedOrBuilder() {
return feed_ == null ? com.google.cloud.asset.v1p2beta1.Feed.getDefaultInstance() : feed_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Required. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </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. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </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. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </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, getFeed());
}
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, getFeed());
}
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.asset.v1p2beta1.UpdateFeedRequest)) {
return super.equals(obj);
}
com.google.cloud.asset.v1p2beta1.UpdateFeedRequest other =
(com.google.cloud.asset.v1p2beta1.UpdateFeedRequest) obj;
if (hasFeed() != other.hasFeed()) return false;
if (hasFeed()) {
if (!getFeed().equals(other.getFeed())) 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 (hasFeed()) {
hash = (37 * hash) + FEED_FIELD_NUMBER;
hash = (53 * hash) + getFeed().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.asset.v1p2beta1.UpdateFeedRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.asset.v1p2beta1.UpdateFeedRequest 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.v1p2beta1.UpdateFeedRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.asset.v1p2beta1.UpdateFeedRequest 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.v1p2beta1.UpdateFeedRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.asset.v1p2beta1.UpdateFeedRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.asset.v1p2beta1.UpdateFeedRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.asset.v1p2beta1.UpdateFeedRequest 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.v1p2beta1.UpdateFeedRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.asset.v1p2beta1.UpdateFeedRequest 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.v1p2beta1.UpdateFeedRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.asset.v1p2beta1.UpdateFeedRequest 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.v1p2beta1.UpdateFeedRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Update asset feed request.
* </pre>
*
* Protobuf type {@code google.cloud.asset.v1p2beta1.UpdateFeedRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.asset.v1p2beta1.UpdateFeedRequest)
com.google.cloud.asset.v1p2beta1.UpdateFeedRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.asset.v1p2beta1.AssetServiceProto
.internal_static_google_cloud_asset_v1p2beta1_UpdateFeedRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.asset.v1p2beta1.AssetServiceProto
.internal_static_google_cloud_asset_v1p2beta1_UpdateFeedRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.asset.v1p2beta1.UpdateFeedRequest.class,
com.google.cloud.asset.v1p2beta1.UpdateFeedRequest.Builder.class);
}
// Construct using com.google.cloud.asset.v1p2beta1.UpdateFeedRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getFeedFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
feed_ = null;
if (feedBuilder_ != null) {
feedBuilder_.dispose();
feedBuilder_ = 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.asset.v1p2beta1.AssetServiceProto
.internal_static_google_cloud_asset_v1p2beta1_UpdateFeedRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.asset.v1p2beta1.UpdateFeedRequest getDefaultInstanceForType() {
return com.google.cloud.asset.v1p2beta1.UpdateFeedRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.asset.v1p2beta1.UpdateFeedRequest build() {
com.google.cloud.asset.v1p2beta1.UpdateFeedRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.asset.v1p2beta1.UpdateFeedRequest buildPartial() {
com.google.cloud.asset.v1p2beta1.UpdateFeedRequest result =
new com.google.cloud.asset.v1p2beta1.UpdateFeedRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.asset.v1p2beta1.UpdateFeedRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.feed_ = feedBuilder_ == null ? feed_ : feedBuilder_.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.asset.v1p2beta1.UpdateFeedRequest) {
return mergeFrom((com.google.cloud.asset.v1p2beta1.UpdateFeedRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.asset.v1p2beta1.UpdateFeedRequest other) {
if (other == com.google.cloud.asset.v1p2beta1.UpdateFeedRequest.getDefaultInstance())
return this;
if (other.hasFeed()) {
mergeFeed(other.getFeed());
}
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(getFeedFieldBuilder().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.asset.v1p2beta1.Feed feed_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.asset.v1p2beta1.Feed,
com.google.cloud.asset.v1p2beta1.Feed.Builder,
com.google.cloud.asset.v1p2beta1.FeedOrBuilder>
feedBuilder_;
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1p2beta1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the feed field is set.
*/
public boolean hasFeed() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1p2beta1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The feed.
*/
public com.google.cloud.asset.v1p2beta1.Feed getFeed() {
if (feedBuilder_ == null) {
return feed_ == null ? com.google.cloud.asset.v1p2beta1.Feed.getDefaultInstance() : feed_;
} else {
return feedBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1p2beta1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setFeed(com.google.cloud.asset.v1p2beta1.Feed value) {
if (feedBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
feed_ = value;
} else {
feedBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1p2beta1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setFeed(com.google.cloud.asset.v1p2beta1.Feed.Builder builderForValue) {
if (feedBuilder_ == null) {
feed_ = builderForValue.build();
} else {
feedBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1p2beta1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeFeed(com.google.cloud.asset.v1p2beta1.Feed value) {
if (feedBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& feed_ != null
&& feed_ != com.google.cloud.asset.v1p2beta1.Feed.getDefaultInstance()) {
getFeedBuilder().mergeFrom(value);
} else {
feed_ = value;
}
} else {
feedBuilder_.mergeFrom(value);
}
if (feed_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1p2beta1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearFeed() {
bitField0_ = (bitField0_ & ~0x00000001);
feed_ = null;
if (feedBuilder_ != null) {
feedBuilder_.dispose();
feedBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1p2beta1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.asset.v1p2beta1.Feed.Builder getFeedBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getFeedFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1p2beta1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.asset.v1p2beta1.FeedOrBuilder getFeedOrBuilder() {
if (feedBuilder_ != null) {
return feedBuilder_.getMessageOrBuilder();
} else {
return feed_ == null ? com.google.cloud.asset.v1p2beta1.Feed.getDefaultInstance() : feed_;
}
}
/**
*
*
* <pre>
* Required. The new values of feed details. It must match an existing feed
* and the field `name` must be in the format of:
* projects/project_number/feeds/feed_id or
* folders/folder_number/feeds/feed_id or
* organizations/organization_number/feeds/feed_id.
* </pre>
*
* <code>.google.cloud.asset.v1p2beta1.Feed feed = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.asset.v1p2beta1.Feed,
com.google.cloud.asset.v1p2beta1.Feed.Builder,
com.google.cloud.asset.v1p2beta1.FeedOrBuilder>
getFeedFieldBuilder() {
if (feedBuilder_ == null) {
feedBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.asset.v1p2beta1.Feed,
com.google.cloud.asset.v1p2beta1.Feed.Builder,
com.google.cloud.asset.v1p2beta1.FeedOrBuilder>(
getFeed(), getParentForChildren(), isClean());
feed_ = null;
}
return feedBuilder_;
}
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. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </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. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </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. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </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. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </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. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </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. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </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. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </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. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </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. Only updates the `feed` fields indicated by this mask.
* The field mask must not be empty, and it must not contain fields that
* are immutable or only set by the server.
* </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.asset.v1p2beta1.UpdateFeedRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.asset.v1p2beta1.UpdateFeedRequest)
private static final com.google.cloud.asset.v1p2beta1.UpdateFeedRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.asset.v1p2beta1.UpdateFeedRequest();
}
public static com.google.cloud.asset.v1p2beta1.UpdateFeedRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateFeedRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateFeedRequest>() {
@java.lang.Override
public UpdateFeedRequest 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<UpdateFeedRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateFeedRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.asset.v1p2beta1.UpdateFeedRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/harmony | 36,627 | classlib/modules/luni/src/main/java/java/util/SimpleTimeZone.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.util;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.security.AccessController;
import java.security.PrivilegedAction;
import org.apache.harmony.luni.internal.nls.Messages;
/**
* {@code SimpleTimeZone} is a concrete subclass of {@code TimeZone}
* that represents a time zone for use with a Gregorian calendar. This class
* does not handle historical changes.
* <p>
* Use a negative value for {@code dayOfWeekInMonth} to indicate that
* {@code SimpleTimeZone} should count from the end of the month
* backwards. For example, Daylight Savings Time ends at the last
* (dayOfWeekInMonth = -1) Sunday in October, at 2 AM in standard time.
*
* @see Calendar
* @see GregorianCalendar
* @see TimeZone
*/
public class SimpleTimeZone extends TimeZone {
private static final long serialVersionUID = -403250971215465050L;
private static com.ibm.icu.util.TimeZone getICUTimeZone(final String name){
return AccessController.doPrivileged(new PrivilegedAction<com.ibm.icu.util.TimeZone>(){
public com.ibm.icu.util.TimeZone run() {
return com.ibm.icu.util.TimeZone.getTimeZone(name);
}
});
}
private int rawOffset;
private int startYear, startMonth, startDay, startDayOfWeek, startTime;
private int endMonth, endDay, endDayOfWeek, endTime;
private int startMode, endMode;
private static final int DOM_MODE = 1, DOW_IN_MONTH_MODE = 2,
DOW_GE_DOM_MODE = 3, DOW_LE_DOM_MODE = 4;
/**
* The constant for representing a start or end time in GMT time mode.
*/
public static final int UTC_TIME = 2;
/**
* The constant for representing a start or end time in standard local time mode,
* based on timezone's raw offset from GMT; does not include Daylight
* savings.
*/
public static final int STANDARD_TIME = 1;
/**
* The constant for representing a start or end time in local wall clock time
* mode, based on timezone's adjusted offset from GMT; includes
* Daylight savings.
*/
public static final int WALL_TIME = 0;
private boolean useDaylight;
private GregorianCalendar daylightSavings;
private int dstSavings = 3600000;
private final transient com.ibm.icu.util.TimeZone icuTZ;
private final transient boolean isSimple;
/**
* Constructs a {@code SimpleTimeZone} with the given base time zone offset from GMT
* and time zone ID. Timezone IDs can be obtained from
* {@code TimeZone.getAvailableIDs}. Normally you should use {@code TimeZone.getDefault} to
* construct a {@code TimeZone}.
*
* @param offset
* the given base time zone offset to GMT.
* @param name
* the time zone ID which is obtained from
* {@code TimeZone.getAvailableIDs}.
*/
public SimpleTimeZone(int offset, final String name) {
setID(name);
rawOffset = offset;
icuTZ = getICUTimeZone(name);
if (icuTZ instanceof com.ibm.icu.util.SimpleTimeZone) {
isSimple = true;
icuTZ.setRawOffset(offset);
} else {
isSimple = false;
}
useDaylight = icuTZ.useDaylightTime();
}
/**
* Constructs a {@code SimpleTimeZone} with the given base time zone offset from GMT,
* time zone ID, and times to start and end the daylight savings time. Timezone IDs can
* be obtained from {@code TimeZone.getAvailableIDs}. Normally you should use
* {@code TimeZone.getDefault} to create a {@code TimeZone}. For a time zone that does not
* use daylight saving time, do not use this constructor; instead you should
* use {@code SimpleTimeZone(rawOffset, ID)}.
* <p>
* By default, this constructor specifies day-of-week-in-month rules. That
* is, if the {@code startDay} is 1, and the {@code startDayOfWeek} is {@code SUNDAY}, then this
* indicates the first Sunday in the {@code startMonth}. A {@code startDay} of -1 likewise
* indicates the last Sunday. However, by using negative or zero values for
* certain parameters, other types of rules can be specified.
* <p>
* Day of month: To specify an exact day of the month, such as March 1, set
* {@code startDayOfWeek} to zero.
* <p>
* Day of week after day of month: To specify the first day of the week
* occurring on or after an exact day of the month, make the day of the week
* negative. For example, if {@code startDay} is 5 and {@code startDayOfWeek} is {@code -MONDAY},
* this indicates the first Monday on or after the 5th day of the
* {@code startMonth}.
* <p>
* Day of week before day of month: To specify the last day of the week
* occurring on or before an exact day of the month, make the day of the
* week and the day of the month negative. For example, if {@code startDay} is {@code -21}
* and {@code startDayOfWeek} is {@code -WEDNESDAY}, this indicates the last Wednesday on or
* before the 21st of the {@code startMonth}.
* <p>
* The above examples refer to the {@code startMonth}, {@code startDay}, and {@code startDayOfWeek};
* the same applies for the {@code endMonth}, {@code endDay}, and {@code endDayOfWeek}.
* <p>
* The daylight savings time difference is set to the default value: one hour.
*
* @param offset
* the given base time zone offset to GMT.
* @param name
* the time zone ID which is obtained from
* {@code TimeZone.getAvailableIDs}.
* @param startMonth
* the daylight savings starting month. The month indexing is 0-based. eg, 0
* for January.
* @param startDay
* the daylight savings starting day-of-week-in-month. Please see
* the member description for an example.
* @param startDayOfWeek
* the daylight savings starting day-of-week. Please see the
* member description for an example.
* @param startTime
* the daylight savings starting time in local wall time, which
* is standard time in this case. Please see the member
* description for an example.
* @param endMonth
* the daylight savings ending month. The month indexing is 0-based. eg, 0 for
* January.
* @param endDay
* the daylight savings ending day-of-week-in-month. Please see
* the member description for an example.
* @param endDayOfWeek
* the daylight savings ending day-of-week. Please see the member
* description for an example.
* @param endTime
* the daylight savings ending time in local wall time, which is
* daylight time in this case. Please see the member description
* for an example.
* @throws IllegalArgumentException
* if the month, day, dayOfWeek, or time parameters are out of
* range for the start or end rule.
*/
public SimpleTimeZone(int offset, String name, int startMonth,
int startDay, int startDayOfWeek, int startTime, int endMonth,
int endDay, int endDayOfWeek, int endTime) {
this(offset, name, startMonth, startDay, startDayOfWeek, startTime,
endMonth, endDay, endDayOfWeek, endTime, 3600000);
}
/**
* Constructs a {@code SimpleTimeZone} with the given base time zone offset from GMT,
* time zone ID, times to start and end the daylight savings time, and
* the daylight savings time difference in milliseconds.
*
* @param offset
* the given base time zone offset to GMT.
* @param name
* the time zone ID which is obtained from
* {@code TimeZone.getAvailableIDs}.
* @param startMonth
* the daylight savings starting month. Month is 0-based. eg, 0
* for January.
* @param startDay
* the daylight savings starting day-of-week-in-month. Please see
* the description of {@link #SimpleTimeZone(int, String, int, int, int, int, int, int, int, int)} for an example.
* @param startDayOfWeek
* the daylight savings starting day-of-week. Please see the
* description of {@link #SimpleTimeZone(int, String, int, int, int, int, int, int, int, int)} for an example.
* @param startTime
* The daylight savings starting time in local wall time, which
* is standard time in this case. Please see the description of
* {@link #SimpleTimeZone(int, String, int, int, int, int, int, int, int, int)} for an example.
* @param endMonth
* the daylight savings ending month. Month is 0-based. eg, 0 for
* January.
* @param endDay
* the daylight savings ending day-of-week-in-month. Please see
* the description of {@link #SimpleTimeZone(int, String, int, int, int, int, int, int, int, int)} for an example.
* @param endDayOfWeek
* the daylight savings ending day-of-week. Please see the description of
* {@link #SimpleTimeZone(int, String, int, int, int, int, int, int, int, int)} for an example.
* @param endTime
* the daylight savings ending time in local wall time, which is
* daylight time in this case. Please see the description of {@link #SimpleTimeZone(int, String, int, int, int, int, int, int, int, int)}
* for an example.
* @param daylightSavings
* the daylight savings time difference in milliseconds.
* @throws IllegalArgumentException
* if the month, day, dayOfWeek, or time parameters are out of
* range for the start or end rule.
*/
public SimpleTimeZone(int offset, String name, int startMonth,
int startDay, int startDayOfWeek, int startTime, int endMonth,
int endDay, int endDayOfWeek, int endTime, int daylightSavings) {
icuTZ = getICUTimeZone(name);
if (icuTZ instanceof com.ibm.icu.util.SimpleTimeZone) {
isSimple = true;
com.ibm.icu.util.SimpleTimeZone tz = (com.ibm.icu.util.SimpleTimeZone)icuTZ;
tz.setRawOffset(offset);
tz.setStartRule(startMonth, startDay, startDayOfWeek, startTime);
tz.setEndRule(endMonth, endDay, endDayOfWeek, endTime);
tz.setDSTSavings(daylightSavings);
} else {
isSimple = false;
}
setID(name);
rawOffset = offset;
if (daylightSavings <= 0) {
throw new IllegalArgumentException(Messages.getString(
"luni.3B", daylightSavings)); //$NON-NLS-1$
}
dstSavings = daylightSavings;
setStartRule(startMonth, startDay, startDayOfWeek, startTime);
setEndRule(endMonth, endDay, endDayOfWeek, endTime);
useDaylight = daylightSavings > 0 || icuTZ.useDaylightTime();
}
/**
* Construct a {@code SimpleTimeZone} with the given base time zone offset from GMT,
* time zone ID, times to start and end the daylight savings time including a
* mode specifier, the daylight savings time difference in milliseconds.
* The mode specifies either {@link #WALL_TIME}, {@link #STANDARD_TIME}, or
* {@link #UTC_TIME}.
*
* @param offset
* the given base time zone offset to GMT.
* @param name
* the time zone ID which is obtained from
* {@code TimeZone.getAvailableIDs}.
* @param startMonth
* the daylight savings starting month. The month indexing is 0-based. eg, 0
* for January.
* @param startDay
* the daylight savings starting day-of-week-in-month. Please see
* the description of {@link #SimpleTimeZone(int, String, int, int, int, int, int, int, int, int)} for an example.
* @param startDayOfWeek
* the daylight savings starting day-of-week. Please see the
* description of {@link #SimpleTimeZone(int, String, int, int, int, int, int, int, int, int)} for an example.
* @param startTime
* the time of day in milliseconds on which daylight savings
* time starts, based on the {@code startTimeMode}.
* @param startTimeMode
* the mode (UTC, standard, or wall time) of the start time
* value.
* @param endDay
* the day of the week on which daylight savings time ends.
* @param endMonth
* the daylight savings ending month. The month indexing is 0-based. eg, 0 for
* January.
* @param endDayOfWeek
* the daylight savings ending day-of-week. Please see the description of
* {@link #SimpleTimeZone(int, String, int, int, int, int, int, int, int, int)} for an example.
* @param endTime
* the time of day in milliseconds on which daylight savings
* time ends, based on the {@code endTimeMode}.
* @param endTimeMode
* the mode (UTC, standard, or wall time) of the end time value.
* @param daylightSavings
* the daylight savings time difference in milliseconds.
* @throws IllegalArgumentException
* if the month, day, dayOfWeek, or time parameters are out of
* range for the start or end rule.
*/
public SimpleTimeZone(int offset, String name, int startMonth,
int startDay, int startDayOfWeek, int startTime, int startTimeMode,
int endMonth, int endDay, int endDayOfWeek, int endTime,
int endTimeMode, int daylightSavings) {
this(offset, name, startMonth, startDay, startDayOfWeek, startTime,
endMonth, endDay, endDayOfWeek, endTime, daylightSavings);
startMode = startTimeMode;
endMode = endTimeMode;
}
/**
* Returns a new {@code SimpleTimeZone} with the same ID, {@code rawOffset} and daylight
* savings time rules as this SimpleTimeZone.
*
* @return a shallow copy of this {@code SimpleTimeZone}.
* @see java.lang.Cloneable
*/
@Override
public Object clone() {
SimpleTimeZone zone = (SimpleTimeZone) super.clone();
if (daylightSavings != null) {
zone.daylightSavings = (GregorianCalendar) daylightSavings.clone();
}
return zone;
}
/**
* Compares the specified object to this {@code SimpleTimeZone} and returns whether they
* are equal. The object must be an instance of {@code SimpleTimeZone} and have the
* same internal data.
*
* @param object
* the object to compare with this object.
* @return {@code true} if the specified object is equal to this
* {@code SimpleTimeZone}, {@code false} otherwise.
* @see #hashCode
*/
@Override
public boolean equals(Object object) {
if (!(object instanceof SimpleTimeZone)) {
return false;
}
SimpleTimeZone tz = (SimpleTimeZone) object;
return getID().equals(tz.getID())
&& rawOffset == tz.rawOffset
&& useDaylight == tz.useDaylight
&& (!useDaylight || (startYear == tz.startYear
&& startMonth == tz.startMonth
&& startDay == tz.startDay && startMode == tz.startMode
&& startDayOfWeek == tz.startDayOfWeek
&& startTime == tz.startTime && endMonth == tz.endMonth
&& endDay == tz.endDay
&& endDayOfWeek == tz.endDayOfWeek
&& endTime == tz.endTime && endMode == tz.endMode && dstSavings == tz.dstSavings));
}
@Override
public int getDSTSavings() {
if (!useDaylight) {
return 0;
}
return dstSavings;
}
@Override
public int getOffset(int era, int year, int month, int day, int dayOfWeek,
int time) {
if (era != GregorianCalendar.BC && era != GregorianCalendar.AD) {
throw new IllegalArgumentException(Messages.getString("luni.3C", era)); //$NON-NLS-1$
}
checkRange(month, dayOfWeek, time);
if (month != Calendar.FEBRUARY || day != 29 || !isLeapYear(year)) {
checkDay(month, day);
}
return icuTZ.getOffset(era, year, month, day, dayOfWeek, time);
}
@Override
public int getOffset(long time) {
return icuTZ.getOffset(time);
}
@Override
public int getRawOffset() {
return rawOffset;
}
/**
* Returns an integer hash code for the receiver. Objects which are equal
* return the same value for this method.
*
* @return the receiver's hash.
* @see #equals
*/
@Override
public synchronized int hashCode() {
int hashCode = getID().hashCode() + rawOffset;
if (useDaylight) {
hashCode += startYear + startMonth + startDay + startDayOfWeek
+ startTime + startMode + endMonth + endDay + endDayOfWeek
+ endTime + endMode + dstSavings;
}
return hashCode;
}
@Override
public boolean hasSameRules(TimeZone zone) {
if (!(zone instanceof SimpleTimeZone)) {
return false;
}
SimpleTimeZone tz = (SimpleTimeZone) zone;
if (useDaylight != tz.useDaylight) {
return false;
}
if (!useDaylight) {
return rawOffset == tz.rawOffset;
}
return rawOffset == tz.rawOffset && dstSavings == tz.dstSavings
&& startYear == tz.startYear && startMonth == tz.startMonth
&& startDay == tz.startDay && startMode == tz.startMode
&& startDayOfWeek == tz.startDayOfWeek
&& startTime == tz.startTime && endMonth == tz.endMonth
&& endDay == tz.endDay && endDayOfWeek == tz.endDayOfWeek
&& endTime == tz.endTime && endMode == tz.endMode;
}
@Override
public boolean inDaylightTime(Date time) {
return icuTZ.inDaylightTime(time);
}
private boolean isLeapYear(int year) {
if (year > 1582) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
return year % 4 == 0;
}
/**
* Sets the daylight savings offset in milliseconds for this {@code SimpleTimeZone}.
*
* @param milliseconds
* the daylight savings offset in milliseconds.
*/
public void setDSTSavings(int milliseconds) {
if (milliseconds > 0) {
dstSavings = milliseconds;
} else {
throw new IllegalArgumentException();
}
}
private void checkRange(int month, int dayOfWeek, int time) {
if (month < Calendar.JANUARY || month > Calendar.DECEMBER) {
throw new IllegalArgumentException(Messages.getString("luni.3D", month)); //$NON-NLS-1$
}
if (dayOfWeek < Calendar.SUNDAY || dayOfWeek > Calendar.SATURDAY) {
throw new IllegalArgumentException(Messages
.getString("luni.48", dayOfWeek)); //$NON-NLS-1$
}
if (time < 0 || time >= 24 * 3600000) {
throw new IllegalArgumentException(Messages.getString("luni.3E", time)); //$NON-NLS-1$
}
}
private void checkDay(int month, int day) {
if (day <= 0 || day > GregorianCalendar.DaysInMonth[month]) {
throw new IllegalArgumentException(Messages.getString("luni.3F", day)); //$NON-NLS-1$
}
}
private void setEndMode() {
if (endDayOfWeek == 0) {
endMode = DOM_MODE;
} else if (endDayOfWeek < 0) {
endDayOfWeek = -endDayOfWeek;
if (endDay < 0) {
endDay = -endDay;
endMode = DOW_LE_DOM_MODE;
} else {
endMode = DOW_GE_DOM_MODE;
}
} else {
endMode = DOW_IN_MONTH_MODE;
}
useDaylight = startDay != 0 && endDay != 0;
if (endDay != 0) {
checkRange(endMonth, endMode == DOM_MODE ? 1 : endDayOfWeek,
endTime);
if (endMode != DOW_IN_MONTH_MODE) {
checkDay(endMonth, endDay);
} else {
if (endDay < -5 || endDay > 5) {
throw new IllegalArgumentException(Messages.getString(
"luni.40", endDay)); //$NON-NLS-1$
}
}
}
if (endMode != DOM_MODE) {
endDayOfWeek--;
}
}
/**
* Sets the rule which specifies the end of daylight savings time.
*
* @param month
* the {@code Calendar} month in which daylight savings time ends.
* @param dayOfMonth
* the {@code Calendar} day of the month on which daylight savings time
* ends.
* @param time
* the time of day in milliseconds standard time on which
* daylight savings time ends.
*/
public void setEndRule(int month, int dayOfMonth, int time) {
endMonth = month;
endDay = dayOfMonth;
endDayOfWeek = 0; // Initialize this value for hasSameRules()
endTime = time;
setEndMode();
if (isSimple) {
((com.ibm.icu.util.SimpleTimeZone) icuTZ).setEndRule(month,
dayOfMonth, time);
}
}
/**
* Sets the rule which specifies the end of daylight savings time.
*
* @param month
* the {@code Calendar} month in which daylight savings time ends.
* @param day
* the occurrence of the day of the week on which daylight
* savings time ends.
* @param dayOfWeek
* the {@code Calendar} day of the week on which daylight savings time
* ends.
* @param time
* the time of day in milliseconds standard time on which
* daylight savings time ends.
*/
public void setEndRule(int month, int day, int dayOfWeek, int time) {
endMonth = month;
endDay = day;
endDayOfWeek = dayOfWeek;
endTime = time;
setEndMode();
if (isSimple) {
((com.ibm.icu.util.SimpleTimeZone) icuTZ).setEndRule(month, day,
dayOfWeek, time);
}
}
/**
* Sets the rule which specifies the end of daylight savings time.
*
* @param month
* the {@code Calendar} month in which daylight savings time ends.
* @param day
* the {@code Calendar} day of the month.
* @param dayOfWeek
* the {@code Calendar} day of the week on which daylight savings time
* ends.
* @param time
* the time of day in milliseconds on which daylight savings time
* ends.
* @param after
* selects the day after or before the day of month.
*/
public void setEndRule(int month, int day, int dayOfWeek, int time,
boolean after) {
endMonth = month;
endDay = after ? day : -day;
endDayOfWeek = -dayOfWeek;
endTime = time;
setEndMode();
if (isSimple) {
((com.ibm.icu.util.SimpleTimeZone) icuTZ).setEndRule(month, day,
dayOfWeek, time, after);
}
}
/**
* Sets the offset for standard time from GMT for this {@code SimpleTimeZone}.
*
* @param offset
* the offset from GMT of standard time in milliseconds.
*/
@Override
public void setRawOffset(int offset) {
rawOffset = offset;
icuTZ.setRawOffset(offset);
}
private void setStartMode() {
if (startDayOfWeek == 0) {
startMode = DOM_MODE;
} else if (startDayOfWeek < 0) {
startDayOfWeek = -startDayOfWeek;
if (startDay < 0) {
startDay = -startDay;
startMode = DOW_LE_DOM_MODE;
} else {
startMode = DOW_GE_DOM_MODE;
}
} else {
startMode = DOW_IN_MONTH_MODE;
}
useDaylight = startDay != 0 && endDay != 0;
if (startDay != 0) {
checkRange(startMonth, startMode == DOM_MODE ? 1 : startDayOfWeek,
startTime);
if (startMode != DOW_IN_MONTH_MODE) {
checkDay(startMonth, startDay);
} else {
if (startDay < -5 || startDay > 5) {
throw new IllegalArgumentException(Messages.getString(
"luni.40", startDay)); //$NON-NLS-1$
}
}
}
if (startMode != DOM_MODE) {
startDayOfWeek--;
}
}
/**
* Sets the rule which specifies the start of daylight savings time.
*
* @param month
* the {@code Calendar} month in which daylight savings time starts.
* @param dayOfMonth
* the {@code Calendar} day of the month on which daylight savings time
* starts.
* @param time
* the time of day in milliseconds on which daylight savings time
* starts.
*/
public void setStartRule(int month, int dayOfMonth, int time) {
startMonth = month;
startDay = dayOfMonth;
startDayOfWeek = 0; // Initialize this value for hasSameRules()
startTime = time;
setStartMode();
if (isSimple) {
((com.ibm.icu.util.SimpleTimeZone) icuTZ).setStartRule(month,
dayOfMonth, time);
}
}
/**
* Sets the rule which specifies the start of daylight savings time.
*
* @param month
* the {@code Calendar} month in which daylight savings time starts.
* @param day
* the occurrence of the day of the week on which daylight
* savings time starts.
* @param dayOfWeek
* the {@code Calendar} day of the week on which daylight savings time
* starts.
* @param time
* the time of day in milliseconds on which daylight savings time
* starts.
*/
public void setStartRule(int month, int day, int dayOfWeek, int time) {
startMonth = month;
startDay = day;
startDayOfWeek = dayOfWeek;
startTime = time;
setStartMode();
if (isSimple) {
((com.ibm.icu.util.SimpleTimeZone) icuTZ).setStartRule(month, day,
dayOfWeek, time);
}
}
/**
* Sets the rule which specifies the start of daylight savings time.
*
* @param month
* the {@code Calendar} month in which daylight savings time starts.
* @param day
* the {@code Calendar} day of the month.
* @param dayOfWeek
* the {@code Calendar} day of the week on which daylight savings time
* starts.
* @param time
* the time of day in milliseconds on which daylight savings time
* starts.
* @param after
* selects the day after or before the day of month.
*/
public void setStartRule(int month, int day, int dayOfWeek, int time,
boolean after) {
startMonth = month;
startDay = after ? day : -day;
startDayOfWeek = -dayOfWeek;
startTime = time;
setStartMode();
if (isSimple) {
((com.ibm.icu.util.SimpleTimeZone) icuTZ).setStartRule(month, day,
dayOfWeek, time, after);
}
}
/**
* Sets the starting year for daylight savings time in this {@code SimpleTimeZone}.
* Years before this start year will always be in standard time.
*
* @param year
* the starting year.
*/
public void setStartYear(int year) {
startYear = year;
useDaylight = true;
}
/**
* Returns the string representation of this {@code SimpleTimeZone}.
*
* @return the string representation of this {@code SimpleTimeZone}.
*/
@Override
public String toString() {
return getClass().getName()
+ "[id=" //$NON-NLS-1$
+ getID()
+ ",offset=" //$NON-NLS-1$
+ rawOffset
+ ",dstSavings=" //$NON-NLS-1$
+ dstSavings
+ ",useDaylight=" //$NON-NLS-1$
+ useDaylight
+ ",startYear=" //$NON-NLS-1$
+ startYear
+ ",startMode=" //$NON-NLS-1$
+ startMode
+ ",startMonth=" //$NON-NLS-1$
+ startMonth
+ ",startDay=" //$NON-NLS-1$
+ startDay
+ ",startDayOfWeek=" //$NON-NLS-1$
+ (useDaylight && (startMode != DOM_MODE) ? startDayOfWeek + 1
: 0) + ",startTime=" + startTime + ",endMode=" //$NON-NLS-1$ //$NON-NLS-2$
+ endMode + ",endMonth=" + endMonth + ",endDay=" + endDay //$NON-NLS-1$ //$NON-NLS-2$
+ ",endDayOfWeek=" //$NON-NLS-1$
+ (useDaylight && (endMode != DOM_MODE) ? endDayOfWeek + 1 : 0)
+ ",endTime=" + endTime + "]"; //$NON-NLS-1$//$NON-NLS-2$
}
@Override
public boolean useDaylightTime() {
return useDaylight;
}
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("dstSavings", Integer.TYPE), //$NON-NLS-1$
new ObjectStreamField("endDay", Integer.TYPE), //$NON-NLS-1$
new ObjectStreamField("endDayOfWeek", Integer.TYPE), //$NON-NLS-1$
new ObjectStreamField("endMode", Integer.TYPE), //$NON-NLS-1$
new ObjectStreamField("endMonth", Integer.TYPE), //$NON-NLS-1$
new ObjectStreamField("endTime", Integer.TYPE), //$NON-NLS-1$
new ObjectStreamField("monthLength", byte[].class), //$NON-NLS-1$
new ObjectStreamField("rawOffset", Integer.TYPE), //$NON-NLS-1$
new ObjectStreamField("serialVersionOnStream", Integer.TYPE), //$NON-NLS-1$
new ObjectStreamField("startDay", Integer.TYPE), //$NON-NLS-1$
new ObjectStreamField("startDayOfWeek", Integer.TYPE), //$NON-NLS-1$
new ObjectStreamField("startMode", Integer.TYPE), //$NON-NLS-1$
new ObjectStreamField("startMonth", Integer.TYPE), //$NON-NLS-1$
new ObjectStreamField("startTime", Integer.TYPE), //$NON-NLS-1$
new ObjectStreamField("startYear", Integer.TYPE), //$NON-NLS-1$
new ObjectStreamField("useDaylight", Boolean.TYPE), }; //$NON-NLS-1$
private void writeObject(ObjectOutputStream stream) throws IOException {
int sEndDay = endDay, sEndDayOfWeek = endDayOfWeek + 1, sStartDay = startDay, sStartDayOfWeek = startDayOfWeek + 1;
if (useDaylight
&& (startMode != DOW_IN_MONTH_MODE || endMode != DOW_IN_MONTH_MODE)) {
Calendar cal = new GregorianCalendar(this);
if (endMode != DOW_IN_MONTH_MODE) {
cal.set(Calendar.MONTH, endMonth);
cal.set(Calendar.DATE, endDay);
sEndDay = cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);
if (endMode == DOM_MODE) {
sEndDayOfWeek = cal.getFirstDayOfWeek();
}
}
if (startMode != DOW_IN_MONTH_MODE) {
cal.set(Calendar.MONTH, startMonth);
cal.set(Calendar.DATE, startDay);
sStartDay = cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);
if (startMode == DOM_MODE) {
sStartDayOfWeek = cal.getFirstDayOfWeek();
}
}
}
ObjectOutputStream.PutField fields = stream.putFields();
fields.put("dstSavings", dstSavings); //$NON-NLS-1$
fields.put("endDay", sEndDay); //$NON-NLS-1$
fields.put("endDayOfWeek", sEndDayOfWeek); //$NON-NLS-1$
fields.put("endMode", endMode); //$NON-NLS-1$
fields.put("endMonth", endMonth); //$NON-NLS-1$
fields.put("endTime", endTime); //$NON-NLS-1$
fields.put("monthLength", GregorianCalendar.DaysInMonth); //$NON-NLS-1$
fields.put("rawOffset", rawOffset); //$NON-NLS-1$
fields.put("serialVersionOnStream", 1); //$NON-NLS-1$
fields.put("startDay", sStartDay); //$NON-NLS-1$
fields.put("startDayOfWeek", sStartDayOfWeek); //$NON-NLS-1$
fields.put("startMode", startMode); //$NON-NLS-1$
fields.put("startMonth", startMonth); //$NON-NLS-1$
fields.put("startTime", startTime); //$NON-NLS-1$
fields.put("startYear", startYear); //$NON-NLS-1$
fields.put("useDaylight", useDaylight); //$NON-NLS-1$
stream.writeFields();
stream.writeInt(4);
byte[] values = new byte[4];
values[0] = (byte) startDay;
values[1] = (byte) (startMode == DOM_MODE ? 0 : startDayOfWeek + 1);
values[2] = (byte) endDay;
values[3] = (byte) (endMode == DOM_MODE ? 0 : endDayOfWeek + 1);
stream.write(values);
}
private void readObject(ObjectInputStream stream) throws IOException,
ClassNotFoundException {
ObjectInputStream.GetField fields = stream.readFields();
rawOffset = fields.get("rawOffset", 0); //$NON-NLS-1$
useDaylight = fields.get("useDaylight", false); //$NON-NLS-1$
if (useDaylight) {
endMonth = fields.get("endMonth", 0); //$NON-NLS-1$
endTime = fields.get("endTime", 0); //$NON-NLS-1$
startMonth = fields.get("startMonth", 0); //$NON-NLS-1$
startTime = fields.get("startTime", 0); //$NON-NLS-1$
startYear = fields.get("startYear", 0); //$NON-NLS-1$
}
if (fields.get("serialVersionOnStream", 0) == 0) { //$NON-NLS-1$
if (useDaylight) {
startMode = endMode = DOW_IN_MONTH_MODE;
endDay = fields.get("endDay", 0); //$NON-NLS-1$
endDayOfWeek = fields.get("endDayOfWeek", 0) - 1; //$NON-NLS-1$
startDay = fields.get("startDay", 0); //$NON-NLS-1$
startDayOfWeek = fields.get("startDayOfWeek", 0) - 1; //$NON-NLS-1$
}
} else {
dstSavings = fields.get("dstSavings", 0); //$NON-NLS-1$
if (useDaylight) {
endMode = fields.get("endMode", 0); //$NON-NLS-1$
startMode = fields.get("startMode", 0); //$NON-NLS-1$
int length = stream.readInt();
byte[] values = new byte[length];
stream.readFully(values);
if (length >= 4) {
startDay = values[0];
startDayOfWeek = values[1];
if (startMode != DOM_MODE) {
startDayOfWeek--;
}
endDay = values[2];
endDayOfWeek = values[3];
if (endMode != DOM_MODE) {
endDayOfWeek--;
}
}
}
}
}
}
|
apache/usergrid | 36,328 | stack/corepersistence/graph/src/test/java/org/apache/usergrid/persistence/graph/GraphManagerShardConsistencyIT.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.usergrid.persistence.graph;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Nullable;
import org.apache.usergrid.StressTest;
import org.apache.usergrid.persistence.model.util.UUIDGenerator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.usergrid.persistence.core.migration.schema.MigrationException;
import org.apache.usergrid.persistence.core.migration.schema.MigrationManager;
import org.apache.usergrid.persistence.core.scope.ApplicationScope;
import org.apache.usergrid.persistence.core.scope.ApplicationScopeImpl;
import org.apache.usergrid.persistence.core.util.IdGenerator;
import org.apache.usergrid.persistence.graph.guice.TestGraphModule;
import org.apache.usergrid.persistence.graph.impl.SimpleSearchByEdgeType;
import org.apache.usergrid.persistence.graph.serialization.impl.shard.DirectedEdgeMeta;
import org.apache.usergrid.persistence.graph.serialization.impl.shard.NodeShardCache;
import org.apache.usergrid.persistence.graph.serialization.impl.shard.Shard;
import org.apache.usergrid.persistence.graph.serialization.impl.shard.ShardEntryGroup;
import org.apache.usergrid.persistence.model.entity.Id;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Slf4jReporter;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.netflix.config.ConfigurationManager;
import rx.Observable;
import static org.apache.usergrid.persistence.graph.test.util.EdgeTestUtils.createEdge;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
public class GraphManagerShardConsistencyIT {
private static final Logger logger = LoggerFactory.getLogger( GraphManagerShardConsistencyIT.class );
private static final MetricRegistry registry = new MetricRegistry();
private static final Meter writeMeter = registry.meter( "writeThroughput" );
private Slf4jReporter reporter;
protected ApplicationScope scope;
protected Object originalShardSize;
protected Object originalShardTimeout;
protected Object originalShardDelta;
protected ListeningExecutorService writeExecutor;
protected ListeningExecutorService deleteExecutor;
protected int TARGET_NUM_SHARDS = 5;
protected int POST_WRITE_SLEEP = 2000;
@Before
public void setupOrg() {
originalShardSize = ConfigurationManager.getConfigInstance().getProperty( GraphFig.SHARD_SIZE );
originalShardTimeout = ConfigurationManager.getConfigInstance().getProperty( GraphFig.SHARD_CACHE_TIMEOUT );
originalShardDelta = ConfigurationManager.getConfigInstance().getProperty( GraphFig.SHARD_MIN_DELTA );
ConfigurationManager.getConfigInstance().setProperty( GraphFig.SHARD_SIZE, 10000 );
final long cacheTimeout = 1000;
//set our cache timeout to the above value
ConfigurationManager.getConfigInstance().setProperty( GraphFig.SHARD_CACHE_TIMEOUT, cacheTimeout );
final long minDelta = ( long ) ( cacheTimeout * 2.5 );
ConfigurationManager.getConfigInstance().setProperty( GraphFig.SHARD_MIN_DELTA, minDelta );
// get the system property of the UUID to use. If one is not set, use the defualt
String uuidString = System.getProperty( "org.id", "80a42760-b699-11e3-a5e2-0800200c9a66" );
scope = new ApplicationScopeImpl( IdGenerator.createId(UUIDGenerator.newTimeUUID(), "test" ) );
reporter =
Slf4jReporter.forRegistry( registry ).outputTo(logger).convertRatesTo( TimeUnit.SECONDS )
.convertDurationsTo( TimeUnit.MILLISECONDS ).build();
reporter.start( 10, TimeUnit.SECONDS );
}
@After
public void tearDown() throws Exception {
reporter.stop();
reporter.report();
if(writeExecutor != null && !writeExecutor.isShutdown()){
writeExecutor.shutdownNow();
writeExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS);
}
if(deleteExecutor != null && !deleteExecutor.isShutdown()){
deleteExecutor.shutdownNow();
deleteExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS);
}
Thread.sleep(3000);
}
private void createWriteExecutor( final int size ) {
writeExecutor = MoreExecutors.listeningDecorator( Executors.newFixedThreadPool( size ) );
}
private void createDeleteExecutor( final int size ) {
deleteExecutor = MoreExecutors.listeningDecorator( Executors.newFixedThreadPool( size ) );
}
@Test(timeout=300000) // set a timeout so this doesn't run forever in the event that it is failing
public void writeThousandsSingleSource()
throws InterruptedException, ExecutionException, MigrationException, UnsupportedEncodingException {
final Id sourceId = IdGenerator.createId( "sourceWrite" );
final String edgeType = "testWrite";
final EdgeGenerator generator = new EdgeGenerator() {
@Override
public Edge newEdge() {
Edge edge = createEdge( sourceId, edgeType, IdGenerator.createId( "targetWrite" ) );
return edge;
}
@Override
public Observable<MarkedEdge> doSearch( final GraphManager manager ) {
return manager.loadEdgesFromSource(
new SimpleSearchByEdgeType( sourceId, edgeType, Long.MAX_VALUE, SearchByEdgeType.Order.DESCENDING,
Optional.<Edge>absent() ) );
}
};
final int numInjectors = 2;
/**
* create injectors. This way all the caches are independent of one another. This is the same as
* multiple nodes if there are multiple injectors
*/
final List<Injector> injectors = createInjectors( numInjectors );
final GraphFig graphFig = getInstance( injectors, GraphFig.class );
final long shardSize = graphFig.getShardSize();
//we don't want to starve the cass runtime since it will be on the same box. Only take 50% of processing
// power for writes
final int numProcessors = Runtime.getRuntime().availableProcessors() / 2;
final int numWorkersPerInjector = numProcessors / numInjectors;
final long numberOfEdges = shardSize * TARGET_NUM_SHARDS;
final long workerWriteLimit = numberOfEdges / numWorkersPerInjector / numInjectors;
createWriteExecutor( numWorkersPerInjector );
final AtomicLong writeCounter = new AtomicLong();
//min stop time the min delta + 1 cache cycle timeout
final long minExecutionTime = graphFig.getShardMinDelta() + graphFig.getShardCacheTimeout() + 120000;
logger.info( "Writing {} edges per worker on {} workers in {} injectors", workerWriteLimit, numWorkersPerInjector,
numInjectors );
final List<Future<Boolean>> futures = new ArrayList<>();
for ( Injector injector : injectors ) {
final GraphManagerFactory gmf = injector.getInstance( GraphManagerFactory.class );
for ( int i = 0; i < numWorkersPerInjector; i++ ) {
Future<Boolean> future =
writeExecutor.submit( new Worker( gmf, generator, workerWriteLimit, minExecutionTime, writeCounter) );
futures.add( future );
}
}
/**
* Wait for all writes to complete
*/
for ( Future<Boolean> future : futures ) {
future.get();
}
//now get all our shards
final NodeShardCache cache = getInstance( injectors, NodeShardCache.class );
final DirectedEdgeMeta directedEdgeMeta = DirectedEdgeMeta.fromSourceNode( sourceId, edgeType );
//now submit the readers.
final GraphManagerFactory gmf = getInstance( injectors, GraphManagerFactory.class );
final long writeCount = writeCounter.get();
final long expectedShardCount = writeCount / shardSize;
final Meter readMeter = registry.meter( "readThroughput-writeTest" );
final List<Throwable> failures = new ArrayList<>();
logger.info("Sleeping {}ms before reading to ensure all compactions have completed", POST_WRITE_SLEEP);
Thread.sleep(POST_WRITE_SLEEP); // let's make sure everything is written
for(int i = 0; i < 2; i ++) {
/**
* Start reading continuously while we migrate data to ensure our view is always correct
*/
final ListenableFuture<Long> future =
writeExecutor.submit( new ReadWorker( gmf, generator, writeCount, readMeter ) );
//add the future
Futures.addCallback( future, new FutureCallback<Long>() {
@Override
public void onSuccess( @Nullable final Long result ) {
logger.info( "Successfully ran the read, re-running" );
if( !writeExecutor.isShutdown() ) {
writeExecutor.submit(new ReadWorker(gmf, generator, writeCount, readMeter));
}
}
@Override
public void onFailure( final Throwable t ) {
failures.add( t );
logger.error( "Failed test!", t );
final Iterator<ShardEntryGroup> groups = cache.getReadShardGroup( scope, Long.MAX_VALUE, directedEdgeMeta );
while ( groups.hasNext() ) {
logger.info( "Shard entry group: {}", groups.next() );
}
}
} );
}
int compactedCount;
// now start the compaction watcher
while ( true ) {
if ( !failures.isEmpty() ) {
StringBuilder builder = new StringBuilder();
builder.append( "Read runner failed!\n" );
for ( Throwable t : failures ) {
builder.append( "Exception is: " );
ByteArrayOutputStream output = new ByteArrayOutputStream();
t.printStackTrace( new PrintWriter( output ) );
builder.append( output.toString( "UTF-8" ) );
builder.append( "\n\n" );
}
fail( builder.toString() );
}
// reset our count. Ultimately we'll have 4 groups once our compaction completes
compactedCount = 0;
// we have to get it from the cache, because this will trigger the compaction process
final Iterator<ShardEntryGroup> groups = cache.getReadShardGroup( scope, Long.MAX_VALUE, directedEdgeMeta );
final Set<ShardEntryGroup> shardEntryGroups = new HashSet<>();
while ( groups.hasNext() ) {
final ShardEntryGroup group = groups.next();
shardEntryGroups.add( group );
logger.info( "Compaction pending status for group {} is {}", group, group.isCompactionPending() );
if ( !group.isCompactionPending() ) {
compactedCount++;
}
}
//we're done
if ( compactedCount >= expectedShardCount ) {
logger.info( "All compactions complete, sleeping. Compacted shard count={}, expected shard count={}",
compactedCount, expectedShardCount );
break;
}
Thread.sleep( 2000 );
}
//now continue reading everything for 30 seconds to make sure things are OK
Thread.sleep(30000);
//writeExecutor.shutdownNow();
//writeExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS);
}
private <T> T getInstance( final List<Injector> injectors, Class<T> clazz ) {
return injectors.get( 0 ).getInstance( clazz );
}
/**
* Create new Guice injector environments and return them
*/
private List<Injector> createInjectors( int count ) throws MigrationException {
final List<Injector> injectors = new ArrayList<>( count );
for ( int i = 0; i < count; i++ ) {
final Injector injector = Guice.createInjector( new TestGraphModule() );
injectors.add( injector );
}
final MigrationManager migrationManager = getInstance( injectors, MigrationManager.class );
migrationManager.migrate(false);
return injectors;
}
@Test(timeout=300000) // this test is SLOW as deletes are intensive and shard cleanup is async
@Category(StressTest.class)
public void writeThousandsDelete()
throws InterruptedException, ExecutionException, MigrationException, UnsupportedEncodingException {
final Id sourceId = IdGenerator.createId( "sourceDelete" );
final String deleteEdgeType = "testDelete";
final EdgeGenerator generator = new EdgeGenerator() {
@Override
public Edge newEdge() {
Edge edge = createEdge( sourceId, deleteEdgeType, IdGenerator.createId( "targetDelete" ) );
return edge;
}
@Override
public Observable<MarkedEdge> doSearch( final GraphManager manager ) {
return manager.loadEdgesFromSource(
new SimpleSearchByEdgeType( sourceId, deleteEdgeType, Long.MAX_VALUE, SearchByEdgeType.Order.DESCENDING,
Optional.<Edge>absent(), false ) );
}
};
final int numInjectors = 3;
/**
* create injectors. This way all the caches are independent of one another. This is the same as
* multiple nodes if there are multiple injectors
*/
final List<Injector> injectors = createInjectors( numInjectors );
final GraphFig graphFig = getInstance( injectors, GraphFig.class );
final long shardSize = graphFig.getShardSize();
//we don't want to starve the cass runtime since it will be on the same box. Only take 50% of processing
// power for writes
final int numProcessors = Runtime.getRuntime().availableProcessors() / 2;
final int numWorkersPerInjector = numProcessors / numInjectors;
final long numberOfEdges = shardSize * TARGET_NUM_SHARDS;
final long workerWriteLimit = numberOfEdges / numWorkersPerInjector / numInjectors;
createDeleteExecutor( numWorkersPerInjector );
final AtomicLong writeCounter = new AtomicLong();
//min stop time the min delta + 1 cache cycle timeout
final long minExecutionTime = graphFig.getShardMinDelta() + graphFig.getShardCacheTimeout();
logger.info( "Writing {} edges per worker on {} workers in {} injectors", workerWriteLimit, numWorkersPerInjector,
numInjectors );
final List<Future<Boolean>> futures = new ArrayList<>();
for ( Injector injector : injectors ) {
final GraphManagerFactory gmf = injector.getInstance( GraphManagerFactory.class );
for ( int i = 0; i < numWorkersPerInjector; i++ ) {
Future<Boolean> future =
deleteExecutor.submit( new Worker( gmf, generator, workerWriteLimit, minExecutionTime, writeCounter) );
futures.add( future );
}
}
/**
* Wait for all writes to complete
*/
for ( Future<Boolean> future : futures ) {
future.get();
}
// now get all our shards
final NodeShardCache cache = getInstance( injectors, NodeShardCache.class );
final DirectedEdgeMeta directedEdgeMeta = DirectedEdgeMeta.fromSourceNode( sourceId, deleteEdgeType );
final GraphManagerFactory gmf = getInstance( injectors, GraphManagerFactory.class );
final long writeCount = writeCounter.get();
final Meter readMeter = registry.meter( "readThroughput-deleteTest" );
//check our shard state
final Iterator<ShardEntryGroup> existingShardGroups =
cache.getReadShardGroup( scope, Long.MAX_VALUE, directedEdgeMeta );
int shardCount = 0;
while ( existingShardGroups.hasNext() ) {
final ShardEntryGroup group = existingShardGroups.next();
shardCount++;
logger.info( "Compaction pending status for group {} is {}", group, group.isCompactionPending() );
}
logger.info( "Found {} shard groups", shardCount );
//now mark and delete all the edges
final GraphManager manager = gmf.createEdgeManager( scope );
//sleep occasionally to stop pushing cassandra over
long count = Long.MAX_VALUE;
Thread.sleep(3000); // let's make sure everything is written
long totalDeleted = 0;
// now do the deletes
while(count != 0) {
logger.info("total deleted: {}", totalDeleted);
if(count != Long.MAX_VALUE) { // count starts with Long.MAX
logger.info("deleted {} entities, continuing until count is 0", count);
}
//take 1000 then sleep
count = generator.doSearch( manager ).take( 1000 )
.filter(markedEdge -> {
// if it's already been marked let's filter, move on as async deleteEdge()
if(markedEdge.isDeleted()) {
logger.info("Edge already marked, but gm.deleteEdge() is async, Edge: {}", markedEdge);
}
//return !markedEdge.isDeleted();
return true;
})
.flatMap( edge -> manager.markEdge( edge ))
.flatMap( edge -> manager.deleteEdge( edge ) ).countLong().toBlocking().last();
totalDeleted += count;
logger.info("Sleeping 250ms second because deleteEdge() is async.");
Thread.sleep( 250 );
}
// loop with a reader until our shards are gone
/**
* Start reading continuously while we migrate data to ensure our view is always correct
*/
final ListenableFuture<Long> future = deleteExecutor.submit( new ReadWorker( gmf, generator, 0, readMeter ) );
final List<Throwable> failures = new ArrayList<>();
//add the future
Futures.addCallback( future, new FutureCallback<Long>() {
@Override
public void onSuccess( @Nullable final Long result ) {
logger.info( "Successfully ran the read, re-running" );
if( !deleteExecutor.isShutdown() ) {
deleteExecutor.submit(new ReadWorker(gmf, generator, 0, readMeter));
}
}
@Override
public void onFailure( final Throwable t ) {
failures.add( t );
logger.error( "Failed test!", t );
}
} );
Thread.sleep(3000); // let the edge readers start
// now loop check the shard count
while ( true ) {
if ( !failures.isEmpty() ) {
StringBuilder builder = new StringBuilder();
builder.append( "Read runner failed!\n" );
for ( Throwable t : failures ) {
builder.append( "Exception is: " );
ByteArrayOutputStream output = new ByteArrayOutputStream();
t.printStackTrace( new PrintWriter( output ) );
builder.append( output.toString( "UTF-8" ) );
builder.append( "\n\n" );
}
fail( builder.toString() );
}
//reset our count. Ultimately we'll have 4 groups once our compaction completes
shardCount = 0;
//we have to get it from the cache, because this will trigger the compaction process
final Iterator<ShardEntryGroup> groups = cache.getReadShardGroup( scope, Long.MAX_VALUE, directedEdgeMeta );
ShardEntryGroup group = null;
while ( groups.hasNext() ) {
group = groups.next();
logger.info( "Shard size for group is {}", group.getReadShards() );
Collection<Shard> shards = group.getReadShards();
for(Shard shard: shards){
if(!shard.isDeleted()){
shardCount++;
}
}
//shardCount += group.getReadShards().size();
}
// we're done, 1 shard remains, we have a group, and it's our default shard
if ( shardCount == 1 && group.getMinShard().getShardIndex() == Shard.MIN_SHARD.getShardIndex() ) {
logger.info( "All compactions complete," );
break;
}
Thread.sleep( 2000 );
}
//now that we have finished deleting and shards are removed, shutdown
//deleteExecutor.shutdownNow();
//deleteExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS);
}
@Test(timeout=300000) // this test is SLOW as deletes are intensive and shard cleanup is async
@Category(StressTest.class)
public void writeThousandsDeleteWriteAgain()
throws InterruptedException, ExecutionException, MigrationException, UnsupportedEncodingException {
ConfigurationManager.getConfigInstance().setProperty( GraphFig.SHARD_SIZE, 2000 );
final Id sourceId = IdGenerator.createId( "sourceDeleteRewrite" );
final String deleteEdgeType = "testDeleteRewrite";
final List<Edge> edges = new ArrayList<>();
final EdgeGenerator generator = new EdgeGenerator() {
@Override
public Edge newEdge() {
Edge edge = createEdge( sourceId, deleteEdgeType, IdGenerator.createId( "targetDeleteRewrite" ) );
edges.add(edge);
return edge;
}
@Override
public Observable<MarkedEdge> doSearch( final GraphManager manager ) {
return manager.loadEdgesFromSource(
new SimpleSearchByEdgeType( sourceId, deleteEdgeType, Long.MAX_VALUE, SearchByEdgeType.Order.DESCENDING,
Optional.<Edge>absent(), false ) );
}
};
final int numInjectors = 3;
/**
* create injectors. This way all the caches are independent of one another. This is the same as
* multiple nodes if there are multiple injectors
*/
final List<Injector> injectors = createInjectors( numInjectors );
final GraphFig graphFig = getInstance( injectors, GraphFig.class );
final long shardSize = graphFig.getShardSize();
//we don't want to starve the cass runtime since it will be on the same box. Only take 50% of processing
// power for writes
final int numProcessors = Runtime.getRuntime().availableProcessors() / 2;
final int numWorkersPerInjector = numProcessors / numInjectors;
final long numberOfEdges = shardSize * TARGET_NUM_SHARDS;
final long workerWriteLimit = numberOfEdges / numWorkersPerInjector / numInjectors;
createDeleteExecutor( numWorkersPerInjector );
final AtomicLong writeCounter = new AtomicLong();
//min stop time the min delta + 1 cache cycle timeout
final long minExecutionTime = graphFig.getShardMinDelta() + graphFig.getShardCacheTimeout();
logger.info( "Writing {} edges per worker on {} workers in {} injectors", workerWriteLimit, numWorkersPerInjector,
numInjectors );
final List<Future<Boolean>> futures = new ArrayList<>();
for ( Injector injector : injectors ) {
final GraphManagerFactory gmf = injector.getInstance( GraphManagerFactory.class );
for ( int i = 0; i < numWorkersPerInjector; i++ ) {
Future<Boolean> future =
deleteExecutor.submit( new Worker( gmf, generator, workerWriteLimit, minExecutionTime, writeCounter) );
futures.add( future );
}
}
/**
* Wait for all writes to complete
*/
for ( Future<Boolean> future : futures ) {
future.get();
}
// now get all our shards
final NodeShardCache cache = getInstance( injectors, NodeShardCache.class );
final DirectedEdgeMeta directedEdgeMeta = DirectedEdgeMeta.fromSourceNode( sourceId, deleteEdgeType );
final GraphManagerFactory gmf = getInstance( injectors, GraphManagerFactory.class );
final long writeCount = writeCounter.get();
final Meter readMeter = registry.meter( "readThroughput-deleteTestRewrite" );
//check our shard state
final Iterator<ShardEntryGroup> existingShardGroups =
cache.getReadShardGroup( scope, Long.MAX_VALUE, directedEdgeMeta );
int shardCount = 0;
while ( existingShardGroups.hasNext() ) {
final ShardEntryGroup group = existingShardGroups.next();
shardCount++;
logger.info( "Compaction pending status for group {} is {}", group, group.isCompactionPending() );
}
logger.info( "Found {} shard groups", shardCount );
//now mark and delete all the edges
final GraphManager manager = gmf.createEdgeManager( scope );
//sleep occasionally to stop pushing cassandra over
long count = Long.MAX_VALUE;
Thread.sleep(3000); // let's make sure everything is written
long totalDeleted = 0;
// now do the deletes
while(count != 0) {
logger.info("total deleted: {}", totalDeleted);
if(count != Long.MAX_VALUE) { // count starts with Long.MAX
logger.info("deleted {} entities, continuing until count is 0", count);
}
//take 1000 then sleep
count = generator.doSearch( manager ).take( 1000 )
.filter(markedEdge -> {
// if it's already been marked let's filter, move on as async deleteEdge()
if(markedEdge.isDeleted()){
logger.info("Edge already marked, gm.deleteEdge() is Async, Edge: {}", markedEdge);
}
//return !markedEdge.isDeleted();
return true;
})
.flatMap( edge -> manager.markEdge( edge ))
.flatMap( edge -> manager.deleteEdge( edge ) ).countLong().toBlocking().last();
totalDeleted += count;
logger.info("Sleeping 250ms second because deleteEdge() is an async process");
Thread.sleep( 250 );
}
logger.info("Sleeping before starting the read");
Thread.sleep(6000); // let the edge readers start
// loop with a reader until our shards are gone
GraphManager gm = gmf.createEdgeManager( scope );
//do a read to eventually trigger our group compaction. Take 2 pages of columns
long returnedEdgeCount = generator.doSearch( gm )
.doOnNext( edge -> readMeter.mark() )
.countLong().toBlocking().last();
logger.info( "Completed reading {} edges", returnedEdgeCount );
if ( 0 != returnedEdgeCount ) {
//logger.warn( "Unexpected edge count returned!!! Expected {} but was {}", 0,
// returnedEdgeCount );
fail("Unexpected edge count returned!!! Expected 0 but was "+ returnedEdgeCount );
}
logger.info("Got expected read count of 0");
//we have to get it from the cache, because this will trigger the compaction process
final Iterator<ShardEntryGroup> groups = cache.getReadShardGroup( scope, Long.MAX_VALUE, directedEdgeMeta );
ShardEntryGroup group = null;
while ( groups.hasNext() ) {
group = groups.next();
logger.info( "Shard size for group is {}", group.getReadShards() );
Collection<Shard> shards = group.getReadShards();
for(Shard shard: shards){
if(!shard.isDeleted()){
shardCount++;
}
}
}
// we're done, 1 shard remains, we have a group, and it's our default shard
if ( shardCount == 1 && group.getMinShard().getShardIndex() == Shard.MIN_SHARD.getShardIndex() ) {
logger.info( "All compactions complete," );
}
Thread.sleep( 2000 );
logger.info( "Re-Writing same edges", workerWriteLimit, numWorkersPerInjector,
numInjectors );
int edgeCount = 0;
if ( edges.size() > 0) {
for (Edge edge : edges) {
Edge returned = gm.writeEdge(edge).toBlocking().last();
assertNotNull("Returned has a version", returned.getTimestamp());
edgeCount++;
writeMeter.mark();
writeCounter.incrementAndGet();
if (edgeCount % 100 == 0) {
logger.info("wrote: " + edgeCount);
}
}
logger.info("Re-wrote total: {}", edgeCount);
}
int retries = 2;
while ( retries > 0 ) {
//do a read to eventually trigger our group compaction. Take 2 pages of columns
returnedEdgeCount = generator.doSearch( gm )
.doOnNext( edge -> readMeter.mark() )
.countLong().toBlocking().last();
logger.info( "Completed reading {} edges", returnedEdgeCount );
if ( edgeCount != returnedEdgeCount ) {
logger.warn( "Unexpected edge count returned!!! Expected {} but was {}", edgeCount,
returnedEdgeCount );
}
retries--;
if( returnedEdgeCount == edgeCount ){
logger.info("Got expected read count of {}", edgeCount);
break;
}
}
//we have to get it from the cache, because this will trigger the compaction process
final Iterator<ShardEntryGroup> finalgroups = cache.getReadShardGroup( scope, Long.MAX_VALUE, directedEdgeMeta );
ShardEntryGroup finalgroup = null;
// reset the shard count
shardCount = 0;
while ( finalgroups.hasNext() ) {
finalgroup = finalgroups.next();
logger.info( "Shard size for group is {}", finalgroup.getReadShards() );
Collection<Shard> shards = finalgroup.getReadShards();
for(Shard shard: shards){
if(!shard.isDeleted()){
shardCount++;
}
}
}
// we're done, 1 shard remains, we have a group, and it's our default shard
if ( shardCount > 1 ) {
logger.info( "All done. Final shard count: {}", shardCount );
assertEquals(1,1);
}else{
fail("There should be more than 1 shard");
}
//deleteExecutor.shutdownNow();
//deleteExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS);
}
private class Worker implements Callable<Boolean> {
private final GraphManagerFactory factory;
private final EdgeGenerator generator;
private final long writeLimit;
private final long minExecutionTime;
private final AtomicLong writeCounter;
private Worker(final GraphManagerFactory factory, final EdgeGenerator generator, final long writeLimit,
final long minExecutionTime, final AtomicLong writeCounter) {
this.factory = factory;
this.generator = generator;
this.writeLimit = writeLimit;
this.minExecutionTime = minExecutionTime;
this.writeCounter = writeCounter;
}
@Override
public Boolean call() throws Exception {
GraphManager manager = factory.createEdgeManager( scope );
final long startTime = System.currentTimeMillis();
for ( long i = 1; i < writeLimit +1 && System.currentTimeMillis() - startTime < minExecutionTime; i++ ) {
Edge edge = generator.newEdge();
Edge returned = manager.writeEdge( edge ).toBlocking().last();
assertNotNull( "Returned has a version", returned.getTimestamp() );
writeCounter.incrementAndGet();
if ( i % 100 == 0 ) {
logger.info( "wrote: " + i );
}
}
return true;
}
}
private class ReadWorker implements Callable<Long> {
private final GraphManagerFactory factory;
private final EdgeGenerator generator;
private final long writeCount;
private final Meter readMeter;
private ReadWorker( final GraphManagerFactory factory, final EdgeGenerator generator, final long writeCount,
final Meter readMeter ) {
this.factory = factory;
this.generator = generator;
this.writeCount = writeCount;
this.readMeter = readMeter;
}
@Override
public Long call() throws Exception {
GraphManager gm = factory.createEdgeManager( scope );
while ( !Thread.currentThread().isInterrupted() ) {
//do a read to eventually trigger our group compaction. Take 2 pages of columns
final long returnedEdgeCount = generator.doSearch( gm )
.doOnNext( edge -> readMeter.mark() )
.countLong().toBlocking().last();
logger.info( "Completed reading {} edges", returnedEdgeCount );
if ( writeCount != returnedEdgeCount ) {
logger.warn( "Unexpected edge count returned!!! Expected {} but was {}", writeCount,
returnedEdgeCount );
}
assertEquals( "Expected to read same edge count", writeCount, returnedEdgeCount );
}
return 0L;
}
}
private interface EdgeGenerator {
/**
* Create a new edge to persiste
*/
public Edge newEdge();
/**
* Perform the search returning an observable edge
*/
public Observable<MarkedEdge> doSearch( final GraphManager manager );
}
}
|
googleapis/google-cloud-java | 36,335 | java-shopping-css/proto-google-shopping-css-v1/src/main/java/com/google/shopping/css/v1/MethodDetails.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/css/v1/quota.proto
// Protobuf Java Version: 3.25.8
package com.google.shopping.css.v1;
/**
*
*
* <pre>
* The method details per method in the CSS API.
* </pre>
*
* Protobuf type {@code google.shopping.css.v1.MethodDetails}
*/
public final class MethodDetails extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.shopping.css.v1.MethodDetails)
MethodDetailsOrBuilder {
private static final long serialVersionUID = 0L;
// Use MethodDetails.newBuilder() to construct.
private MethodDetails(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private MethodDetails() {
method_ = "";
version_ = "";
subapi_ = "";
path_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new MethodDetails();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.shopping.css.v1.QuotaProto
.internal_static_google_shopping_css_v1_MethodDetails_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.shopping.css.v1.QuotaProto
.internal_static_google_shopping_css_v1_MethodDetails_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.shopping.css.v1.MethodDetails.class,
com.google.shopping.css.v1.MethodDetails.Builder.class);
}
public static final int METHOD_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object method_ = "";
/**
*
*
* <pre>
* Output only. The name of the method for example
* `cssproductsservice.listcssproducts`.
* </pre>
*
* <code>string method = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The method.
*/
@java.lang.Override
public java.lang.String getMethod() {
java.lang.Object ref = method_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
method_ = s;
return s;
}
}
/**
*
*
* <pre>
* Output only. The name of the method for example
* `cssproductsservice.listcssproducts`.
* </pre>
*
* <code>string method = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for method.
*/
@java.lang.Override
public com.google.protobuf.ByteString getMethodBytes() {
java.lang.Object ref = method_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
method_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VERSION_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object version_ = "";
/**
*
*
* <pre>
* Output only. The API version that the method belongs to.
* </pre>
*
* <code>string version = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The version.
*/
@java.lang.Override
public java.lang.String getVersion() {
java.lang.Object ref = version_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
version_ = s;
return s;
}
}
/**
*
*
* <pre>
* Output only. The API version that the method belongs to.
* </pre>
*
* <code>string version = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for version.
*/
@java.lang.Override
public com.google.protobuf.ByteString getVersionBytes() {
java.lang.Object ref = version_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
version_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SUBAPI_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object subapi_ = "";
/**
*
*
* <pre>
* Output only. The sub-API that the method belongs to. In the CSS API, this
* is always `css`.
* </pre>
*
* <code>string subapi = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The subapi.
*/
@java.lang.Override
public java.lang.String getSubapi() {
java.lang.Object ref = subapi_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
subapi_ = s;
return s;
}
}
/**
*
*
* <pre>
* Output only. The sub-API that the method belongs to. In the CSS API, this
* is always `css`.
* </pre>
*
* <code>string subapi = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for subapi.
*/
@java.lang.Override
public com.google.protobuf.ByteString getSubapiBytes() {
java.lang.Object ref = subapi_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
subapi_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PATH_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object path_ = "";
/**
*
*
* <pre>
* Output only. The path for the method such as
* `v1/cssproductsservice.listcssproducts`.
* </pre>
*
* <code>string path = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The path.
*/
@java.lang.Override
public java.lang.String getPath() {
java.lang.Object ref = path_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
path_ = s;
return s;
}
}
/**
*
*
* <pre>
* Output only. The path for the method such as
* `v1/cssproductsservice.listcssproducts`.
* </pre>
*
* <code>string path = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for path.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPathBytes() {
java.lang.Object ref = path_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
path_ = 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(method_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, method_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, version_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(subapi_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, subapi_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(path_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, path_);
}
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(method_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, method_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, version_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(subapi_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, subapi_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(path_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, path_);
}
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.css.v1.MethodDetails)) {
return super.equals(obj);
}
com.google.shopping.css.v1.MethodDetails other = (com.google.shopping.css.v1.MethodDetails) obj;
if (!getMethod().equals(other.getMethod())) return false;
if (!getVersion().equals(other.getVersion())) return false;
if (!getSubapi().equals(other.getSubapi())) return false;
if (!getPath().equals(other.getPath())) 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) + METHOD_FIELD_NUMBER;
hash = (53 * hash) + getMethod().hashCode();
hash = (37 * hash) + VERSION_FIELD_NUMBER;
hash = (53 * hash) + getVersion().hashCode();
hash = (37 * hash) + SUBAPI_FIELD_NUMBER;
hash = (53 * hash) + getSubapi().hashCode();
hash = (37 * hash) + PATH_FIELD_NUMBER;
hash = (53 * hash) + getPath().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.shopping.css.v1.MethodDetails parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.css.v1.MethodDetails 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.css.v1.MethodDetails parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.css.v1.MethodDetails 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.css.v1.MethodDetails parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.css.v1.MethodDetails parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.shopping.css.v1.MethodDetails parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.shopping.css.v1.MethodDetails 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.css.v1.MethodDetails parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.shopping.css.v1.MethodDetails 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.css.v1.MethodDetails parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.shopping.css.v1.MethodDetails 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.css.v1.MethodDetails 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 method details per method in the CSS API.
* </pre>
*
* Protobuf type {@code google.shopping.css.v1.MethodDetails}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.shopping.css.v1.MethodDetails)
com.google.shopping.css.v1.MethodDetailsOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.shopping.css.v1.QuotaProto
.internal_static_google_shopping_css_v1_MethodDetails_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.shopping.css.v1.QuotaProto
.internal_static_google_shopping_css_v1_MethodDetails_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.shopping.css.v1.MethodDetails.class,
com.google.shopping.css.v1.MethodDetails.Builder.class);
}
// Construct using com.google.shopping.css.v1.MethodDetails.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
method_ = "";
version_ = "";
subapi_ = "";
path_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.shopping.css.v1.QuotaProto
.internal_static_google_shopping_css_v1_MethodDetails_descriptor;
}
@java.lang.Override
public com.google.shopping.css.v1.MethodDetails getDefaultInstanceForType() {
return com.google.shopping.css.v1.MethodDetails.getDefaultInstance();
}
@java.lang.Override
public com.google.shopping.css.v1.MethodDetails build() {
com.google.shopping.css.v1.MethodDetails result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.shopping.css.v1.MethodDetails buildPartial() {
com.google.shopping.css.v1.MethodDetails result =
new com.google.shopping.css.v1.MethodDetails(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.shopping.css.v1.MethodDetails result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.method_ = method_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.version_ = version_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.subapi_ = subapi_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.path_ = path_;
}
}
@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.css.v1.MethodDetails) {
return mergeFrom((com.google.shopping.css.v1.MethodDetails) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.shopping.css.v1.MethodDetails other) {
if (other == com.google.shopping.css.v1.MethodDetails.getDefaultInstance()) return this;
if (!other.getMethod().isEmpty()) {
method_ = other.method_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getVersion().isEmpty()) {
version_ = other.version_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getSubapi().isEmpty()) {
subapi_ = other.subapi_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getPath().isEmpty()) {
path_ = other.path_;
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:
{
method_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
version_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
subapi_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
path_ = 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 method_ = "";
/**
*
*
* <pre>
* Output only. The name of the method for example
* `cssproductsservice.listcssproducts`.
* </pre>
*
* <code>string method = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The method.
*/
public java.lang.String getMethod() {
java.lang.Object ref = method_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
method_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Output only. The name of the method for example
* `cssproductsservice.listcssproducts`.
* </pre>
*
* <code>string method = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for method.
*/
public com.google.protobuf.ByteString getMethodBytes() {
java.lang.Object ref = method_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
method_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Output only. The name of the method for example
* `cssproductsservice.listcssproducts`.
* </pre>
*
* <code>string method = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @param value The method to set.
* @return This builder for chaining.
*/
public Builder setMethod(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
method_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The name of the method for example
* `cssproductsservice.listcssproducts`.
* </pre>
*
* <code>string method = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return This builder for chaining.
*/
public Builder clearMethod() {
method_ = getDefaultInstance().getMethod();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The name of the method for example
* `cssproductsservice.listcssproducts`.
* </pre>
*
* <code>string method = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @param value The bytes for method to set.
* @return This builder for chaining.
*/
public Builder setMethodBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
method_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object version_ = "";
/**
*
*
* <pre>
* Output only. The API version that the method belongs to.
* </pre>
*
* <code>string version = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The version.
*/
public java.lang.String getVersion() {
java.lang.Object ref = version_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
version_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Output only. The API version that the method belongs to.
* </pre>
*
* <code>string version = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for version.
*/
public com.google.protobuf.ByteString getVersionBytes() {
java.lang.Object ref = version_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
version_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Output only. The API version that the method belongs to.
* </pre>
*
* <code>string version = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @param value The version to set.
* @return This builder for chaining.
*/
public Builder setVersion(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
version_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The API version that the method belongs to.
* </pre>
*
* <code>string version = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return This builder for chaining.
*/
public Builder clearVersion() {
version_ = getDefaultInstance().getVersion();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The API version that the method belongs to.
* </pre>
*
* <code>string version = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @param value The bytes for version to set.
* @return This builder for chaining.
*/
public Builder setVersionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
version_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object subapi_ = "";
/**
*
*
* <pre>
* Output only. The sub-API that the method belongs to. In the CSS API, this
* is always `css`.
* </pre>
*
* <code>string subapi = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The subapi.
*/
public java.lang.String getSubapi() {
java.lang.Object ref = subapi_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
subapi_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Output only. The sub-API that the method belongs to. In the CSS API, this
* is always `css`.
* </pre>
*
* <code>string subapi = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for subapi.
*/
public com.google.protobuf.ByteString getSubapiBytes() {
java.lang.Object ref = subapi_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
subapi_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Output only. The sub-API that the method belongs to. In the CSS API, this
* is always `css`.
* </pre>
*
* <code>string subapi = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @param value The subapi to set.
* @return This builder for chaining.
*/
public Builder setSubapi(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
subapi_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The sub-API that the method belongs to. In the CSS API, this
* is always `css`.
* </pre>
*
* <code>string subapi = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return This builder for chaining.
*/
public Builder clearSubapi() {
subapi_ = getDefaultInstance().getSubapi();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The sub-API that the method belongs to. In the CSS API, this
* is always `css`.
* </pre>
*
* <code>string subapi = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @param value The bytes for subapi to set.
* @return This builder for chaining.
*/
public Builder setSubapiBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
subapi_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object path_ = "";
/**
*
*
* <pre>
* Output only. The path for the method such as
* `v1/cssproductsservice.listcssproducts`.
* </pre>
*
* <code>string path = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The path.
*/
public java.lang.String getPath() {
java.lang.Object ref = path_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
path_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Output only. The path for the method such as
* `v1/cssproductsservice.listcssproducts`.
* </pre>
*
* <code>string path = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for path.
*/
public com.google.protobuf.ByteString getPathBytes() {
java.lang.Object ref = path_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
path_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Output only. The path for the method such as
* `v1/cssproductsservice.listcssproducts`.
* </pre>
*
* <code>string path = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @param value The path to set.
* @return This builder for chaining.
*/
public Builder setPath(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
path_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The path for the method such as
* `v1/cssproductsservice.listcssproducts`.
* </pre>
*
* <code>string path = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return This builder for chaining.
*/
public Builder clearPath() {
path_ = getDefaultInstance().getPath();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The path for the method such as
* `v1/cssproductsservice.listcssproducts`.
* </pre>
*
* <code>string path = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @param value The bytes for path to set.
* @return This builder for chaining.
*/
public Builder setPathBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
path_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.shopping.css.v1.MethodDetails)
}
// @@protoc_insertion_point(class_scope:google.shopping.css.v1.MethodDetails)
private static final com.google.shopping.css.v1.MethodDetails DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.shopping.css.v1.MethodDetails();
}
public static com.google.shopping.css.v1.MethodDetails getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<MethodDetails> PARSER =
new com.google.protobuf.AbstractParser<MethodDetails>() {
@java.lang.Override
public MethodDetails 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<MethodDetails> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<MethodDetails> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.shopping.css.v1.MethodDetails getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,439 | java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/schema/trainingjob/definition/AutoMlTables.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1/schema/trainingjob/definition/automl_tables.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1.schema.trainingjob.definition;
/**
*
*
* <pre>
* A TrainingJob that trains and uploads an AutoML Tables Model.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables}
*/
public final class AutoMlTables extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables)
AutoMlTablesOrBuilder {
private static final long serialVersionUID = 0L;
// Use AutoMlTables.newBuilder() to construct.
private AutoMlTables(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private AutoMlTables() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new AutoMlTables();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMLTablesProto
.internal_static_google_cloud_aiplatform_v1_schema_trainingjob_definition_AutoMlTables_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMLTablesProto
.internal_static_google_cloud_aiplatform_v1_schema_trainingjob_definition_AutoMlTables_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables.class,
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables.Builder
.class);
}
private int bitField0_;
public static final int INPUTS_FIELD_NUMBER = 1;
private com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs inputs_;
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*
* @return Whether the inputs field is set.
*/
@java.lang.Override
public boolean hasInputs() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*
* @return The inputs.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs
getInputs() {
return inputs_ == null
? com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs
.getDefaultInstance()
: inputs_;
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputsOrBuilder
getInputsOrBuilder() {
return inputs_ == null
? com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs
.getDefaultInstance()
: inputs_;
}
public static final int METADATA_FIELD_NUMBER = 2;
private com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata
metadata_;
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*
* @return Whether the metadata field is set.
*/
@java.lang.Override
public boolean hasMetadata() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*
* @return The metadata.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata
getMetadata() {
return metadata_ == null
? com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata
.getDefaultInstance()
: metadata_;
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadataOrBuilder
getMetadataOrBuilder() {
return metadata_ == null
? com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata
.getDefaultInstance()
: metadata_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getInputs());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getMetadata());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getInputs());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getMetadata());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj
instanceof com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables other =
(com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables) obj;
if (hasInputs() != other.hasInputs()) return false;
if (hasInputs()) {
if (!getInputs().equals(other.getInputs())) return false;
}
if (hasMetadata() != other.hasMetadata()) return false;
if (hasMetadata()) {
if (!getMetadata().equals(other.getMetadata())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasInputs()) {
hash = (37 * hash) + INPUTS_FIELD_NUMBER;
hash = (53 * hash) + getInputs().hashCode();
}
if (hasMetadata()) {
hash = (37 * hash) + METADATA_FIELD_NUMBER;
hash = (53 * hash) + getMetadata().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* A TrainingJob that trains and uploads an AutoML Tables Model.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables)
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMLTablesProto
.internal_static_google_cloud_aiplatform_v1_schema_trainingjob_definition_AutoMlTables_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMLTablesProto
.internal_static_google_cloud_aiplatform_v1_schema_trainingjob_definition_AutoMlTables_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables.class,
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables.Builder
.class);
}
// Construct using
// com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getInputsFieldBuilder();
getMetadataFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
inputs_ = null;
if (inputsBuilder_ != null) {
inputsBuilder_.dispose();
inputsBuilder_ = null;
}
metadata_ = null;
if (metadataBuilder_ != null) {
metadataBuilder_.dispose();
metadataBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMLTablesProto
.internal_static_google_cloud_aiplatform_v1_schema_trainingjob_definition_AutoMlTables_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables build() {
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables result =
buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables
buildPartial() {
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables result =
new com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.inputs_ = inputsBuilder_ == null ? inputs_ : inputsBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.metadata_ = metadataBuilder_ == null ? metadata_ : metadataBuilder_.build();
to_bitField0_ |= 0x00000002;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other
instanceof com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables) {
return mergeFrom(
(com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables other) {
if (other
== com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables
.getDefaultInstance()) return this;
if (other.hasInputs()) {
mergeInputs(other.getInputs());
}
if (other.hasMetadata()) {
mergeMetadata(other.getMetadata());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(getInputsFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getMetadataFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs inputs_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs,
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs.Builder,
com.google.cloud.aiplatform.v1.schema.trainingjob.definition
.AutoMlTablesInputsOrBuilder>
inputsBuilder_;
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*
* @return Whether the inputs field is set.
*/
public boolean hasInputs() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*
* @return The inputs.
*/
public com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs
getInputs() {
if (inputsBuilder_ == null) {
return inputs_ == null
? com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs
.getDefaultInstance()
: inputs_;
} else {
return inputsBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*/
public Builder setInputs(
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs value) {
if (inputsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
inputs_ = value;
} else {
inputsBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*/
public Builder setInputs(
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs.Builder
builderForValue) {
if (inputsBuilder_ == null) {
inputs_ = builderForValue.build();
} else {
inputsBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*/
public Builder mergeInputs(
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs value) {
if (inputsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& inputs_ != null
&& inputs_
!= com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs
.getDefaultInstance()) {
getInputsBuilder().mergeFrom(value);
} else {
inputs_ = value;
}
} else {
inputsBuilder_.mergeFrom(value);
}
if (inputs_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*/
public Builder clearInputs() {
bitField0_ = (bitField0_ & ~0x00000001);
inputs_ = null;
if (inputsBuilder_ != null) {
inputsBuilder_.dispose();
inputsBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*/
public com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs.Builder
getInputsBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getInputsFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*/
public com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputsOrBuilder
getInputsOrBuilder() {
if (inputsBuilder_ != null) {
return inputsBuilder_.getMessageOrBuilder();
} else {
return inputs_ == null
? com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs
.getDefaultInstance()
: inputs_;
}
}
/**
*
*
* <pre>
* The input parameters of this TrainingJob.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs inputs = 1;
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs,
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs.Builder,
com.google.cloud.aiplatform.v1.schema.trainingjob.definition
.AutoMlTablesInputsOrBuilder>
getInputsFieldBuilder() {
if (inputsBuilder_ == null) {
inputsBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs,
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesInputs
.Builder,
com.google.cloud.aiplatform.v1.schema.trainingjob.definition
.AutoMlTablesInputsOrBuilder>(getInputs(), getParentForChildren(), isClean());
inputs_ = null;
}
return inputsBuilder_;
}
private com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata
metadata_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata,
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata
.Builder,
com.google.cloud.aiplatform.v1.schema.trainingjob.definition
.AutoMlTablesMetadataOrBuilder>
metadataBuilder_;
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*
* @return Whether the metadata field is set.
*/
public boolean hasMetadata() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*
* @return The metadata.
*/
public com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata
getMetadata() {
if (metadataBuilder_ == null) {
return metadata_ == null
? com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata
.getDefaultInstance()
: metadata_;
} else {
return metadataBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*/
public Builder setMetadata(
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata value) {
if (metadataBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
metadata_ = value;
} else {
metadataBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*/
public Builder setMetadata(
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata.Builder
builderForValue) {
if (metadataBuilder_ == null) {
metadata_ = builderForValue.build();
} else {
metadataBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*/
public Builder mergeMetadata(
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata value) {
if (metadataBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& metadata_ != null
&& metadata_
!= com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata
.getDefaultInstance()) {
getMetadataBuilder().mergeFrom(value);
} else {
metadata_ = value;
}
} else {
metadataBuilder_.mergeFrom(value);
}
if (metadata_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*/
public Builder clearMetadata() {
bitField0_ = (bitField0_ & ~0x00000002);
metadata_ = null;
if (metadataBuilder_ != null) {
metadataBuilder_.dispose();
metadataBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*/
public com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata.Builder
getMetadataBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getMetadataFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*/
public com.google.cloud.aiplatform.v1.schema.trainingjob.definition
.AutoMlTablesMetadataOrBuilder
getMetadataOrBuilder() {
if (metadataBuilder_ != null) {
return metadataBuilder_.getMessageOrBuilder();
} else {
return metadata_ == null
? com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata
.getDefaultInstance()
: metadata_;
}
}
/**
*
*
* <pre>
* The metadata information.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata metadata = 2;
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata,
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata
.Builder,
com.google.cloud.aiplatform.v1.schema.trainingjob.definition
.AutoMlTablesMetadataOrBuilder>
getMetadataFieldBuilder() {
if (metadataBuilder_ == null) {
metadataBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata,
com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTablesMetadata
.Builder,
com.google.cloud.aiplatform.v1.schema.trainingjob.definition
.AutoMlTablesMetadataOrBuilder>(
getMetadata(), getParentForChildren(), isClean());
metadata_ = null;
}
return metadataBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables)
private static final com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE =
new com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables();
}
public static com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<AutoMlTables> PARSER =
new com.google.protobuf.AbstractParser<AutoMlTables>() {
@java.lang.Override
public AutoMlTables parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<AutoMlTables> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<AutoMlTables> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.schema.trainingjob.definition.AutoMlTables
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/pulsar | 36,724 | pulsar-broker/src/test/java/org/apache/pulsar/broker/service/InactiveTopicDeleteTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.broker.service;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import com.google.common.collect.Sets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.apache.pulsar.broker.namespace.NamespaceService;
import org.apache.pulsar.broker.service.persistent.PersistentTopic;
import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.common.naming.NamespaceName;
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.common.naming.TopicVersion;
import org.apache.pulsar.common.policies.data.InactiveTopicDeleteMode;
import org.apache.pulsar.common.policies.data.InactiveTopicPolicies;
import org.apache.pulsar.common.policies.data.RetentionPolicies;
import org.awaitility.Awaitility;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@Test(groups = "broker")
public class InactiveTopicDeleteTest extends BrokerTestBase {
@BeforeMethod
protected void setup() throws Exception {
//No-op
}
@AfterMethod(alwaysRun = true)
protected void cleanup() throws Exception {
super.internalCleanup();
}
@Test
public void testDeleteWhenNoSubscriptions() throws Exception {
conf.setBrokerDeleteInactiveTopicsMode(InactiveTopicDeleteMode.delete_when_no_subscriptions);
conf.setBrokerDeleteInactiveTopicsFrequencySeconds(1);
super.baseSetup();
final String topic = "persistent://prop/ns-abc/testDeleteWhenNoSubscriptions";
Producer<byte[]> producer = pulsarClient.newProducer()
.topic(topic)
.create();
Consumer<byte[]> consumer = pulsarClient.newConsumer()
.topic(topic)
.subscriptionName("sub")
.subscribe();
consumer.close();
producer.close();
Awaitility.await().untilAsserted(() -> Assert.assertTrue(admin.topics().getList("prop/ns-abc")
.contains(topic)));
admin.topics().deleteSubscription(topic, "sub");
Awaitility.await().untilAsserted(() -> Assert.assertFalse(admin.topics().getList("prop/ns-abc")
.contains(topic)));
}
@Test
public void testDeleteAndCleanZkNode() throws Exception {
conf.setBrokerDeleteInactiveTopicsMode(InactiveTopicDeleteMode.delete_when_no_subscriptions);
conf.setBrokerDeleteInactivePartitionedTopicMetadataEnabled(true);
conf.setBrokerDeleteInactiveTopicsFrequencySeconds(1);
super.baseSetup();
final String topic = "persistent://prop/ns-abc/testDeleteWhenNoSubscriptions";
admin.topics().createPartitionedTopic(topic, 5);
pulsarClient.newProducer().topic(topic).create().close();
pulsarClient.newConsumer().topic(topic).subscriptionName("sub").subscribe().close();
Awaitility.await()
.untilAsserted(() -> Assert.assertTrue(admin.topics().getPartitionedTopicList("prop/ns-abc")
.contains(topic)));
admin.topics().deleteSubscription(topic, "sub");
Awaitility.await()
.untilAsserted(() -> Assert.assertFalse(admin.topics().getPartitionedTopicList("prop/ns-abc")
.contains(topic)));
}
@Test
public void testWhenSubPartitionNotDelete() throws Exception {
conf.setBrokerDeleteInactiveTopicsMode(InactiveTopicDeleteMode.delete_when_no_subscriptions);
conf.setBrokerDeleteInactivePartitionedTopicMetadataEnabled(true);
conf.setBrokerDeleteInactiveTopicsFrequencySeconds(1);
super.baseSetup();
final String topic = "persistent://prop/ns-abc/testDeleteWhenNoSubscriptions";
final TopicName topicName = TopicName.get(topic);
admin.topics().createPartitionedTopic(topic, 5);
pulsarClient.newProducer().topic(topic).create().close();
pulsarClient.newConsumer().topic(topic).subscriptionName("sub").subscribe().close();
Thread.sleep(2000);
// Topic should not be deleted
Assert.assertTrue(admin.topics().getPartitionedTopicList("prop/ns-abc").contains(topic));
admin.topics().deleteSubscription(topic, "sub");
Awaitility.await().untilAsserted(() -> {
// Now the topic should be deleted
Assert.assertFalse(admin.topics().getPartitionedTopicList("prop/ns-abc").contains(topic));
});
}
@Test
public void testNotEnabledDeleteZkNode() throws Exception {
conf.setBrokerDeleteInactiveTopicsMode(InactiveTopicDeleteMode.delete_when_no_subscriptions);
conf.setBrokerDeleteInactiveTopicsFrequencySeconds(1);
conf.setBrokerDeleteInactiveTopicsEnabled(true);
super.baseSetup();
final String namespace = "prop/ns-abc";
final String topic = "persistent://prop/ns-abc/testNotEnabledDeleteZkNode1";
final String topic2 = "persistent://prop/ns-abc/testNotEnabledDeleteZkNode2";
admin.topics().createPartitionedTopic(topic, 5);
admin.topics().createNonPartitionedTopic(topic2);
pulsarClient.newProducer().topic(topic).create().close();
pulsarClient.newProducer().topic(topic2).create().close();
pulsarClient.newConsumer().topic(topic).subscriptionName("sub").subscribe().close();
pulsarClient.newConsumer().topic(topic2).subscriptionName("sub2").subscribe().close();
Awaitility.await()
.untilAsserted(() -> Assert.assertTrue(admin.topics().getList(namespace).contains(topic2)));
Assert.assertTrue(admin.topics().getPartitionedTopicList(namespace).contains(topic));
admin.topics().deleteSubscription(topic, "sub");
admin.topics().deleteSubscription(topic2, "sub2");
Awaitility.await()
.untilAsserted(() -> Assert.assertFalse(admin.topics().getList(namespace).contains(topic2)));
Assert.assertTrue(admin.topics().getPartitionedTopicList(namespace).contains(topic));
// BrokerDeleteInactivePartitionedTopicMetaDataEnabled is not enabled,
// so only NonPartitionedTopic will be cleaned
Assert.assertFalse(admin.topics().getList(namespace).contains(topic2));
}
@Test(timeOut = 20000)
public void testTopicPolicyUpdateAndClean() throws Exception {
final String namespace = "prop/ns-abc";
final String namespace2 = "prop/ns-abc2";
final String namespace3 = "prop/ns-abc3";
List<String> namespaceList = Arrays.asList(namespace2, namespace3);
conf.setBrokerDeleteInactiveTopicsEnabled(true);
conf.setBrokerDeleteInactiveTopicsMaxInactiveDurationSeconds(1000);
conf.setBrokerDeleteInactiveTopicsMode(InactiveTopicDeleteMode.delete_when_no_subscriptions);
InactiveTopicPolicies defaultPolicy =
new InactiveTopicPolicies(InactiveTopicDeleteMode.delete_when_no_subscriptions
, 1000, true);
super.baseSetup();
for (String ns : namespaceList) {
admin.namespaces().createNamespace(ns);
admin.namespaces().setNamespaceReplicationClusters(ns, Sets.newHashSet("test"));
}
final String topic = "persistent://prop/ns-abc/testDeletePolicyUpdate";
final String topic2 = "persistent://prop/ns-abc2/testDeletePolicyUpdate";
final String topic3 = "persistent://prop/ns-abc3/testDeletePolicyUpdate";
List<String> topics = Arrays.asList(topic, topic2, topic3);
for (String tp : topics) {
admin.topics().createNonPartitionedTopic(tp);
}
InactiveTopicPolicies inactiveTopicPolicies =
new InactiveTopicPolicies(InactiveTopicDeleteMode.delete_when_no_subscriptions, 1, true);
admin.namespaces().setInactiveTopicPolicies(namespace, inactiveTopicPolicies);
inactiveTopicPolicies.setInactiveTopicDeleteMode(InactiveTopicDeleteMode.delete_when_subscriptions_caught_up);
admin.namespaces().setInactiveTopicPolicies(namespace2, inactiveTopicPolicies);
inactiveTopicPolicies.setInactiveTopicDeleteMode(InactiveTopicDeleteMode.delete_when_no_subscriptions);
admin.namespaces().setInactiveTopicPolicies(namespace3, inactiveTopicPolicies);
InactiveTopicPolicies policies;
//wait for zk
Awaitility.await().until(() -> {
InactiveTopicPolicies temp = ((PersistentTopic) pulsar.getBrokerService().getTopic(topic, false).get()
.get()).getInactiveTopicPolicies();
return temp.isDeleteWhileInactive();
});
policies = ((PersistentTopic) pulsar.getBrokerService().getTopic(topic, false).get()
.get()).getInactiveTopicPolicies();
Assert.assertTrue(policies.isDeleteWhileInactive());
assertEquals(policies.getInactiveTopicDeleteMode(), InactiveTopicDeleteMode.delete_when_no_subscriptions);
assertEquals(policies.getMaxInactiveDurationSeconds(), 1);
assertEquals(policies, admin.namespaces().getInactiveTopicPolicies(namespace));
admin.namespaces().removeInactiveTopicPolicies(namespace);
Awaitility.await().until(() -> {
InactiveTopicPolicies temp = ((PersistentTopic) pulsar.getBrokerService().getTopic(topic, false).get()
.get()).getInactiveTopicPolicies();
return temp.getMaxInactiveDurationSeconds() == 1000;
});
assertEquals(((PersistentTopic) pulsar.getBrokerService().getTopic(topic, false)
.get().get()).getInactiveTopicPolicies(), defaultPolicy);
policies = ((PersistentTopic) pulsar.getBrokerService().getTopic(topic2, false).get()
.get()).getInactiveTopicPolicies();
Assert.assertTrue(policies.isDeleteWhileInactive());
assertEquals(policies.getInactiveTopicDeleteMode(),
InactiveTopicDeleteMode.delete_when_subscriptions_caught_up);
assertEquals(policies.getMaxInactiveDurationSeconds(), 1);
assertEquals(policies, admin.namespaces().getInactiveTopicPolicies(namespace2));
admin.namespaces().removeInactiveTopicPolicies(namespace2);
Awaitility.await().until(() -> {
InactiveTopicPolicies temp = ((PersistentTopic) pulsar.getBrokerService().getTopic(topic, false).get()
.get()).getInactiveTopicPolicies();
return temp.getMaxInactiveDurationSeconds() == 1000;
});
assertEquals(((PersistentTopic) pulsar.getBrokerService().getTopic(topic2, false)
.get().get()).getInactiveTopicPolicies()
, defaultPolicy);
}
@Test(timeOut = 20000)
public void testDeleteWhenNoSubscriptionsWithMultiConfig() throws Exception {
final String namespace = "prop/ns-abc";
final String namespace2 = "prop/ns-abc2";
final String namespace3 = "prop/ns-abc3";
List<String> namespaceList = Arrays.asList(namespace2, namespace3);
conf.setBrokerDeleteInactiveTopicsEnabled(true);
conf.setBrokerDeleteInactiveTopicsFrequencySeconds(1);
super.baseSetup();
for (String ns : namespaceList) {
admin.namespaces().createNamespace(ns);
admin.namespaces().setNamespaceReplicationClusters(ns, Sets.newHashSet("test"));
}
final String topic = "persistent://prop/ns-abc/testDeleteWhenNoSubscriptionsWithMultiConfig";
final String topic2 = "persistent://prop/ns-abc2/testDeleteWhenNoSubscriptionsWithMultiConfig";
final String topic3 = "persistent://prop/ns-abc3/testDeleteWhenNoSubscriptionsWithMultiConfig";
List<String> topics = Arrays.asList(topic, topic2, topic3);
//create producer/consumer and close
Map<String, String> topicToSub = new HashMap<>();
for (String tp : topics) {
Producer<byte[]> producer = pulsarClient.newProducer().topic(tp).create();
String subName = "sub" + System.currentTimeMillis();
topicToSub.put(tp, subName);
Consumer<byte[]> consumer = pulsarClient.newConsumer().topic(tp).subscriptionName(subName).subscribe();
for (int i = 0; i < 10; i++) {
producer.send("Pulsar".getBytes());
}
consumer.close();
producer.close();
Thread.sleep(1);
}
// namespace use delete_when_no_subscriptions, namespace2 use delete_when_subscriptions_caught_up
// namespace3 use default:delete_when_no_subscriptions
InactiveTopicPolicies inactiveTopicPolicies =
new InactiveTopicPolicies(InactiveTopicDeleteMode.delete_when_no_subscriptions, 1, true);
admin.namespaces().setInactiveTopicPolicies(namespace, inactiveTopicPolicies);
inactiveTopicPolicies.setInactiveTopicDeleteMode(InactiveTopicDeleteMode.delete_when_subscriptions_caught_up);
admin.namespaces().setInactiveTopicPolicies(namespace2, inactiveTopicPolicies);
//wait for zk
Awaitility.await().until(() -> {
InactiveTopicPolicies temp = ((PersistentTopic) pulsar.getBrokerService().getTopic(topic, false).get()
.get()).getInactiveTopicPolicies();
return temp.isDeleteWhileInactive();
});
// topic should still exist
Thread.sleep(2000);
Assert.assertTrue(admin.topics().getList(namespace).contains(topic));
Assert.assertTrue(admin.topics().getList(namespace2).contains(topic2));
Assert.assertTrue(admin.topics().getList(namespace3).contains(topic3));
// no backlog, trigger delete_when_subscriptions_caught_up
admin.topics().skipAllMessages(topic2, topicToSub.remove(topic2));
Awaitility.await().untilAsserted(()
-> Assert.assertFalse(admin.topics().getList(namespace2).contains(topic2)));
// delete subscription, trigger delete_when_no_subscriptions
for (Map.Entry<String, String> entry : topicToSub.entrySet()) {
admin.topics().deleteSubscription(entry.getKey(), entry.getValue());
}
Awaitility.await()
.untilAsserted(() -> Assert.assertFalse(admin.topics().getList(namespace).contains(topic)));
Awaitility.await()
.untilAsserted(() -> Assert.assertFalse(admin.topics().getList(namespace3).contains(topic3)));
}
@Test
public void testDeleteWhenNoBacklogs() throws Exception {
conf.setBrokerDeleteInactiveTopicsMode(InactiveTopicDeleteMode.delete_when_subscriptions_caught_up);
conf.setBrokerDeleteInactiveTopicsFrequencySeconds(1);
super.baseSetup();
final String topic = "persistent://prop/ns-abc/testDeleteWhenNoBacklogs";
final String topic2 = "persistent://prop/ns-abc/testDeleteWhenNoBacklogsB";
Producer<byte[]> producer = pulsarClient.newProducer()
.topic(topic)
.create();
Producer<byte[]> producer2 = pulsarClient.newProducer()
.topic(topic2)
.create();
Consumer<byte[]> consumer = pulsarClient.newConsumer()
.topic(topic)
.subscriptionName("sub")
.subscribe();
Consumer<byte[]> consumer2 = pulsarClient.newConsumer()
.topicsPattern("persistent://prop/ns-abc/test.*")
.subscriptionName("sub2")
.subscribe();
int producedCount = 10;
for (int i = 0; i < producedCount; i++) {
producer.send("Pulsar".getBytes());
producer2.send("Pulsar".getBytes());
}
producer.close();
producer2.close();
int receivedCount = 0;
Message<byte[]> msg;
while ((msg = consumer2.receive(1, TimeUnit.SECONDS)) != null) {
consumer2.acknowledge(msg);
receivedCount++;
}
assertEquals(producedCount * 2, receivedCount);
Thread.sleep(2000);
Assert.assertTrue(admin.topics().getList("prop/ns-abc").contains(topic));
admin.topics().skipAllMessages(topic, "sub");
Awaitility.await().untilAsserted(() -> {
final List<String> topics = admin.topics().getList("prop/ns-abc");
Assert.assertFalse(topics.contains(topic));
Assert.assertFalse(topics.contains(topic2));
});
consumer.close();
consumer2.close();
}
@Test
public void testMaxInactiveDuration() throws Exception {
conf.setBrokerDeleteInactiveTopicsMode(InactiveTopicDeleteMode.delete_when_subscriptions_caught_up);
conf.setBrokerDeleteInactiveTopicsFrequencySeconds(1);
conf.setBrokerDeleteInactiveTopicsMaxInactiveDurationSeconds(5);
super.baseSetup();
final String topic = "persistent://prop/ns-abc/testMaxInactiveDuration";
Producer<byte[]> producer = pulsarClient.newProducer()
.topic(topic)
.create();
producer.close();
Thread.sleep(2000);
Assert.assertTrue(admin.topics().getList("prop/ns-abc")
.contains(topic));
Thread.sleep(4000);
Assert.assertFalse(admin.topics().getList("prop/ns-abc")
.contains(topic));
super.internalCleanup();
}
@Test(timeOut = 20000)
public void testTopicLevelInActiveTopicApi() throws Exception {
super.baseSetup();
final String topicName = "persistent://prop/ns-abc/testMaxInactiveDuration-" + UUID.randomUUID().toString();
admin.topics().createPartitionedTopic(topicName, 3);
pulsarClient.newConsumer().topic(topicName).subscriptionName("my-sub").subscribe().close();
TopicName topic = TopicName.get(topicName);
InactiveTopicPolicies inactiveTopicPolicies = admin.topics().getInactiveTopicPolicies(topicName);
assertNull(inactiveTopicPolicies);
InactiveTopicPolicies policies = new InactiveTopicPolicies();
policies.setDeleteWhileInactive(true);
policies.setInactiveTopicDeleteMode(InactiveTopicDeleteMode.delete_when_no_subscriptions);
policies.setMaxInactiveDurationSeconds(10);
admin.topics().setInactiveTopicPolicies(topicName, policies);
Awaitility.await().until(()
-> admin.topics().getInactiveTopicPolicies(topicName) != null);
assertEquals(admin.topics().getInactiveTopicPolicies(topicName), policies);
admin.topics().removeInactiveTopicPolicies(topicName);
Awaitility.await().untilAsserted(()
-> assertNull(admin.topics().getInactiveTopicPolicies(topicName)));
}
@Test(timeOut = 30000)
public void testTopicLevelInactivePolicyUpdateAndClean() throws Exception {
conf.setBrokerDeleteInactiveTopicsEnabled(true);
conf.setBrokerDeleteInactiveTopicsMaxInactiveDurationSeconds(1000);
conf.setBrokerDeleteInactiveTopicsMode(InactiveTopicDeleteMode.delete_when_no_subscriptions);
InactiveTopicPolicies defaultPolicy =
new InactiveTopicPolicies(InactiveTopicDeleteMode.delete_when_no_subscriptions
, 1000, true);
super.baseSetup();
final String namespace = "prop/ns-abc";
final String topic = "persistent://prop/ns-abc/testTopicLevelInactivePolicy" + UUID.randomUUID().toString();
final String topic2 = "persistent://prop/ns-abc/testTopicLevelInactivePolicy" + UUID.randomUUID().toString();
final String topic3 = "persistent://prop/ns-abc/testTopicLevelInactivePolicy" + UUID.randomUUID().toString();
List<String> topics = Arrays.asList(topic, topic2, topic3);
for (String tp : topics) {
admin.topics().createNonPartitionedTopic(tp);
}
for (String tp : topics) {
//wait for cache
pulsarClient.newConsumer().topic(tp).subscriptionName("my-sub").subscribe().close();
TopicName topicName = TopicName.get(tp);
}
InactiveTopicPolicies inactiveTopicPolicies =
new InactiveTopicPolicies(InactiveTopicDeleteMode.delete_when_no_subscriptions, 1, true);
admin.topics().setInactiveTopicPolicies(topic, inactiveTopicPolicies);
inactiveTopicPolicies.setInactiveTopicDeleteMode(InactiveTopicDeleteMode.delete_when_subscriptions_caught_up);
admin.topics().setInactiveTopicPolicies(topic2, inactiveTopicPolicies);
inactiveTopicPolicies.setInactiveTopicDeleteMode(InactiveTopicDeleteMode.delete_when_no_subscriptions);
admin.topics().setInactiveTopicPolicies(topic3, inactiveTopicPolicies);
//wait for cache
Awaitility.await().until(()
-> admin.topics().getInactiveTopicPolicies(topic) != null);
InactiveTopicPolicies policies = ((PersistentTopic) pulsar.getBrokerService()
.getTopic(topic, false).get().get()).getInactiveTopicPolicies();
Assert.assertTrue(policies.isDeleteWhileInactive());
assertEquals(policies.getInactiveTopicDeleteMode(), InactiveTopicDeleteMode.delete_when_no_subscriptions);
assertEquals(policies.getMaxInactiveDurationSeconds(), 1);
assertEquals(policies, admin.topics().getInactiveTopicPolicies(topic));
admin.topics().removeInactiveTopicPolicies(topic);
//Only the broker-level policies is set, so after removing the topic-level policies
//, the topic will use the broker-level policies
Awaitility.await().untilAsserted(()
-> assertEquals(((PersistentTopic) pulsar.getBrokerService().getTopic(topic, false)
.get().get()).getInactiveTopicPolicies(), defaultPolicy));
policies = ((PersistentTopic) pulsar.getBrokerService().getTopic(topic2, false)
.get().get()).getInactiveTopicPolicies();
Assert.assertTrue(policies.isDeleteWhileInactive());
assertEquals(policies.getInactiveTopicDeleteMode(),
InactiveTopicDeleteMode.delete_when_subscriptions_caught_up);
assertEquals(policies.getMaxInactiveDurationSeconds(), 1);
assertEquals(policies, admin.topics().getInactiveTopicPolicies(topic2));
inactiveTopicPolicies.setMaxInactiveDurationSeconds(999);
//Both broker level and namespace level policies are set, so after removing the topic level policies
//, the topic will use the namespace level policies
admin.namespaces().setInactiveTopicPolicies(namespace, inactiveTopicPolicies);
//wait for zk
Awaitility.await().until(() -> {
InactiveTopicPolicies tempPolicies = ((PersistentTopic) pulsar.getBrokerService().getTopic(topic, false)
.get().get()).getInactiveTopicPolicies();
return inactiveTopicPolicies.equals(tempPolicies);
});
admin.topics().removeInactiveTopicPolicies(topic2);
// The cache has been updated, but the system-event may not be consumed yet
// , so wait for topic-policies update event
Awaitility.await().untilAsserted(() -> {
InactiveTopicPolicies nsPolicies = ((PersistentTopic) pulsar.getBrokerService()
.getTopic(topic2, false).get().get()).getInactiveTopicPolicies();
assertEquals(nsPolicies.getMaxInactiveDurationSeconds(), 999);
});
}
@Test(timeOut = 30000)
public void testDeleteWhenNoSubscriptionsWithTopicLevelPolicies() throws Exception {
final String namespace = "prop/ns-abc";
conf.setBrokerDeleteInactiveTopicsEnabled(true);
conf.setBrokerDeleteInactiveTopicsFrequencySeconds(1);
super.baseSetup();
final String topic = "persistent://prop/ns-abc/test-" + UUID.randomUUID();
final String topic2 = "persistent://prop/ns-abc/test-" + UUID.randomUUID();
final String topic3 = "persistent://prop/ns-abc/test-" + UUID.randomUUID();
List<String> topics = Arrays.asList(topic, topic2, topic3);
//create producer/consumer and close
Map<String, String> topicToSub = new HashMap<>();
for (String tp : topics) {
Producer<byte[]> producer = pulsarClient.newProducer().topic(tp).create();
String subName = "sub" + System.currentTimeMillis();
topicToSub.put(tp, subName);
Consumer<byte[]> consumer = pulsarClient.newConsumer().topic(tp).subscriptionName(subName).subscribe();
for (int i = 0; i < 10; i++) {
producer.send("Pulsar".getBytes());
}
consumer.close();
producer.close();
Thread.sleep(1);
}
// "topic" use delete_when_no_subscriptions, "topic2" use delete_when_subscriptions_caught_up
// "topic3" use default:delete_when_no_subscriptions
InactiveTopicPolicies inactiveTopicPolicies =
new InactiveTopicPolicies(InactiveTopicDeleteMode.delete_when_no_subscriptions, 1, true);
admin.topics().setInactiveTopicPolicies(topic, inactiveTopicPolicies);
inactiveTopicPolicies.setInactiveTopicDeleteMode(InactiveTopicDeleteMode.delete_when_subscriptions_caught_up);
admin.topics().setInactiveTopicPolicies(topic2, inactiveTopicPolicies);
//wait for update
Awaitility.await().until(()
-> admin.topics().getInactiveTopicPolicies(topic2) != null);
// topic should still exist
Thread.sleep(2000);
Assert.assertTrue(admin.topics().getList(namespace).contains(topic));
Assert.assertTrue(admin.topics().getList(namespace).contains(topic2));
Assert.assertTrue(admin.topics().getList(namespace).contains(topic3));
// no backlog, trigger delete_when_subscriptions_caught_up
admin.topics().skipAllMessages(topic2, topicToSub.remove(topic2));
Awaitility.await().untilAsserted(()
-> Assert.assertFalse(admin.topics().getList(namespace).contains(topic2)));
// delete subscription, trigger delete_when_no_subscriptions
for (Map.Entry<String, String> entry : topicToSub.entrySet()) {
admin.topics().deleteSubscription(entry.getKey(), entry.getValue());
}
Awaitility.await().untilAsserted(()
-> Assert.assertFalse(admin.topics().getList(namespace).contains(topic3)));
Assert.assertFalse(admin.topics().getList(namespace).contains(topic));
}
@Test(timeOut = 30000)
public void testInactiveTopicApplied() throws Exception {
super.baseSetup();
final String namespace = "prop/ns-abc";
final String topic = "persistent://prop/ns-abc/test-" + UUID.randomUUID();
pulsarClient.newProducer().topic(topic).create().close();
//namespace-level default value is null
assertNull(admin.namespaces().getInactiveTopicPolicies(namespace));
//topic-level default value is null
assertNull(admin.topics().getInactiveTopicPolicies(topic));
//use broker-level by default
InactiveTopicPolicies brokerLevelPolicy =
new InactiveTopicPolicies(conf.getBrokerDeleteInactiveTopicsMode(),
conf.getBrokerDeleteInactiveTopicsMaxInactiveDurationSeconds(),
conf.isBrokerDeleteInactiveTopicsEnabled());
Assert.assertEquals(admin.topics().getInactiveTopicPolicies(topic, true), brokerLevelPolicy);
//set namespace-level policy
InactiveTopicPolicies namespaceLevelPolicy =
new InactiveTopicPolicies(InactiveTopicDeleteMode.delete_when_no_subscriptions,
20, false);
admin.namespaces().setInactiveTopicPolicies(namespace, namespaceLevelPolicy);
Awaitility.await().untilAsserted(()
-> assertNotNull(admin.namespaces().getInactiveTopicPolicies(namespace)));
InactiveTopicPolicies policyFromBroker = admin.topics().getInactiveTopicPolicies(topic, true);
assertEquals(policyFromBroker.getMaxInactiveDurationSeconds(), 20);
assertFalse(policyFromBroker.isDeleteWhileInactive());
assertEquals(policyFromBroker.getInactiveTopicDeleteMode(),
InactiveTopicDeleteMode.delete_when_no_subscriptions);
// set topic-level policy
InactiveTopicPolicies topicLevelPolicy =
new InactiveTopicPolicies(InactiveTopicDeleteMode.delete_when_subscriptions_caught_up,
30, false);
admin.topics().setInactiveTopicPolicies(topic, topicLevelPolicy);
Awaitility.await().untilAsserted(()
-> assertNotNull(admin.topics().getInactiveTopicPolicies(topic)));
policyFromBroker = admin.topics().getInactiveTopicPolicies(topic, true);
assertEquals(policyFromBroker.getMaxInactiveDurationSeconds(), 30);
assertFalse(policyFromBroker.isDeleteWhileInactive());
assertEquals(policyFromBroker.getInactiveTopicDeleteMode(),
InactiveTopicDeleteMode.delete_when_subscriptions_caught_up);
//remove topic-level policy
admin.topics().removeInactiveTopicPolicies(topic);
Awaitility.await().untilAsserted(()
-> assertEquals(admin.topics().getInactiveTopicPolicies(topic, true), namespaceLevelPolicy));
//remove namespace-level policy
admin.namespaces().removeInactiveTopicPolicies(namespace);
Awaitility.await().untilAsserted(()
-> assertEquals(admin.topics().getInactiveTopicPolicies(topic, true), brokerLevelPolicy));
}
@Test(timeOut = 30000)
public void testHealthTopicInactiveNotClean() throws Exception {
conf.setBrokerDeleteInactiveTopicsMode(InactiveTopicDeleteMode.delete_when_no_subscriptions);
conf.setBrokerDeleteInactiveTopicsFrequencySeconds(1);
super.baseSetup();
// init topic
NamespaceName heartbeatNamespaceV1 = NamespaceService
.getHeartbeatNamespace(pulsar.getBrokerId(), pulsar.getConfig());
final String healthCheckTopicV1 = "persistent://" + heartbeatNamespaceV1 + "/healthcheck";
NamespaceName heartbeatNamespaceV2 = NamespaceService
.getHeartbeatNamespaceV2(pulsar.getBrokerId(), pulsar.getConfig());
final String healthCheckTopicV2 = "persistent://" + heartbeatNamespaceV2 + "/healthcheck";
admin.brokers().healthcheck(TopicVersion.V1);
admin.brokers().healthcheck(TopicVersion.V2);
List<String> v1Partitions = pulsar
.getPulsarResources()
.getTopicResources()
.getExistingPartitions(TopicName.get(healthCheckTopicV1))
.get(10, TimeUnit.SECONDS);
List<String> v2Partitions = pulsar
.getPulsarResources()
.getTopicResources()
.getExistingPartitions(TopicName.get(healthCheckTopicV2))
.get(10, TimeUnit.SECONDS);
Assert.assertTrue(v1Partitions.contains(healthCheckTopicV1));
Assert.assertTrue(v2Partitions.contains(healthCheckTopicV2));
}
@Test
public void testDynamicConfigurationBrokerDeleteInactiveTopicsEnabled() throws Exception {
conf.setBrokerDeleteInactiveTopicsEnabled(true);
super.baseSetup();
admin.brokers().updateDynamicConfiguration("brokerDeleteInactiveTopicsEnabled", "false");
Awaitility.await().atMost(2, TimeUnit.SECONDS).untilAsserted(()->{
assertFalse(conf.isBrokerDeleteInactiveTopicsEnabled());
});
}
@Test
public void testDynamicConfigurationBrokerDeleteInactiveTopicsFrequencySeconds() throws Exception {
conf.setBrokerDeleteInactiveTopicsFrequencySeconds(30);
super.baseSetup();
admin.brokers()
.updateDynamicConfiguration("brokerDeleteInactiveTopicsFrequencySeconds", "60");
Awaitility.await().atMost(2, TimeUnit.SECONDS).untilAsserted(()->{
assertEquals(conf.getBrokerDeleteInactiveTopicsFrequencySeconds(), 60);
});
}
@Test
public void testDynamicConfigurationBrokerDeleteInactiveTopicsMaxInactiveDurationSeconds() throws Exception {
conf.setBrokerDeleteInactiveTopicsMaxInactiveDurationSeconds(30);
super.baseSetup();
admin.brokers()
.updateDynamicConfiguration("brokerDeleteInactiveTopicsMaxInactiveDurationSeconds", "60");
Awaitility.await().atMost(2, TimeUnit.SECONDS).untilAsserted(()->{
assertEquals(conf.getBrokerDeleteInactiveTopicsMaxInactiveDurationSeconds(), 60);
});
}
@Test
public void testDynamicConfigurationBrokerDeleteInactiveTopicsMode() throws Exception {
conf.setBrokerDeleteInactiveTopicsMode (InactiveTopicDeleteMode.delete_when_no_subscriptions);
super.baseSetup();
String expect = InactiveTopicDeleteMode.delete_when_subscriptions_caught_up.toString();
admin.brokers()
.updateDynamicConfiguration("brokerDeleteInactiveTopicsMode",
expect);
Awaitility.await().atMost(2, TimeUnit.SECONDS).untilAsserted(()->{
assertEquals(conf.getBrokerDeleteInactiveTopicsMode().toString(), expect);
});
}
@Test
public void testBrokerDeleteInactivePartitionedTopicMetadataEnabled() throws Exception {
conf.setBrokerDeleteInactivePartitionedTopicMetadataEnabled(false);
super.baseSetup();
admin.brokers()
.updateDynamicConfiguration("brokerDeleteInactivePartitionedTopicMetadataEnabled",
"true");
Awaitility.await().atMost(2, TimeUnit.SECONDS).untilAsserted(()->{
assertTrue(conf.isBrokerDeleteInactivePartitionedTopicMetadataEnabled());
});
}
@Test(timeOut = 30000)
public void testDeleteEmptyTopicWithRetentionPolicy() throws Exception {
conf.setBrokerDeleteInactiveTopicsMode(InactiveTopicDeleteMode.delete_when_no_subscriptions);
conf.setBrokerDeleteInactiveTopicsFrequencySeconds(1);
conf.setBrokerDeleteInactiveTopicsMaxInactiveDurationSeconds(1);
super.baseSetup();
final String namespace = "prop/ns-abc";
final String topic = "persistent://" + namespace + "/testDeleteEmptyTopicWithRetention-" + UUID.randomUUID();
admin.namespaces().setRetention(namespace, new RetentionPolicies(60, 1024));
pulsarClient.newProducer().topic(topic).create().close();
Awaitility.await().untilAsserted(() ->
Assert.assertTrue(admin.topics().getList(namespace).contains(topic)));
Awaitility.await().atMost(10, TimeUnit.SECONDS).untilAsserted(() ->
Assert.assertFalse(admin.topics().getList(namespace).contains(topic)));
}
@Test(timeOut = 30000)
public void testRetainTopicWithDataAndRetentionPolicy() throws Exception {
conf.setBrokerDeleteInactiveTopicsMode(InactiveTopicDeleteMode.delete_when_no_subscriptions);
conf.setBrokerDeleteInactiveTopicsFrequencySeconds(1);
conf.setBrokerDeleteInactiveTopicsMaxInactiveDurationSeconds(1);
super.baseSetup();
final String namespace = "prop/ns-abc";
final String topic = "persistent://" + namespace + "/testRetainTopicWithData-" + UUID.randomUUID();
admin.namespaces().setRetention(namespace, new RetentionPolicies(60, 1024));
Producer<byte[]> producer = pulsarClient.newProducer().topic(topic).create();
producer.send("test message".getBytes());
producer.close();
Awaitility.await().during(5, TimeUnit.SECONDS).untilAsserted(() ->
Assert.assertTrue(admin.topics().getList(namespace).contains(topic)));
}
}
|
googleapis/google-cloud-java | 36,401 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/GenerateVideoResponse.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/prediction_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1;
/**
*
*
* <pre>
* Generate video response.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.GenerateVideoResponse}
*/
public final class GenerateVideoResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.GenerateVideoResponse)
GenerateVideoResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use GenerateVideoResponse.newBuilder() to construct.
private GenerateVideoResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GenerateVideoResponse() {
generatedSamples_ = com.google.protobuf.LazyStringArrayList.emptyList();
raiMediaFilteredReasons_ = com.google.protobuf.LazyStringArrayList.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new GenerateVideoResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.PredictionServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_GenerateVideoResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.PredictionServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_GenerateVideoResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse.class,
com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse.Builder.class);
}
private int bitField0_;
public static final int GENERATED_SAMPLES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private com.google.protobuf.LazyStringArrayList generatedSamples_ =
com.google.protobuf.LazyStringArrayList.emptyList();
/**
*
*
* <pre>
* The cloud storage uris of the generated videos.
* </pre>
*
* <code>repeated string generated_samples = 1;</code>
*
* @return A list containing the generatedSamples.
*/
public com.google.protobuf.ProtocolStringList getGeneratedSamplesList() {
return generatedSamples_;
}
/**
*
*
* <pre>
* The cloud storage uris of the generated videos.
* </pre>
*
* <code>repeated string generated_samples = 1;</code>
*
* @return The count of generatedSamples.
*/
public int getGeneratedSamplesCount() {
return generatedSamples_.size();
}
/**
*
*
* <pre>
* The cloud storage uris of the generated videos.
* </pre>
*
* <code>repeated string generated_samples = 1;</code>
*
* @param index The index of the element to return.
* @return The generatedSamples at the given index.
*/
public java.lang.String getGeneratedSamples(int index) {
return generatedSamples_.get(index);
}
/**
*
*
* <pre>
* The cloud storage uris of the generated videos.
* </pre>
*
* <code>repeated string generated_samples = 1;</code>
*
* @param index The index of the value to return.
* @return The bytes of the generatedSamples at the given index.
*/
public com.google.protobuf.ByteString getGeneratedSamplesBytes(int index) {
return generatedSamples_.getByteString(index);
}
public static final int RAI_MEDIA_FILTERED_COUNT_FIELD_NUMBER = 2;
private int raiMediaFilteredCount_ = 0;
/**
*
*
* <pre>
* Returns if any videos were filtered due to RAI policies.
* </pre>
*
* <code>optional int32 rai_media_filtered_count = 2;</code>
*
* @return Whether the raiMediaFilteredCount field is set.
*/
@java.lang.Override
public boolean hasRaiMediaFilteredCount() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Returns if any videos were filtered due to RAI policies.
* </pre>
*
* <code>optional int32 rai_media_filtered_count = 2;</code>
*
* @return The raiMediaFilteredCount.
*/
@java.lang.Override
public int getRaiMediaFilteredCount() {
return raiMediaFilteredCount_;
}
public static final int RAI_MEDIA_FILTERED_REASONS_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private com.google.protobuf.LazyStringArrayList raiMediaFilteredReasons_ =
com.google.protobuf.LazyStringArrayList.emptyList();
/**
*
*
* <pre>
* Returns rai failure reasons if any.
* </pre>
*
* <code>repeated string rai_media_filtered_reasons = 3;</code>
*
* @return A list containing the raiMediaFilteredReasons.
*/
public com.google.protobuf.ProtocolStringList getRaiMediaFilteredReasonsList() {
return raiMediaFilteredReasons_;
}
/**
*
*
* <pre>
* Returns rai failure reasons if any.
* </pre>
*
* <code>repeated string rai_media_filtered_reasons = 3;</code>
*
* @return The count of raiMediaFilteredReasons.
*/
public int getRaiMediaFilteredReasonsCount() {
return raiMediaFilteredReasons_.size();
}
/**
*
*
* <pre>
* Returns rai failure reasons if any.
* </pre>
*
* <code>repeated string rai_media_filtered_reasons = 3;</code>
*
* @param index The index of the element to return.
* @return The raiMediaFilteredReasons at the given index.
*/
public java.lang.String getRaiMediaFilteredReasons(int index) {
return raiMediaFilteredReasons_.get(index);
}
/**
*
*
* <pre>
* Returns rai failure reasons if any.
* </pre>
*
* <code>repeated string rai_media_filtered_reasons = 3;</code>
*
* @param index The index of the value to return.
* @return The bytes of the raiMediaFilteredReasons at the given index.
*/
public com.google.protobuf.ByteString getRaiMediaFilteredReasonsBytes(int index) {
return raiMediaFilteredReasons_.getByteString(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < generatedSamples_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, generatedSamples_.getRaw(i));
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeInt32(2, raiMediaFilteredCount_);
}
for (int i = 0; i < raiMediaFilteredReasons_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(
output, 3, raiMediaFilteredReasons_.getRaw(i));
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
{
int dataSize = 0;
for (int i = 0; i < generatedSamples_.size(); i++) {
dataSize += computeStringSizeNoTag(generatedSamples_.getRaw(i));
}
size += dataSize;
size += 1 * getGeneratedSamplesList().size();
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, raiMediaFilteredCount_);
}
{
int dataSize = 0;
for (int i = 0; i < raiMediaFilteredReasons_.size(); i++) {
dataSize += computeStringSizeNoTag(raiMediaFilteredReasons_.getRaw(i));
}
size += dataSize;
size += 1 * getRaiMediaFilteredReasonsList().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.aiplatform.v1beta1.GenerateVideoResponse)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse other =
(com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse) obj;
if (!getGeneratedSamplesList().equals(other.getGeneratedSamplesList())) return false;
if (hasRaiMediaFilteredCount() != other.hasRaiMediaFilteredCount()) return false;
if (hasRaiMediaFilteredCount()) {
if (getRaiMediaFilteredCount() != other.getRaiMediaFilteredCount()) return false;
}
if (!getRaiMediaFilteredReasonsList().equals(other.getRaiMediaFilteredReasonsList()))
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 (getGeneratedSamplesCount() > 0) {
hash = (37 * hash) + GENERATED_SAMPLES_FIELD_NUMBER;
hash = (53 * hash) + getGeneratedSamplesList().hashCode();
}
if (hasRaiMediaFilteredCount()) {
hash = (37 * hash) + RAI_MEDIA_FILTERED_COUNT_FIELD_NUMBER;
hash = (53 * hash) + getRaiMediaFilteredCount();
}
if (getRaiMediaFilteredReasonsCount() > 0) {
hash = (37 * hash) + RAI_MEDIA_FILTERED_REASONS_FIELD_NUMBER;
hash = (53 * hash) + getRaiMediaFilteredReasonsList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse 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.GenerateVideoResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse 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.GenerateVideoResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse 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.GenerateVideoResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse 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.GenerateVideoResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse 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.GenerateVideoResponse 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.GenerateVideoResponse 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.GenerateVideoResponse 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>
* Generate video response.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.GenerateVideoResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.GenerateVideoResponse)
com.google.cloud.aiplatform.v1beta1.GenerateVideoResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.PredictionServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_GenerateVideoResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.PredictionServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_GenerateVideoResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse.class,
com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
generatedSamples_ = com.google.protobuf.LazyStringArrayList.emptyList();
raiMediaFilteredCount_ = 0;
raiMediaFilteredReasons_ = com.google.protobuf.LazyStringArrayList.emptyList();
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1beta1.PredictionServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_GenerateVideoResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse build() {
com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse buildPartial() {
com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse result =
new com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
generatedSamples_.makeImmutable();
result.generatedSamples_ = generatedSamples_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.raiMediaFilteredCount_ = raiMediaFilteredCount_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
raiMediaFilteredReasons_.makeImmutable();
result.raiMediaFilteredReasons_ = raiMediaFilteredReasons_;
}
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.GenerateVideoResponse) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse other) {
if (other == com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse.getDefaultInstance())
return this;
if (!other.generatedSamples_.isEmpty()) {
if (generatedSamples_.isEmpty()) {
generatedSamples_ = other.generatedSamples_;
bitField0_ |= 0x00000001;
} else {
ensureGeneratedSamplesIsMutable();
generatedSamples_.addAll(other.generatedSamples_);
}
onChanged();
}
if (other.hasRaiMediaFilteredCount()) {
setRaiMediaFilteredCount(other.getRaiMediaFilteredCount());
}
if (!other.raiMediaFilteredReasons_.isEmpty()) {
if (raiMediaFilteredReasons_.isEmpty()) {
raiMediaFilteredReasons_ = other.raiMediaFilteredReasons_;
bitField0_ |= 0x00000004;
} else {
ensureRaiMediaFilteredReasonsIsMutable();
raiMediaFilteredReasons_.addAll(other.raiMediaFilteredReasons_);
}
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
ensureGeneratedSamplesIsMutable();
generatedSamples_.add(s);
break;
} // case 10
case 16:
{
raiMediaFilteredCount_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
java.lang.String s = input.readStringRequireUtf8();
ensureRaiMediaFilteredReasonsIsMutable();
raiMediaFilteredReasons_.add(s);
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.protobuf.LazyStringArrayList generatedSamples_ =
com.google.protobuf.LazyStringArrayList.emptyList();
private void ensureGeneratedSamplesIsMutable() {
if (!generatedSamples_.isModifiable()) {
generatedSamples_ = new com.google.protobuf.LazyStringArrayList(generatedSamples_);
}
bitField0_ |= 0x00000001;
}
/**
*
*
* <pre>
* The cloud storage uris of the generated videos.
* </pre>
*
* <code>repeated string generated_samples = 1;</code>
*
* @return A list containing the generatedSamples.
*/
public com.google.protobuf.ProtocolStringList getGeneratedSamplesList() {
generatedSamples_.makeImmutable();
return generatedSamples_;
}
/**
*
*
* <pre>
* The cloud storage uris of the generated videos.
* </pre>
*
* <code>repeated string generated_samples = 1;</code>
*
* @return The count of generatedSamples.
*/
public int getGeneratedSamplesCount() {
return generatedSamples_.size();
}
/**
*
*
* <pre>
* The cloud storage uris of the generated videos.
* </pre>
*
* <code>repeated string generated_samples = 1;</code>
*
* @param index The index of the element to return.
* @return The generatedSamples at the given index.
*/
public java.lang.String getGeneratedSamples(int index) {
return generatedSamples_.get(index);
}
/**
*
*
* <pre>
* The cloud storage uris of the generated videos.
* </pre>
*
* <code>repeated string generated_samples = 1;</code>
*
* @param index The index of the value to return.
* @return The bytes of the generatedSamples at the given index.
*/
public com.google.protobuf.ByteString getGeneratedSamplesBytes(int index) {
return generatedSamples_.getByteString(index);
}
/**
*
*
* <pre>
* The cloud storage uris of the generated videos.
* </pre>
*
* <code>repeated string generated_samples = 1;</code>
*
* @param index The index to set the value at.
* @param value The generatedSamples to set.
* @return This builder for chaining.
*/
public Builder setGeneratedSamples(int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureGeneratedSamplesIsMutable();
generatedSamples_.set(index, value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The cloud storage uris of the generated videos.
* </pre>
*
* <code>repeated string generated_samples = 1;</code>
*
* @param value The generatedSamples to add.
* @return This builder for chaining.
*/
public Builder addGeneratedSamples(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureGeneratedSamplesIsMutable();
generatedSamples_.add(value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The cloud storage uris of the generated videos.
* </pre>
*
* <code>repeated string generated_samples = 1;</code>
*
* @param values The generatedSamples to add.
* @return This builder for chaining.
*/
public Builder addAllGeneratedSamples(java.lang.Iterable<java.lang.String> values) {
ensureGeneratedSamplesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, generatedSamples_);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The cloud storage uris of the generated videos.
* </pre>
*
* <code>repeated string generated_samples = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearGeneratedSamples() {
generatedSamples_ = com.google.protobuf.LazyStringArrayList.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
;
onChanged();
return this;
}
/**
*
*
* <pre>
* The cloud storage uris of the generated videos.
* </pre>
*
* <code>repeated string generated_samples = 1;</code>
*
* @param value The bytes of the generatedSamples to add.
* @return This builder for chaining.
*/
public Builder addGeneratedSamplesBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ensureGeneratedSamplesIsMutable();
generatedSamples_.add(value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int raiMediaFilteredCount_;
/**
*
*
* <pre>
* Returns if any videos were filtered due to RAI policies.
* </pre>
*
* <code>optional int32 rai_media_filtered_count = 2;</code>
*
* @return Whether the raiMediaFilteredCount field is set.
*/
@java.lang.Override
public boolean hasRaiMediaFilteredCount() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Returns if any videos were filtered due to RAI policies.
* </pre>
*
* <code>optional int32 rai_media_filtered_count = 2;</code>
*
* @return The raiMediaFilteredCount.
*/
@java.lang.Override
public int getRaiMediaFilteredCount() {
return raiMediaFilteredCount_;
}
/**
*
*
* <pre>
* Returns if any videos were filtered due to RAI policies.
* </pre>
*
* <code>optional int32 rai_media_filtered_count = 2;</code>
*
* @param value The raiMediaFilteredCount to set.
* @return This builder for chaining.
*/
public Builder setRaiMediaFilteredCount(int value) {
raiMediaFilteredCount_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Returns if any videos were filtered due to RAI policies.
* </pre>
*
* <code>optional int32 rai_media_filtered_count = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearRaiMediaFilteredCount() {
bitField0_ = (bitField0_ & ~0x00000002);
raiMediaFilteredCount_ = 0;
onChanged();
return this;
}
private com.google.protobuf.LazyStringArrayList raiMediaFilteredReasons_ =
com.google.protobuf.LazyStringArrayList.emptyList();
private void ensureRaiMediaFilteredReasonsIsMutable() {
if (!raiMediaFilteredReasons_.isModifiable()) {
raiMediaFilteredReasons_ =
new com.google.protobuf.LazyStringArrayList(raiMediaFilteredReasons_);
}
bitField0_ |= 0x00000004;
}
/**
*
*
* <pre>
* Returns rai failure reasons if any.
* </pre>
*
* <code>repeated string rai_media_filtered_reasons = 3;</code>
*
* @return A list containing the raiMediaFilteredReasons.
*/
public com.google.protobuf.ProtocolStringList getRaiMediaFilteredReasonsList() {
raiMediaFilteredReasons_.makeImmutable();
return raiMediaFilteredReasons_;
}
/**
*
*
* <pre>
* Returns rai failure reasons if any.
* </pre>
*
* <code>repeated string rai_media_filtered_reasons = 3;</code>
*
* @return The count of raiMediaFilteredReasons.
*/
public int getRaiMediaFilteredReasonsCount() {
return raiMediaFilteredReasons_.size();
}
/**
*
*
* <pre>
* Returns rai failure reasons if any.
* </pre>
*
* <code>repeated string rai_media_filtered_reasons = 3;</code>
*
* @param index The index of the element to return.
* @return The raiMediaFilteredReasons at the given index.
*/
public java.lang.String getRaiMediaFilteredReasons(int index) {
return raiMediaFilteredReasons_.get(index);
}
/**
*
*
* <pre>
* Returns rai failure reasons if any.
* </pre>
*
* <code>repeated string rai_media_filtered_reasons = 3;</code>
*
* @param index The index of the value to return.
* @return The bytes of the raiMediaFilteredReasons at the given index.
*/
public com.google.protobuf.ByteString getRaiMediaFilteredReasonsBytes(int index) {
return raiMediaFilteredReasons_.getByteString(index);
}
/**
*
*
* <pre>
* Returns rai failure reasons if any.
* </pre>
*
* <code>repeated string rai_media_filtered_reasons = 3;</code>
*
* @param index The index to set the value at.
* @param value The raiMediaFilteredReasons to set.
* @return This builder for chaining.
*/
public Builder setRaiMediaFilteredReasons(int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureRaiMediaFilteredReasonsIsMutable();
raiMediaFilteredReasons_.set(index, value);
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Returns rai failure reasons if any.
* </pre>
*
* <code>repeated string rai_media_filtered_reasons = 3;</code>
*
* @param value The raiMediaFilteredReasons to add.
* @return This builder for chaining.
*/
public Builder addRaiMediaFilteredReasons(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureRaiMediaFilteredReasonsIsMutable();
raiMediaFilteredReasons_.add(value);
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Returns rai failure reasons if any.
* </pre>
*
* <code>repeated string rai_media_filtered_reasons = 3;</code>
*
* @param values The raiMediaFilteredReasons to add.
* @return This builder for chaining.
*/
public Builder addAllRaiMediaFilteredReasons(java.lang.Iterable<java.lang.String> values) {
ensureRaiMediaFilteredReasonsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, raiMediaFilteredReasons_);
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Returns rai failure reasons if any.
* </pre>
*
* <code>repeated string rai_media_filtered_reasons = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearRaiMediaFilteredReasons() {
raiMediaFilteredReasons_ = com.google.protobuf.LazyStringArrayList.emptyList();
bitField0_ = (bitField0_ & ~0x00000004);
;
onChanged();
return this;
}
/**
*
*
* <pre>
* Returns rai failure reasons if any.
* </pre>
*
* <code>repeated string rai_media_filtered_reasons = 3;</code>
*
* @param value The bytes of the raiMediaFilteredReasons to add.
* @return This builder for chaining.
*/
public Builder addRaiMediaFilteredReasonsBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ensureRaiMediaFilteredReasonsIsMutable();
raiMediaFilteredReasons_.add(value);
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.GenerateVideoResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.GenerateVideoResponse)
private static final com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse();
}
public static com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GenerateVideoResponse> PARSER =
new com.google.protobuf.AbstractParser<GenerateVideoResponse>() {
@java.lang.Override
public GenerateVideoResponse 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<GenerateVideoResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GenerateVideoResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.GenerateVideoResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/geode | 36,324 | geode-core/src/distributedTest/java/org/apache/geode/internal/cache/SizingFlagDUnitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.cache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.apache.geode.DataSerializable;
import org.apache.geode.DataSerializer;
import org.apache.geode.cache.AttributesFactory;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.DataPolicy;
import org.apache.geode.cache.EntryEvent;
import org.apache.geode.cache.EvictionAction;
import org.apache.geode.cache.EvictionAttributes;
import org.apache.geode.cache.InterestPolicy;
import org.apache.geode.cache.PartitionAttributes;
import org.apache.geode.cache.PartitionAttributesFactory;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.Scope;
import org.apache.geode.cache.SubscriptionAttributes;
import org.apache.geode.cache.control.ResourceManager;
import org.apache.geode.cache.partition.PartitionRegionHelper;
import org.apache.geode.cache.util.CacheListenerAdapter;
import org.apache.geode.cache.util.ObjectSizer;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.test.dunit.Assert;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.SerializableCallable;
import org.apache.geode.test.dunit.SerializableRunnable;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
/**
* A test of the when we will use the object sizer to determine the actual size of objects wrapped
* in CacheDeserializables.
*
*
*
* TODO - I was intending to add tests that have an index and object sizer, but it appears we don't
* support indexes on regions with overflow to disk.
*
*/
public class SizingFlagDUnitTest extends JUnit4CacheTestCase {
public SizingFlagDUnitTest() {
super();
}
@Test
public void testRRMemLRU() {
doRRMemLRUTest();
}
@Test
public void testRRMemLRUDeltaAndFlag() {
doRRMemLRUDeltaTest(true);
}
@Test
public void testRRMemLRUDelta() {
doRRMemLRUDeltaTest(false);
}
@Test
public void testRRListener() {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
createRR(vm0);
createRR(vm1);
addListener(vm0);
addListener(vm1);
doListenerTestRR(vm0, vm1);
}
@Test
public void testPRMemLRU() {
doPRMemLRUTest();
}
@Test
public void testPRMemLRUAndFlagDeltaPutOnPrimary() {
doPRDeltaTestLRU(false, false, true, false);
}
@Test
public void testPRMemLRUDeltaPutOnPrimary() {
doPRDeltaTestLRU(false, false, true, false);
}
@Test
public void testPRMemLRUAndFlagDeltaPutOnSecondary() {
doPRDeltaTestLRU(false, false, false, true);
}
@Test
public void testPRMemLRUDeltaPutOnSecondary() {
doPRDeltaTestLRU(false, false, false, true);
}
@Test
public void testPRNoLRUDelta() {
doPRNoLRUDeltaTest(false);
}
@Test
public void testPRNoLRUAndFlagDelta() {
doPRNoLRUDeltaTest(true);
}
@Test
public void testPRListener() {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
createPR(vm0, true);
createPR(vm1, true);
addListener(vm0);
addListener(vm1);
doListenerTestPR(vm0, vm1);
}
@Test
public void testPRHeapLRU() {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
createPRHeapLRU(vm0);
createPRHeapLRU(vm1);
put(vm0, new TestKey("a"), new TestObject(100, 1000));
assertValueType(vm0, new TestKey("a"), ValueType.CD_SERIALIZED);
assertValueType(vm1, new TestKey("a"), ValueType.CD_SERIALIZED);
assertEquals(1, getObjectSizerInvocations(vm0));
long origSize0 = getSizeFromPRStats(vm0);
assertTrue("Size was " + origSize0, 1000 > origSize0);
assertEquals(1, getObjectSizerInvocations(vm1));
long origSize1 = getSizeFromPRStats(vm1);
assertTrue("Size was " + origSize1, 1000 > origSize1);
get(vm0, new TestKey("a"), new TestObject(100, 1000));
assertValueType(vm0, new TestKey("a"), ValueType.CD_DESERIALIZED);
assertValueType(vm1, new TestKey("a"), ValueType.CD_SERIALIZED);
// assertTrue(1000 < getSizeFromPRStats(vm0));
assertEquals(3, getObjectSizerInvocations(vm0));
// assertTrue(1000 > getSizeFromPRStats(vm1));
assertEquals(1, getObjectSizerInvocations(vm1));
// Test what happens when we reach the heap threshold??
}
@Test
public void testRRHeapLRU() {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
createRRHeapLRU(vm0);
createRRHeapLRU(vm1);
put(vm0, "a", new TestObject(100, 1000));
assertValueType(vm0, "a", ValueType.RAW_VALUE);
assertValueType(vm1, "a", ValueType.CD_SERIALIZED);
assertEquals(1, getObjectSizerInvocations(vm0));
assertEquals(0, getObjectSizerInvocations(vm1));
get(vm1, "a", new TestObject(100, 1000));
assertValueType(vm0, "a", ValueType.RAW_VALUE);
assertValueType(vm1, "a", ValueType.CD_DESERIALIZED);
assertEquals(1, getObjectSizerInvocations(vm0));
assertEquals(1, getObjectSizerInvocations(vm1));
// Test what happens when we reach the heap threshold??
}
@Test
public void testPRHeapLRUDeltaWithFlagPutOnPrimary() {
doPRDeltaTestLRU(false, true, true, false);
}
@Test
public void testPRHeapLRUDeltaPutOnPrimary() {
doPRDeltaTestLRU(false, true, true, false);
}
@Test
public void testPRHeapLRUDeltaWithFlagPutOnSecondary() {
doPRDeltaTestLRU(false, true, false, true);
}
@Test
public void testPRHeapLRUDeltaPutOnSecondary() {
doPRDeltaTestLRU(false, true, false, true);
}
// test to cover bug41916
@Test
public void testLargeDelta() {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
setDeltaRecalculatesSize(vm0, false);
setDeltaRecalculatesSize(vm1, false);
createPR(vm0, false);
createPR(vm1, false);
// make a string bigger than socket-buffer-size which defaults to 32k
int BIG_DELTA_SIZE = 32 * 1024 * 2;
StringBuilder sb = new StringBuilder(BIG_DELTA_SIZE);
for (int i = 0; i < BIG_DELTA_SIZE; i++) {
sb.append('7');
}
TestDelta delta1 = new TestDelta(true, sb.toString());
assignPRBuckets(vm0);
boolean vm0isPrimary = prHostsBucketForKey(vm0, 0);
if (!vm0isPrimary) {
assertEquals(true, prHostsBucketForKey(vm1, 0));
}
VM primaryVm;
VM secondaryVm;
if (vm0isPrimary) {
primaryVm = vm0;
secondaryVm = vm1;
} else {
primaryVm = vm1;
secondaryVm = vm0;
}
put(secondaryVm, 0, delta1);
}
void doPRDeltaTestLRU(boolean shouldSizeChange, boolean heapLRU, boolean putOnPrimary,
boolean wasDelta) {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
setDeltaRecalculatesSize(vm0, shouldSizeChange);
setDeltaRecalculatesSize(vm1, shouldSizeChange);
if (heapLRU) {
createPRHeapLRU(vm0);
createPRHeapLRU(vm1);
} else {// memLRU
createPR(vm0, true);
createPR(vm1, true);
}
assignPRBuckets(vm0);
boolean vm0isPrimary = prHostsBucketForKey(vm0, 0);
if (!vm0isPrimary) {
assertEquals(true, prHostsBucketForKey(vm1, 0));
}
VM primaryVm;
VM secondaryVm;
if (vm0isPrimary) {
primaryVm = vm0;
secondaryVm = vm1;
} else {
primaryVm = vm1;
secondaryVm = vm0;
}
TestDelta delta1 = new TestDelta(false, "12345");
if (putOnPrimary) {
put(primaryVm, 0, delta1);
} else {
put(secondaryVm, 0, delta1);
}
// if the put is done on the primary then it will be CD_DESERIALIZED on the primary
// otherwise it will be CD_SERIALIZED on the primary.
if (putOnPrimary) {
assertValueType(primaryVm, 0, ValueType.CD_DESERIALIZED);
assertEquals(1, getObjectSizerInvocations(primaryVm));
} else {
assertValueType(primaryVm, 0, ValueType.CD_SERIALIZED);
assertEquals(0, getObjectSizerInvocations(primaryVm));
}
// It will always be CD_SERIALIZED on the secondary.
assertValueType(secondaryVm, 0, ValueType.CD_SERIALIZED);
assertEquals(0, getObjectSizerInvocations(secondaryVm));
long origEvictionSize0 = getSizeFromEvictionStats(primaryVm);
long origEvictionSize1 = getSizeFromEvictionStats(secondaryVm);
long origPRSize0 = getSizeFromPRStats(primaryVm);
long origPRSize1 = getSizeFromPRStats(secondaryVm);
delta1.info = "1234567890";
delta1.hasDelta = true;
// Update the delta
if (putOnPrimary) {
put(primaryVm, 0, delta1);
} else {
put(secondaryVm, 0, delta1);
}
assertValueType(primaryVm, 0, ValueType.CD_DESERIALIZED);
assertValueType(secondaryVm, 0, ValueType.CD_DESERIALIZED);
if (shouldSizeChange) {
assertEquals(2, getObjectSizerInvocations(primaryVm));
// once when we deserialize the value in the cache
// and once when we size the new value from applying the delta
assertEquals(2, getObjectSizerInvocations(secondaryVm));
} else if (wasDelta) {
assertEquals(0, getObjectSizerInvocations(primaryVm));
// 1 sizer invoke since the first value needs to be deserialized
assertEquals(0, getObjectSizerInvocations(secondaryVm));
} else {
assertEquals(1, getObjectSizerInvocations(primaryVm));
// 1 sizer invoke since the first value needs to be deserialized
assertEquals(0, getObjectSizerInvocations(secondaryVm));
}
long finalEvictionSize0 = getSizeFromEvictionStats(primaryVm);
long finalEvictionSize1 = getSizeFromEvictionStats(secondaryVm);
long finalPRSize0 = getSizeFromPRStats(primaryVm);
long finalPRSize1 = getSizeFromPRStats(secondaryVm);
if (shouldSizeChange) {
// I'm not sure what the change in size should be, because we went
// from serialized to deserialized
assertTrue(finalEvictionSize0 - origEvictionSize0 != 0);
assertTrue(finalPRSize0 - origPRSize0 != 0);
assertTrue(finalEvictionSize1 - origEvictionSize1 != 0);
assertTrue(finalPRSize1 - origPRSize1 != 0);
} else {
assertEquals(0, finalEvictionSize1 - origEvictionSize1);
assertEquals(0, finalPRSize0 - origPRSize0);
assertEquals(0, finalPRSize1 - origPRSize1);
}
}
private void addListener(VM vm) {
vm.invoke(new SerializableRunnable("Add listener") {
@Override
public void run() {
Cache cache = getCache();
Region region = cache.getRegion("region");
try {
region.getAttributesMutator().addCacheListener(new TestCacheListener());
} catch (Exception e) {
Assert.fail("couldn't create index", e);
}
}
});
}
private void doListenerTestRR(VM vm0, VM vm1) {
assertEquals(0, getObjectSizerInvocations(vm0));
assertEquals(0, getObjectSizerInvocations(vm1));
put(vm0, "a", new TestObject(100, 100000));
assertEquals(1, getObjectSizerInvocations(vm0));
assertEquals(1, getObjectSizerInvocations(vm1));
long origEvictionSize0 = getSizeFromEvictionStats(vm0);
long origEvictionSize1 = getSizeFromEvictionStats(vm1);
assertValueType(vm0, "a", ValueType.RAW_VALUE);
assertValueType(vm1, "a", ValueType.CD_DESERIALIZED);
assertTrue(origEvictionSize0 >= 100000);
assertTrue(origEvictionSize1 >= 100000);
put(vm0, "a", new TestObject(200, 200000));
assertEquals(2, getObjectSizerInvocations(vm0));
assertEquals(2, getObjectSizerInvocations(vm1));
long finalEvictionSize0 = getSizeFromEvictionStats(vm0);
long finalEvictionSize1 = getSizeFromEvictionStats(vm1);
assertValueType(vm0, "a", ValueType.RAW_VALUE);
assertValueType(vm1, "a", ValueType.CD_DESERIALIZED);
assertEquals(100000, finalEvictionSize0 - origEvictionSize0);
assertEquals(100000, finalEvictionSize1 - origEvictionSize1);
}
private void doListenerTestPR(VM vm0, VM vm1) {
assertEquals(0, getObjectSizerInvocations(vm0));
assertEquals(0, getObjectSizerInvocations(vm1));
put(vm0, "a", new TestObject(100, 100000));
assertEquals(1, getObjectSizerInvocations(vm0));
assertEquals(1, getObjectSizerInvocations(vm1));
long origEvictionSize0 = getSizeFromEvictionStats(vm0);
long origEvictionSize1 = getSizeFromEvictionStats(vm1);
long origPRSize0 = getSizeFromPRStats(vm1);
long origPRSize1 = getSizeFromPRStats(vm1);
assertValueType(vm0, "a", ValueType.CD_DESERIALIZED);
assertValueType(vm1, "a", ValueType.CD_DESERIALIZED);
assertTrue(origEvictionSize1 >= 100000);
assertTrue(origEvictionSize0 >= 100000);
assertTrue(origPRSize0 <= 500);
assertTrue(origPRSize1 <= 500);
put(vm0, "a", new TestObject(200, 200000));
assertEquals(2, getObjectSizerInvocations(vm0));
assertEquals(2, getObjectSizerInvocations(vm1));
long finalEvictionSize0 = getSizeFromEvictionStats(vm0);
long finalEvictionSize1 = getSizeFromEvictionStats(vm1);
long finalPRSize0 = getSizeFromPRStats(vm0);
long finalPRSize1 = getSizeFromPRStats(vm1);
assertValueType(vm0, "a", ValueType.CD_DESERIALIZED);
assertValueType(vm1, "a", ValueType.CD_DESERIALIZED);
assertEquals(100000, finalEvictionSize0 - origEvictionSize0);
assertEquals(100000, finalEvictionSize1 - origEvictionSize1);
assertEquals(100, finalPRSize0 - origPRSize0);
assertEquals(100, finalPRSize1 - origPRSize1);
}
private void doRRMemLRUTest() {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
createRR(vm0);
createRR(vm1);
put(vm0, "a", new TestObject(100, 100000));
long origEvictionSize0 = getSizeFromEvictionStats(vm0);
long origEvictionSize1 = getSizeFromEvictionStats(vm1);
put(vm0, "a", new TestObject(200, 200000));
assertValueType(vm0, "a", ValueType.RAW_VALUE);
assertValueType(vm1, "a", ValueType.CD_SERIALIZED);
assertEquals(2, getObjectSizerInvocations(vm0));
long finalEvictionSize0 = getSizeFromEvictionStats(vm0);
long finalEvictionSize1 = getSizeFromEvictionStats(vm1);
assertEquals(100000, finalEvictionSize0 - origEvictionSize0);
assertEquals(100, finalEvictionSize1 - origEvictionSize1);
assertEquals(0, getObjectSizerInvocations(vm1));
// Do a get to make sure we deserialize the object and calculate
// the size adjustment
Object v = new TestObject(200, 200000);
get(vm1, "a", v);
int vSize = CachedDeserializableFactory.calcSerializedMemSize(v);
assertValueType(vm1, "a", ValueType.CD_DESERIALIZED);
long evictionSizeAfterGet = getSizeFromEvictionStats(vm1);
assertEquals(1, getObjectSizerInvocations(vm1));
assertEquals(200000 + CachedDeserializableFactory.overhead() - vSize,
evictionSizeAfterGet - finalEvictionSize1);
// Do a put that will trigger an eviction if it is deserialized
put(vm0, "b", new TestObject(100, 1000000));
assertEquals(1, getEvictions(vm0));
assertEquals(0, getEvictions(vm1));
// Do a get to make sure we deserialize the object and calculate
// the size adjustment
get(vm1, "b", new TestObject(100, 1000000));
assertEquals(1, getEvictions(vm1));
}
private void doPRMemLRUTest() {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
createPR(vm0, true);
createPR(vm1, true);
put(vm0, 0, new TestObject(100, 100000));
assertValueType(vm0, 0, ValueType.CD_SERIALIZED);
assertValueType(vm1, 0, ValueType.CD_SERIALIZED);
long origEvictionSize0 = getSizeFromEvictionStats(vm0);
long origEvictionSize1 = getSizeFromEvictionStats(vm1);
long origPRSize0 = getSizeFromPRStats(vm0);
long origPRSize1 = getSizeFromPRStats(vm1);
put(vm0, 0, new TestObject(200, 200000));
assertEquals(0, getObjectSizerInvocations(vm0));
long finalEvictionSize0 = getSizeFromEvictionStats(vm0);
long finalPRSize0 = getSizeFromPRStats(vm0);
long finalEvictionSize1 = getSizeFromEvictionStats(vm1);
long finalPRSize1 = getSizeFromPRStats(vm1);
assertEquals(100, finalEvictionSize0 - origEvictionSize0);
assertEquals(100, finalEvictionSize1 - origEvictionSize1);
assertEquals(100, finalPRSize0 - origPRSize0);
assertEquals(100, finalPRSize1 - origPRSize1);
assertEquals(0, getObjectSizerInvocations(vm1));
// Do a get to see if we deserialize the object and calculate
// the size adjustment
Object v = new TestObject(200, 200000);
get(vm0, 0, v);
int vSize = CachedDeserializableFactory.calcSerializedMemSize(v);
assertValueType(vm0, 0, ValueType.CD_DESERIALIZED);
assertValueType(vm1, 0, ValueType.CD_SERIALIZED);
long evictionSizeAfterGet = getSizeFromEvictionStats(vm0);
long prSizeAfterGet = getSizeFromPRStats(vm0);
assertEquals(1, getObjectSizerInvocations(vm0));
assertEquals(0, getObjectSizerInvocations(vm1));
assertEquals(200000 + CachedDeserializableFactory.overhead() - vSize,
evictionSizeAfterGet - finalEvictionSize0);
assertEquals(0, prSizeAfterGet - finalPRSize0);
// Do a put that will trigger an eviction if it is deserialized
// It should not be deserialized.
put(vm0, 113, new TestObject(100, 1024 * 1024));
assertValueType(vm0, 113, ValueType.CD_SERIALIZED);
assertValueType(vm1, 113, ValueType.CD_SERIALIZED);
long evictionSizeAfterPutVm1 = getSizeFromEvictionStats(vm1);
assertEquals(0, getEvictions(vm0));
assertEquals(0, getEvictions(vm1));
// Do a get to make sure we deserialize the object and calculate
// the size adjustment which should force an eviction
get(vm1, 113, new TestObject(100, 1024 * 1024));
long evictionSizeAfterGetVm1 = getSizeFromEvictionStats(vm1);
assertValueType(vm0, 113, ValueType.CD_SERIALIZED);
assertValueType(vm1, 113, ValueType.EVICTED);
assertEquals(1, getObjectSizerInvocations(vm0)); // from the get of key 0 on vm0
assertEquals(0, getEvictions(vm0));
assertEquals(1, getObjectSizerInvocations(vm1));
assertEquals(2, getEvictions(vm1));
}
private void doRRMemLRUDeltaTest(boolean shouldSizeChange) {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
setDeltaRecalculatesSize(vm0, shouldSizeChange);
setDeltaRecalculatesSize(vm1, shouldSizeChange);
createRR(vm0);
createRR(vm1);
TestDelta delta1 = new TestDelta(false, "12345");
put(vm0, "a", delta1);
assertValueType(vm0, "a", ValueType.RAW_VALUE);
assertValueType(vm1, "a", ValueType.CD_SERIALIZED);
assertEquals(1, getObjectSizerInvocations(vm0));
assertEquals(0, getObjectSizerInvocations(vm1));
long origEvictionSize0 = getSizeFromEvictionStats(vm0);
long origEvictionSize1 = getSizeFromEvictionStats(vm1);
delta1.info = "1234567890";
delta1.hasDelta = true;
// Update the delta
put(vm0, "a", delta1);
assertValueType(vm0, "a", ValueType.RAW_VALUE);
assertValueType(vm1, "a", ValueType.CD_DESERIALIZED);
assertEquals(2, getObjectSizerInvocations(vm0));
long finalEvictionSize0 = getSizeFromEvictionStats(vm0);
long finalEvictionSize1 = getSizeFromEvictionStats(vm1);
assertEquals(5, finalEvictionSize0 - origEvictionSize0);
if (shouldSizeChange) {
assertEquals(1, getObjectSizerInvocations(vm1));
// I'm not sure what the change in size should be, because we went
// from serialized to deserialized
assertTrue(finalEvictionSize1 - origEvictionSize1 != 0);
} else {
// we invoke the sizer once when we deserialize the original to apply the delta to it
assertEquals(0, getObjectSizerInvocations(vm1));
assertEquals(0, finalEvictionSize1 - origEvictionSize1);
}
}
private void doPRNoLRUDeltaTest(boolean shouldSizeChange) {
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
setDeltaRecalculatesSize(vm0, shouldSizeChange);
setDeltaRecalculatesSize(vm1, shouldSizeChange);
createPR(vm0, false);
createPR(vm1, false);
TestDelta delta1 = new TestDelta(false, "12345");
put(vm0, "a", delta1);
long origPRSize0 = getSizeFromPRStats(vm0);
long origPRSize1 = getSizeFromPRStats(vm1);
delta1.info = "1234567890";
delta1.hasDelta = true;
// Update the delta
put(vm0, "a", delta1);
long finalPRSize0 = getSizeFromPRStats(vm0);
long finalPRSize1 = getSizeFromPRStats(vm1);
if (shouldSizeChange) {
// I'm not sure what the change in size should be, because we went
// from serialized to deserialized
assertTrue(finalPRSize0 - origPRSize0 != 0);
assertTrue(finalPRSize1 - origPRSize1 != 0);
} else {
assertEquals(0, finalPRSize0 - origPRSize0);
assertEquals(0, finalPRSize1 - origPRSize1);
}
}
private long getSizeFromPRStats(VM vm0) {
return (Long) vm0.invoke(new SerializableCallable() {
@Override
public Object call() {
Cache cache = getCache();
LocalRegion region = (LocalRegion) cache.getRegion("region");
if (region instanceof PartitionedRegion) {
long total = 0;
PartitionedRegion pr = ((PartitionedRegion) region);
for (int i = 0; i < pr.getPartitionAttributes().getTotalNumBuckets(); i++) {
total += pr.getDataStore().getBucketSize(i);
}
return total;
} else {
return 0L;
}
}
});
}
private long getSizeFromEvictionStats(VM vm0) {
return (Long) vm0.invoke(new SerializableCallable() {
@Override
public Object call() {
Cache cache = getCache();
LocalRegion region = (LocalRegion) cache.getRegion("region");
return getSizeFromEvictionStats(region);
}
});
}
private long getEvictions(VM vm0) {
return (Long) vm0.invoke(new SerializableCallable() {
@Override
public Object call() {
Cache cache = getCache();
LocalRegion region = (LocalRegion) cache.getRegion("region");
return getEvictions(region);
}
});
}
private int getObjectSizerInvocations(VM vm0) {
return (Integer) vm0.invoke(new SerializableCallable() {
@Override
public Object call() {
Cache cache = getCache();
LocalRegion region = (LocalRegion) cache.getRegion("region");
return getObjectSizerInvocations(region);
}
});
}
private void assignPRBuckets(VM vm) {
vm.invoke(new SerializableRunnable("assignPRBuckets") {
@Override
public void run() {
Cache cache = getCache();
PartitionRegionHelper.assignBucketsToPartitions(cache.getRegion("region"));
}
});
}
private boolean prHostsBucketForKey(VM vm, final Object key) {
Boolean result = (Boolean) vm.invoke(new SerializableCallable("prHostsBucketForKey") {
@Override
public Object call() {
Cache cache = getCache();
DistributedMember myId = cache.getDistributedSystem().getDistributedMember();
Region region = cache.getRegion("region");
DistributedMember hostMember = PartitionRegionHelper.getPrimaryMemberForKey(region, key);
if (hostMember == null) {
throw new IllegalStateException("bucket for key " + key + " is not hosted!");
}
boolean res = myId.equals(hostMember);
// cache.getLogger().info("DEBUG prHostsBucketForKey=" + res);
return res;
}
});
return result;
}
private void put(VM vm0, final Object key, final Object value) {
vm0.invoke(new SerializableRunnable("Put data") {
@Override
public void run() {
Cache cache = getCache();
LocalRegion region = (LocalRegion) cache.getRegion("region");
// cache.getLogger().info("DEBUG about to put(" + key + ", " + value + ")");
region.put(key, value);
}
});
}
private void get(VM vm0, final Object key, final Object value) {
vm0.invoke(new SerializableRunnable("Put data") {
@Override
public void run() {
Cache cache = getCache();
LocalRegion region = (LocalRegion) cache.getRegion("region");
assertEquals(value, region.get(key));
}
});
}
protected int getObjectSizerInvocations(LocalRegion region) {
TestObjectSizer sizer = (TestObjectSizer) region.getEvictionAttributes().getObjectSizer();
int result = sizer.invocations.get();
region.getCache().getLogger().info("objectSizerInvocations=" + result);
return result;
}
private long getSizeFromEvictionStats(LocalRegion region) {
long result = region.getEvictionCounter();
// region.getCache().getLogger().info("DEBUG evictionSize=" + result);
return result;
}
private long getEvictions(LocalRegion region) {
return region.getTotalEvictions();
}
private void setDeltaRecalculatesSize(VM vm, final boolean shouldSizeChange) {
vm.invoke(new SerializableRunnable("setDeltaRecalculatesSize") {
@Override
public void run() {
GemFireCacheImpl.DELTAS_RECALCULATE_SIZE = shouldSizeChange;
}
});
}
private void createRR(VM vm) {
vm.invoke(new SerializableRunnable("Create rr") {
@Override
public void run() {
Cache cache = getCache();
AttributesFactory<Integer, TestDelta> attr = new AttributesFactory<>();
attr.setDiskSynchronous(true);
attr.setDataPolicy(DataPolicy.REPLICATE);
attr.setScope(Scope.DISTRIBUTED_ACK);
attr.setEvictionAttributes(EvictionAttributes.createLRUMemoryAttributes(1,
new TestObjectSizer(), EvictionAction.OVERFLOW_TO_DISK));
attr.setDiskDirs(getMyDiskDirs());
Region region = cache.createRegion("region", attr.create());
}
});
}
private void assertValueType(VM vm, final Object key, final ValueType expectedType) {
vm.invoke(new SerializableRunnable("Create rr") {
@Override
public void run() {
Cache cache = getCache();
LocalRegion region = (LocalRegion) cache.getRegion("region");
Object value = region.getValueInVM(key);
switch (expectedType) {
case RAW_VALUE:
assertTrue("Value was " + value + " type " + value.getClass(),
!(value instanceof CachedDeserializable));
break;
case CD_SERIALIZED:
assertTrue("Value was " + value + " type " + value.getClass(),
value instanceof CachedDeserializable);
assertTrue("Value not serialized",
((CachedDeserializable) value).getValue() instanceof byte[]);
break;
case CD_DESERIALIZED:
assertTrue("Value was " + value + " type " + value.getClass(),
value instanceof CachedDeserializable);
assertTrue("Value was serialized",
!(((CachedDeserializable) value).getValue() instanceof byte[]));
break;
case EVICTED:
assertEquals(null, value);
break;
}
}
});
}
private File[] getMyDiskDirs() {
long random = new Random().nextLong();
File file = new File(Long.toString(random));
file.mkdirs();
return new File[] {file};
}
private void createPR(VM vm, final boolean enableLRU) {
vm.invoke(new SerializableRunnable("Create pr") {
@Override
public void run() {
Cache cache = getCache();
AttributesFactory<Integer, TestDelta> attr = new AttributesFactory<>();
attr.setDiskSynchronous(true);
PartitionAttributesFactory<Integer, TestDelta> paf =
new PartitionAttributesFactory<>();
paf.setRedundantCopies(1);
if (enableLRU) {
paf.setLocalMaxMemory(1); // memlru limit is 1 megabyte
attr.setEvictionAttributes(EvictionAttributes
.createLRUMemoryAttributes(new TestObjectSizer(), EvictionAction.OVERFLOW_TO_DISK));
attr.setDiskDirs(getMyDiskDirs());
}
PartitionAttributes<Integer, TestDelta> prAttr = paf.create();
attr.setPartitionAttributes(prAttr);
attr.setDataPolicy(DataPolicy.PARTITION);
attr.setSubscriptionAttributes(new SubscriptionAttributes(InterestPolicy.ALL));
Region<Integer, TestDelta> region = cache.createRegion("region", attr.create());
}
});
}
private void createRRHeapLRU(VM vm) {
vm.invoke(new SerializableRunnable("Create rr") {
@Override
public void run() {
Cache cache = getCache();
ResourceManager manager = cache.getResourceManager();
manager.setCriticalHeapPercentage(95);
manager.setEvictionHeapPercentage(90);
AttributesFactory<Integer, TestDelta> attr = new AttributesFactory<>();
attr.setEvictionAttributes(EvictionAttributes.createLRUHeapAttributes(new TestObjectSizer(),
EvictionAction.OVERFLOW_TO_DISK));
attr.setDiskDirs(getMyDiskDirs());
attr.setDataPolicy(DataPolicy.REPLICATE);
attr.setScope(Scope.DISTRIBUTED_ACK);
attr.setDiskDirs(getMyDiskDirs());
Region region = cache.createRegion("region", attr.create());
}
});
}
private void createPRHeapLRU(VM vm) {
vm.invoke(new SerializableRunnable("Create pr") {
@Override
public void run() {
Cache cache = getCache();
ResourceManager manager = cache.getResourceManager();
manager.setCriticalHeapPercentage(95);
manager.setEvictionHeapPercentage(90);
AttributesFactory<Integer, TestDelta> attr = new AttributesFactory<>();
PartitionAttributesFactory<Integer, TestDelta> paf =
new PartitionAttributesFactory<>();
paf.setRedundantCopies(1);
attr.setEvictionAttributes(EvictionAttributes.createLRUHeapAttributes(new TestObjectSizer(),
EvictionAction.LOCAL_DESTROY));
PartitionAttributes<Integer, TestDelta> prAttr = paf.create();
attr.setPartitionAttributes(prAttr);
attr.setDataPolicy(DataPolicy.PARTITION);
attr.setSubscriptionAttributes(new SubscriptionAttributes(InterestPolicy.ALL));
Region<Integer, TestDelta> region = cache.createRegion("region", attr.create());
}
});
}
private static class TestObjectSizer implements ObjectSizer {
private final AtomicInteger invocations = new AtomicInteger();
@Override
public int sizeof(Object o) {
if (InternalDistributedSystem.getLogger().fineEnabled()) {
InternalDistributedSystem.getLogger()
.fine("TestObjectSizer invoked"/* , new Exception("stack trace") */);
}
if (o instanceof TestObject) {
// org.apache.geode.internal.cache.GemFireCache.getInstance().getLogger().info("DEBUG
// TestObjectSizer: sizeof o=" + o, new RuntimeException("STACK"));
invocations.incrementAndGet();
return ((TestObject) o).sizeForSizer;
}
if (o instanceof TestDelta) {
// org.apache.geode.internal.cache.GemFireCache.getInstance().getLogger().info("DEBUG
// TestObjectSizer: sizeof delta o=" + o, new RuntimeException("STACK"));
invocations.incrementAndGet();
return ((TestDelta) o).info.length();
}
// This is the key. Why don't we handle Integers internally?
if (o instanceof Integer) {
return 0;
}
if (o instanceof TestKey) {
// org.apache.geode.internal.cache.GemFireCache.getInstance().getLogger().info("DEBUG
// TestObjectSizer: sizeof TestKey o=" + o, new RuntimeException("STACK"));
invocations.incrementAndGet();
return ((TestKey) o).value.length();
}
throw new RuntimeException("Unpected type to be sized " + o.getClass() + ", object=" + o);
}
}
private static class TestKey implements DataSerializable {
String value;
public TestKey() {
}
public TestKey(String value) {
this.value = value;
}
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
value = DataSerializer.readString(in);
}
@Override
public void toData(DataOutput out) throws IOException {
DataSerializer.writeString(value, out);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof TestKey)) {
return false;
}
TestKey other = (TestKey) obj;
if (value == null) {
return other.value == null;
} else
return value.equals(other.value);
}
}
private static class TestObject implements DataSerializable {
public int sizeForSizer;
public int sizeForSerialization;
public TestObject() {
}
public TestObject(int sizeForSerialization, int sizeForSizer) {
super();
this.sizeForSizer = sizeForSizer;
this.sizeForSerialization = sizeForSerialization;
}
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
sizeForSizer = in.readInt();
sizeForSerialization = in.readInt();
// We don't actually need these things.
in.skipBytes(sizeForSerialization);
}
@Override
public void toData(DataOutput out) throws IOException {
out.writeInt(sizeForSizer);
out.writeInt(sizeForSerialization);
out.write(new byte[sizeForSerialization]);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + sizeForSerialization;
result = prime * result + sizeForSizer;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof TestObject)) {
return false;
}
TestObject other = (TestObject) obj;
if (sizeForSerialization != other.sizeForSerialization) {
return false;
}
return sizeForSizer == other.sizeForSizer;
}
@Override
public String toString() {
return "TestObject [sizeForSerialization=" + sizeForSerialization + ", sizeForSizer="
+ sizeForSizer + "]";
}
}
public static class TestCacheListener extends CacheListenerAdapter {
@Override
public void afterCreate(EntryEvent event) {
// Make sure we deserialize the new value
event.getRegion().getCache().getLogger().fine("invoked afterCreate with " + event);
event.getRegion().getCache().getLogger().info(String.format("%s",
"value is " + event.getNewValue()));
}
@Override
public void afterUpdate(EntryEvent event) {
// Make sure we deserialize the new value
event.getRegion().getCache().getLogger().fine("invoked afterUpdate with ");
event.getRegion().getCache().getLogger().info(String.format("%s",
"value is " + event.getNewValue()));
}
}
enum ValueType {
RAW_VALUE, CD_SERIALIZED, CD_DESERIALIZED, EVICTED
}
}
|
apache/samza | 36,871 | samza-core/src/main/java/org/apache/samza/clustermanager/StandbyContainerManager.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 java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.samza.SamzaException;
import org.apache.samza.config.ClusterManagerConfig;
import org.apache.samza.config.Config;
import org.apache.samza.container.LocalityManager;
import org.apache.samza.job.model.ProcessorLocality;
import org.apache.samza.job.model.JobModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Encapsulates logic and state concerning standby-containers.
*/
public class StandbyContainerManager {
private static final Logger log = LoggerFactory.getLogger(StandbyContainerManager.class);
private final SamzaApplicationState samzaApplicationState;
private final LocalityManager localityManager;
// Map of samza containerIDs to their corresponding active and standby containers, e.g., 0 -> {0-0, 0-1}, 0-0 -> {0, 0-1}
// This is used for checking no two standbys or active-standby-pair are started on the same host
private final Map<String, List<String>> standbyContainerConstraints;
// Map of active containers that are in failover, indexed by the active container's resourceID (at the time of failure)
private final Map<String, FailoverMetadata> failovers;
// Resource-manager, used to stop containers
private ClusterResourceManager clusterResourceManager;
// FaultDomainManager, used to get fault domain information of different hosts from the cluster manager.
private final FaultDomainManager faultDomainManager;
private final boolean isFaultDomainAwareStandbyEnabled;
public StandbyContainerManager(SamzaApplicationState samzaApplicationState, ClusterResourceManager clusterResourceManager,
LocalityManager localityManager, Config config, FaultDomainManager faultDomainManager) {
this.failovers = new ConcurrentHashMap<>();
this.localityManager = localityManager;
this.standbyContainerConstraints = new HashMap<>();
this.samzaApplicationState = samzaApplicationState;
JobModel jobModel = samzaApplicationState.jobModelManager.jobModel();
// populate the standbyContainerConstraints map by iterating over all containers
jobModel.getContainers()
.keySet()
.forEach(containerId -> standbyContainerConstraints.put(containerId,
StandbyTaskUtil.getStandbyContainerConstraints(containerId, jobModel)));
this.clusterResourceManager = clusterResourceManager;
this.faultDomainManager = faultDomainManager;
ClusterManagerConfig clusterManagerConfig = new ClusterManagerConfig(config);
this.isFaultDomainAwareStandbyEnabled = clusterManagerConfig.getFaultDomainAwareStandbyEnabled();
log.info("Populated standbyContainerConstraints map {}", standbyContainerConstraints);
}
/**
* We handle the stopping of a container depending on the case which is decided using the exit-status:
* Case 1. an Active-Container which has stopped for an "unknown" reason, then we start it on the given preferredHost (but we record the resource-request)
* Case 2. Active container has stopped because of node failure, thene we initiate a failover
* Case 3. StandbyContainer has stopped after it was chosen for failover, see {@link StandbyContainerManager#handleStandbyContainerStop}
* Case 4. StandbyContainer has stopped but not because of a failover, see {@link StandbyContainerManager#handleStandbyContainerStop}
*
* @param containerID containerID of the stopped container
* @param resourceID last resourceID of the stopped container
* @param preferredHost the host on which the container was running
* @param exitStatus the exit status of the failed container
* @param containerAllocator the container allocator
*/
public void handleContainerStop(String containerID, String resourceID, String preferredHost, int exitStatus,
ContainerAllocator containerAllocator, Duration preferredHostRetryDelay) {
if (StandbyTaskUtil.isStandbyContainer(containerID)) {
handleStandbyContainerStop(containerID, resourceID, preferredHost, containerAllocator, preferredHostRetryDelay);
} else {
// initiate failover for the active container based on the exitStatus
switch (exitStatus) {
case SamzaResourceStatus.DISK_FAIL:
case SamzaResourceStatus.ABORTED:
case SamzaResourceStatus.PREEMPTED:
initiateStandbyAwareAllocation(containerID, resourceID, containerAllocator);
break;
// in all other cases, request-resource for the failed container, but record the resource-request, so that
// if this request expires, we can do a failover -- select a standby to stop & start the active on standby's host
default:
log.info("Requesting resource for active-container {} on host {}", containerID, preferredHost);
SamzaResourceRequest resourceRequest = containerAllocator.getResourceRequestWithDelay(containerID, preferredHost, preferredHostRetryDelay);
FailoverMetadata failoverMetadata = registerActiveContainerFailure(containerID, resourceID);
failoverMetadata.recordResourceRequest(resourceRequest);
containerAllocator.issueResourceRequest(resourceRequest);
break;
}
}
}
/**
* Handle the failed launch of a container, based on
* Case 1. If it is an active container, then initiate a failover for it.
* Case 2. If it is standby container, request a new resource on AnyHost.
* @param containerID the ID of the container that has failed
*/
public void handleContainerLaunchFail(String containerID, String resourceID,
ContainerAllocator containerAllocator) {
if (StandbyTaskUtil.isStandbyContainer(containerID)) {
log.info("Handling launch fail for standby-container {}, requesting resource on any host {}", containerID);
String activeContainerHost = getActiveContainerHost(containerID)
.orElse(null);
requestResource(containerAllocator, containerID, ResourceRequestState.ANY_HOST, Duration.ZERO, activeContainerHost);
} else {
initiateStandbyAwareAllocation(containerID, resourceID, containerAllocator);
}
}
/**
* Handle the failed stop for a container, based on
* Case 1. If it is standby container, continue the failover
* Case 2. If it is an active container, then this is in invalid state and throw an exception to alarm/restart.
* @param containerID the ID (e.g., 0, 1, 2) of the container that has failed
* @param resourceID id of the resource used for the failed container
*/
public void handleContainerStopFail(String containerID, String resourceID,
ContainerAllocator containerAllocator) {
if (StandbyTaskUtil.isStandbyContainer(containerID)) {
log.info("Handling stop fail for standby-container {}, continuing the failover (if present)", containerID);
// if this standbyContainerResource was stopped for a failover, we will find a metadata entry
Optional<StandbyContainerManager.FailoverMetadata> failoverMetadata = this.checkIfUsedForFailover(resourceID);
// if we find a metadata entry, we continue with the failover (select another standby or any-host appropriately)
failoverMetadata.ifPresent(
metadata -> initiateStandbyAwareAllocation(metadata.activeContainerID, metadata.activeContainerResourceID,
containerAllocator));
} else {
// If this class receives a callback for stop-fail on an active container, throw an exception
throw new SamzaException("Invalid State. Received stop container fail for container Id: " + containerID);
}
}
/**
* This method removes the fault domain of the host passed as an argument, from the set of fault domains, and then returns it.
* The set of fault domains returned is based on the set difference between all the available fault domains in the
* cluster and the fault domain associated with the host that is passed as input.
* @param hostToAvoid hostname whose fault domains are excluded
* @return The set of fault domains which excludes the fault domain that the given host is on
*/
public Set<FaultDomain> getAllowedFaultDomainsGivenHostToAvoid(String hostToAvoid) {
Set<FaultDomain> allFaultDomains = faultDomainManager.getAllFaultDomains();
Set<FaultDomain> faultDomainToAvoid = Optional.ofNullable(hostToAvoid)
.map(faultDomainManager::getFaultDomainsForHost)
.orElse(Collections.emptySet());
allFaultDomains.removeAll(faultDomainToAvoid);
return allFaultDomains;
}
/**
* If a standby container has stopped, then there are two possible cases
* Case 1. during a failover, the standby container was stopped for an active's start, then we
* 1. request a resource on the standby's host to place the activeContainer, and
* 2. request anyhost to place this standby
*
* Case 2. independent of a failover, the standby container stopped, in which proceed with its resource-request
* @param standbyContainerID SamzaContainerID of the standby container
* @param preferredHost Preferred host of the standby container
*/
private void handleStandbyContainerStop(String standbyContainerID, String resourceID, String preferredHost,
ContainerAllocator containerAllocator, Duration preferredHostRetryDelay) {
// if this standbyContainerResource was stopped for a failover, we will find a metadata entry
Optional<StandbyContainerManager.FailoverMetadata> failoverMetadata = this.checkIfUsedForFailover(resourceID);
if (failoverMetadata.isPresent()) {
String activeContainerID = failoverMetadata.get().activeContainerID;
String standbyContainerHostname = failoverMetadata.get().getStandbyContainerHostname(resourceID);
log.info("Requesting resource for active container {} on host {}, and backup container {} on any host",
activeContainerID, standbyContainerHostname, standbyContainerID);
// request standbycontainer's host for active-container
SamzaResourceRequest resourceRequestForActive =
containerAllocator.getResourceRequestWithDelay(activeContainerID, standbyContainerHostname, preferredHostRetryDelay);
// record the resource request, before issuing it to avoid race with allocation-thread
failoverMetadata.get().recordResourceRequest(resourceRequestForActive);
containerAllocator.issueResourceRequest(resourceRequestForActive);
// request any-host for standby container
requestResource(containerAllocator, standbyContainerID, ResourceRequestState.ANY_HOST, Duration.ZERO, standbyContainerHostname);
} else {
log.info("Issuing request for standby container {} on host {}, since this is not for a failover",
standbyContainerID, preferredHost);
String activeContainerHost = getActiveContainerHost(standbyContainerID)
.orElse(null);
requestResource(containerAllocator, standbyContainerID, preferredHost, preferredHostRetryDelay, activeContainerHost);
}
}
/** Method to handle standby-aware allocation for an active container.
* We try to find a standby host for the active container, and issue a stop on any standby-containers running on it,
* request resource to place the active on the standby's host, and one to place the standby elsewhere.
* When requesting for resources,
* NOTE: When rack awareness is turned on, we always pass the <code>hostToAvoid</> parameter as null for the {@link #requestResource} method used here
* because the hostname of the previous active processor that died does not exist in the running or pending container list anymore.
* However, different racks will always be guaranteed through {@link #checkStandbyConstraintsAndRunStreamProcessor}.
* @param activeContainerID the samzaContainerID of the active-container
* @param resourceID the samza-resource-ID of the container when it failed (used to index failover-state)
*/
private void initiateStandbyAwareAllocation(String activeContainerID, String resourceID,
ContainerAllocator containerAllocator) {
String standbyHost = this.selectStandbyHost(activeContainerID, resourceID);
// if the standbyHost returned is anyhost, we proceed with the request directly
if (standbyHost.equals(ResourceRequestState.ANY_HOST)) {
log.info("No standby container found for active container {}, making a resource-request for placing {} on {}, active's resourceID: {}",
activeContainerID, activeContainerID, ResourceRequestState.ANY_HOST, resourceID);
samzaApplicationState.failoversToAnyHost.incrementAndGet();
containerAllocator.requestResource(activeContainerID, ResourceRequestState.ANY_HOST);
} else {
// Check if there is a running standby-container on that host that needs to be stopped
List<String> standbySamzaContainerIds = this.standbyContainerConstraints.get(activeContainerID);
Map<String, SamzaResource> runningStandbyContainersOnHost = new HashMap<>();
this.samzaApplicationState.runningProcessors.forEach((samzaContainerId, samzaResource) -> {
if (standbySamzaContainerIds.contains(samzaContainerId) && samzaResource.getHost().equals(standbyHost)) {
runningStandbyContainersOnHost.put(samzaContainerId, samzaResource);
}
});
if (runningStandbyContainersOnHost.isEmpty()) {
// if there are no running standby-containers on the standbyHost, we proceed to directly make a resource request
log.info("No running standby container to stop on host {}, making a resource-request for placing {} on {}, active's resourceID: {}",
standbyHost, activeContainerID, standbyHost, resourceID);
FailoverMetadata failoverMetadata = this.registerActiveContainerFailure(activeContainerID, resourceID);
// record the resource request, before issuing it to avoid race with allocation-thread
SamzaResourceRequest resourceRequestForActive =
containerAllocator.getResourceRequest(activeContainerID, standbyHost);
failoverMetadata.recordResourceRequest(resourceRequestForActive);
containerAllocator.issueResourceRequest(resourceRequestForActive);
samzaApplicationState.failoversToStandby.incrementAndGet();
} else {
// if there is a running standby-container on the standbyHost, we issue a stop (the stopComplete callback completes the remainder of the flow)
FailoverMetadata failoverMetadata = this.registerActiveContainerFailure(activeContainerID, resourceID);
runningStandbyContainersOnHost.forEach((standbyContainerID, standbyResource) -> {
log.info("Initiating failover and stopping standby container, found standbyContainer {} = resource {}, "
+ "for active container {}", runningStandbyContainersOnHost.keySet(),
runningStandbyContainersOnHost.values(), activeContainerID);
failoverMetadata.updateStandbyContainer(standbyResource.getContainerId(), standbyResource.getHost());
samzaApplicationState.failoversToStandby.incrementAndGet();
this.clusterResourceManager.stopStreamProcessor(standbyResource);
});
// if multiple standbys are on the same host, we are in an invalid state, so we fail the deploy and retry
if (runningStandbyContainersOnHost.size() > 1) {
throw new SamzaException(
"Invalid State. Multiple standby containers found running on one host:" + runningStandbyContainersOnHost);
}
}
}
}
/**
* Method to select a standby host for a given active container.
* 1. We first try to select a host which has a running standby-container, that we haven't already selected for failover.
* 2. If we dont any such host, we iterate over last-known standbyHosts, if we haven't already selected it for failover.
* 3. If still dont find a host, we fall back to AnyHost.
*
* See https://issues.apache.org/jira/browse/SAMZA-2140
*
* @param activeContainerID Samza containerID of the active container
* @param activeContainerResourceID ResourceID of the active container at the time of its last failure
* @return standby host for the active container (if found), Any-host otherwise.
*/
private String selectStandbyHost(String activeContainerID, String activeContainerResourceID) {
log.info("Standby containers {} for active container {} (resourceID {})", this.standbyContainerConstraints.get(activeContainerID), activeContainerID, activeContainerResourceID);
// obtain any existing failover metadata
Optional<FailoverMetadata> failoverMetadata = getFailoverMetadata(activeContainerResourceID);
// Iterate over the list of running standby containers, to find a standby resource that we have not already
// used for a failover for this active resource
for (String standbyContainerID : this.standbyContainerConstraints.get(activeContainerID)) {
if (samzaApplicationState.runningProcessors.containsKey(standbyContainerID)) {
SamzaResource standbyContainerResource = samzaApplicationState.runningProcessors.get(standbyContainerID);
// use this standby if there was no previous failover for which this standbyResource was used
if (!(failoverMetadata.isPresent() && failoverMetadata.get()
.isStandbyResourceUsed(standbyContainerResource.getContainerId()))) {
log.info("Returning standby container {} in running state on host {} for active container {}",
standbyContainerID, standbyContainerResource.getHost(), activeContainerID);
return standbyContainerResource.getHost();
}
}
}
log.info("Did not find any running standby container for active container {}", activeContainerID);
// We iterate over the list of last-known standbyHosts to check if anyone of them has not already been tried
for (String standbyContainerID : this.standbyContainerConstraints.get(activeContainerID)) {
String standbyHost =
Optional.ofNullable(localityManager.readLocality().getProcessorLocality(standbyContainerID))
.map(ProcessorLocality::host)
.orElse(null);
if (StringUtils.isBlank(standbyHost)) {
log.info("No last known standbyHost for container {}", standbyContainerID);
} else if (failoverMetadata.isPresent() && failoverMetadata.get().isStandbyHostUsed(standbyHost)) {
log.info("Not using standby host {} for active container {} because it had already been selected", standbyHost,
activeContainerID);
} else {
// standbyHost is valid and has not already been selected
log.info("Returning standby host {} for active container {}", standbyHost, activeContainerID);
return standbyHost;
}
}
log.info("Did not find any standby host for active container {}, returning any-host", activeContainerID);
return ResourceRequestState.ANY_HOST;
}
/**
* Register the failure of an active container (identified by its resource ID).
*/
private FailoverMetadata registerActiveContainerFailure(String activeContainerID, String activeContainerResourceID) {
// this active container's resource ID is already registered, in which case update the metadata
FailoverMetadata failoverMetadata;
if (failovers.containsKey(activeContainerResourceID)) {
failoverMetadata = failovers.get(activeContainerResourceID);
} else {
failoverMetadata = new FailoverMetadata(activeContainerID, activeContainerResourceID);
}
this.failovers.put(activeContainerResourceID, failoverMetadata);
return failoverMetadata;
}
/**
* Check if this standbyContainerResource is present in the failoverState for an active container.
* This is used to determine if we requested a stop a container.
*/
private Optional<FailoverMetadata> checkIfUsedForFailover(String standbyContainerResourceId) {
if (standbyContainerResourceId == null) {
return Optional.empty();
}
for (FailoverMetadata failoverMetadata : failovers.values()) {
if (failoverMetadata.isStandbyResourceUsed(standbyContainerResourceId)) {
log.info("Standby container with resource id {} was selected for failover of active container {}",
standbyContainerResourceId, failoverMetadata.activeContainerID);
return Optional.of(failoverMetadata);
}
}
return Optional.empty();
}
/**
* This method checks from the config if standby allocation is fault domain aware or not, and requests resources accordingly.
*
* @param containerAllocator ContainerAllocator object that requests for resources from the resource manager
* @param containerID Samza container ID that will be run when a resource is allocated for this request
* @param preferredHost name of the host that you prefer to run the processor on
* @param preferredHostRetryDelay the {@link Duration} to add to the request timestamp
* @param hostToAvoid The hostname to avoid requesting this resource on if fault domain aware standby allocation is enabled
*/
void requestResource(ContainerAllocator containerAllocator, String containerID, String preferredHost, Duration preferredHostRetryDelay, String hostToAvoid) {
if (StandbyTaskUtil.isStandbyContainer(containerID) && isFaultDomainAwareStandbyEnabled) {
containerAllocator.requestResourceWithDelay(containerID, preferredHost, preferredHostRetryDelay, getAllowedFaultDomainsGivenHostToAvoid(hostToAvoid));
} else {
containerAllocator.requestResourceWithDelay(containerID, preferredHost, preferredHostRetryDelay, new HashSet<>());
}
}
/**
* This method returns the active container host given a standby or active container ID.
*
* @param containerID Standby or active container container ID
* @return The active container host
*/
Optional<String> getActiveContainerHost(String containerID) {
String activeContainerId = containerID;
if (StandbyTaskUtil.isStandbyContainer(containerID)) {
activeContainerId = StandbyTaskUtil.getActiveContainerId(containerID);
}
SamzaResource resource = samzaApplicationState.pendingProcessors.get(activeContainerId);
if (resource == null) {
resource = samzaApplicationState.runningProcessors.get(activeContainerId);
}
return Optional.ofNullable(resource)
.map(SamzaResource::getHost);
}
/**
* Check if matching this SamzaResourceRequest to the given resource, meets all standby-container container constraints.
* This includes the check that a standby and its active should not be on the same fault domain or the same host.
* @param containerIdToStart logical id of the container to start
* @param host potential host to start the container on
* @return
*/
boolean checkStandbyConstraints(String containerIdToStart, String host) {
List<String> containerIDsForStandbyConstraints = this.standbyContainerConstraints.get(containerIdToStart);
// Check if any of these conflicting containers are running/launching on host
for (String containerID : containerIDsForStandbyConstraints) {
SamzaResource resource = samzaApplicationState.pendingProcessors.get(containerID);
// return false if a conflicting container is pending for launch on the host
if (resource != null && isFaultDomainAwareStandbyEnabled
&& faultDomainManager.hasSameFaultDomains(host, resource.getHost())) {
log.info("Container {} cannot be started on host {} because container {} is already scheduled on this fault domain",
containerIdToStart, host, containerID);
if (StandbyTaskUtil.isStandbyContainer(containerIdToStart)) {
samzaApplicationState.failedFaultDomainAwareContainerAllocations.incrementAndGet();
}
return false;
} else if (resource != null && resource.getHost().equals(host)) {
log.info("Container {} cannot be started on host {} because container {} is already scheduled on this host",
containerIdToStart, host, containerID);
return false;
}
// return false if a conflicting container is running on the host
resource = samzaApplicationState.runningProcessors.get(containerID);
if (resource != null && isFaultDomainAwareStandbyEnabled
&& faultDomainManager.hasSameFaultDomains(host, resource.getHost())) {
log.info("Container {} cannot be started on host {} because container {} is already running on this fault domain",
containerIdToStart, host, containerID);
if (StandbyTaskUtil.isStandbyContainer(containerIdToStart)) {
samzaApplicationState.failedFaultDomainAwareContainerAllocations.incrementAndGet();
}
return false;
} else if (resource != null && resource.getHost().equals(host)) {
log.info("Container {} cannot be started on host {} because container {} is already running on this host",
containerIdToStart, host, containerID);
return false;
}
}
return true;
}
/**
* Attempt to the run a container on the given candidate resource, if doing so meets the standby container constraints.
* @param request The Samza container request
* @param preferredHost the preferred host associated with the container
* @param samzaResource the resource candidate
*/
public void checkStandbyConstraintsAndRunStreamProcessor(SamzaResourceRequest request, String preferredHost,
SamzaResource samzaResource, ContainerAllocator containerAllocator,
ResourceRequestState resourceRequestState) {
String containerID = request.getProcessorId();
if (checkStandbyConstraints(containerID, samzaResource.getHost())) {
// This resource can be used to launch this container
log.info("Running container {} on {} meets standby constraints, preferredHost = {}", containerID,
samzaResource.getHost(), preferredHost);
containerAllocator.runStreamProcessor(request, preferredHost);
if (isFaultDomainAwareStandbyEnabled && StandbyTaskUtil.isStandbyContainer(containerID)) {
samzaApplicationState.faultDomainAwareContainersStarted.incrementAndGet();
}
} else if (StandbyTaskUtil.isStandbyContainer(containerID)) {
// This resource cannot be used to launch this standby container, so we make a new anyhost request
log.info(
"Running standby container {} on host {} does not meet standby constraints, cancelling resource request, releasing resource, and making a new ANY_HOST request",
containerID, samzaResource.getHost());
releaseUnstartableContainer(request, samzaResource, preferredHost, resourceRequestState);
String activeContainerHost = getActiveContainerHost(containerID)
.orElse(null);
requestResource(containerAllocator, containerID, ResourceRequestState.ANY_HOST, Duration.ZERO, activeContainerHost);
samzaApplicationState.failedStandbyAllocations.incrementAndGet();
} else {
// This resource cannot be used to launch this active container, so we initiate a failover
log.warn(
"Running active container {} on host {} does not meet standby constraints, cancelling resource request, releasing resource",
containerID, samzaResource.getHost());
releaseUnstartableContainer(request, samzaResource, preferredHost, resourceRequestState);
Optional<FailoverMetadata> failoverMetadata = getFailoverMetadata(request);
String lastKnownResourceID =
failoverMetadata.isPresent() ? failoverMetadata.get().activeContainerResourceID : "unknown-" + containerID;
initiateStandbyAwareAllocation(containerID, lastKnownResourceID, containerAllocator);
samzaApplicationState.failedStandbyAllocations.incrementAndGet();
}
}
/**
* Handle an expired resource request
* @param containerID the containerID for which the resource request was made
* @param request the expired resource request
* @param alternativeResource an alternative, already-allocated, resource (if available)
* @param containerAllocator the container allocator (used to issue any required subsequent resource requests)
* @param resourceRequestState used to cancel resource requests if required.
*/
public void handleExpiredResourceRequest(String containerID, SamzaResourceRequest request,
Optional<SamzaResource> alternativeResource, ContainerAllocator containerAllocator,
ResourceRequestState resourceRequestState) {
if (StandbyTaskUtil.isStandbyContainer(containerID)) {
handleExpiredRequestForStandbyContainer(containerID, request, alternativeResource, containerAllocator,
resourceRequestState);
} else {
handleExpiredRequestForActiveContainer(containerID, request, containerAllocator, resourceRequestState);
}
}
/**
* Fetches a list of standby container for an active container
* @param activeContainerId logical id of the container ex: 0,1,2
* @return list of standby containers ex: for active container 0: {0-0, 0-1}
*/
List<String> getStandbyList(String activeContainerId) {
return this.standbyContainerConstraints.get(activeContainerId);
}
/**
* Release un-startable resources immediately and deletes requests corresponsing to it
*/
void releaseUnstartableContainer(SamzaResourceRequest request, SamzaResource resource, String preferredHost,
ResourceRequestState resourceRequestState) {
resourceRequestState.releaseUnstartableContainer(resource, preferredHost);
resourceRequestState.cancelResourceRequest(request);
}
// Handle an expired resource request that was made for placing a standby container
private void handleExpiredRequestForStandbyContainer(String containerID, SamzaResourceRequest request,
Optional<SamzaResource> alternativeResource, ContainerAllocator containerAllocator,
ResourceRequestState resourceRequestState) {
if (alternativeResource.isPresent()) {
// A standby container can be started on the anyhost-alternative-resource rightaway provided it passes all the
// standby constraints
log.info("Handling expired request, standby container {} can be started on alternative resource {}", containerID,
alternativeResource.get());
checkStandbyConstraintsAndRunStreamProcessor(request, ResourceRequestState.ANY_HOST, alternativeResource.get(),
containerAllocator, resourceRequestState);
} else {
// If there is no alternative-resource for the standby container we make a new anyhost request
log.info("Handling expired request, requesting anyHost resource for standby container {}", containerID);
resourceRequestState.cancelResourceRequest(request);
String activeContainerHost = getActiveContainerHost(containerID)
.orElse(null);
requestResource(containerAllocator, containerID, ResourceRequestState.ANY_HOST, Duration.ZERO, activeContainerHost);
}
}
// Handle an expired resource request that was made for placing an active container
private void handleExpiredRequestForActiveContainer(String containerID, SamzaResourceRequest request,
ContainerAllocator containerAllocator, ResourceRequestState resourceRequestState) {
log.info("Handling expired request for active container {}", containerID);
Optional<FailoverMetadata> failoverMetadata = getFailoverMetadata(request);
resourceRequestState.cancelResourceRequest(request);
// we use the activeContainer's resourceID to initiate the failover and index failover-state
// if there is no prior failure for this active-Container, we use "unknown"
String lastKnownResourceID =
failoverMetadata.isPresent() ? failoverMetadata.get().activeContainerResourceID : "unknown-" + containerID;
log.info("Handling expired request for active container {}, lastKnownResourceID is {}", containerID, lastKnownResourceID);
initiateStandbyAwareAllocation(containerID, lastKnownResourceID, containerAllocator);
}
/**
* Check if a activeContainerResource has failover-metadata associated with it
*/
private Optional<FailoverMetadata> getFailoverMetadata(String activeContainerResourceID) {
return this.failovers.containsKey(activeContainerResourceID) ? Optional.of(
this.failovers.get(activeContainerResourceID)) : Optional.empty();
}
/**
* Check if a SamzaResourceRequest was issued for a failover.
*/
private Optional<FailoverMetadata> getFailoverMetadata(SamzaResourceRequest resourceRequest) {
for (FailoverMetadata failoverMetadata : this.failovers.values()) {
if (failoverMetadata.containsResourceRequest(resourceRequest)) {
return Optional.of(failoverMetadata);
}
}
return Optional.empty();
}
@Override
public String toString() {
return this.failovers.toString();
}
/**
* Encapsulates metadata concerning the failover of an active container.
*/
public class FailoverMetadata {
public final String activeContainerID;
public final String activeContainerResourceID;
// Map of samza-container-resource ID to host, for each standby container selected for failover of the activeContainer
private final Map<String, String> selectedStandbyContainers;
// Resource requests issued during this failover
private final Set<SamzaResourceRequest> resourceRequests;
public FailoverMetadata(String activeContainerID, String activeContainerResourceID) {
this.activeContainerID = activeContainerID;
this.activeContainerResourceID = activeContainerResourceID;
this.selectedStandbyContainers = new HashMap<>();
resourceRequests = new HashSet<>();
}
// Check if this standbyContainerResourceID was used in this failover
public synchronized boolean isStandbyResourceUsed(String standbyContainerResourceID) {
return this.selectedStandbyContainers.keySet().contains(standbyContainerResourceID);
}
// Get the hostname corresponding to the standby resourceID
public synchronized String getStandbyContainerHostname(String standbyContainerResourceID) {
return selectedStandbyContainers.get(standbyContainerResourceID);
}
// Add the standbyContainer resource to the list of standbyContainers used in this failover
public synchronized void updateStandbyContainer(String standbyContainerResourceID, String standbyContainerHost) {
this.selectedStandbyContainers.put(standbyContainerResourceID, standbyContainerHost);
}
// Add the samzaResourceRequest to the list of resource requests associated with this failover
public synchronized void recordResourceRequest(SamzaResourceRequest samzaResourceRequest) {
this.resourceRequests.add(samzaResourceRequest);
}
// Check if this resource request has been issued in this failover
public synchronized boolean containsResourceRequest(SamzaResourceRequest samzaResourceRequest) {
return this.resourceRequests.contains(samzaResourceRequest);
}
// Check if this standby-host has been used in this failover, that is, if this host matches the host of a selected-standby,
// or if we have made a resourceRequest for this host
public boolean isStandbyHostUsed(String standbyHost) {
return this.selectedStandbyContainers.values().contains(standbyHost)
|| this.resourceRequests.stream().filter(request -> request.getPreferredHost().equals(standbyHost)).count() > 0;
}
@Override
public String toString() {
return "[activeContainerID: " + this.activeContainerID + " activeContainerResourceID: "
+ this.activeContainerResourceID + " selectedStandbyContainers:" + selectedStandbyContainers
+ " resourceRequests: " + resourceRequests + "]";
}
}
}
|
googleapis/google-cloud-java | 36,457 | java-redis/proto-google-cloud-redis-v1/src/main/java/com/google/cloud/redis/v1/UpdateInstanceRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/redis/v1/cloud_redis.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.redis.v1;
/**
*
*
* <pre>
* Request for
* [UpdateInstance][google.cloud.redis.v1.CloudRedis.UpdateInstance].
* </pre>
*
* Protobuf type {@code google.cloud.redis.v1.UpdateInstanceRequest}
*/
public final class UpdateInstanceRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.redis.v1.UpdateInstanceRequest)
UpdateInstanceRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateInstanceRequest.newBuilder() to construct.
private UpdateInstanceRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateInstanceRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateInstanceRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.redis.v1.CloudRedisServiceV1Proto
.internal_static_google_cloud_redis_v1_UpdateInstanceRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.redis.v1.CloudRedisServiceV1Proto
.internal_static_google_cloud_redis_v1_UpdateInstanceRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.redis.v1.UpdateInstanceRequest.class,
com.google.cloud.redis.v1.UpdateInstanceRequest.Builder.class);
}
private int bitField0_;
public static final int UPDATE_MASK_FIELD_NUMBER = 1;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field. The elements of the repeated paths field may only include these
* fields from [Instance][google.cloud.redis.v1.Instance]:
*
* * `displayName`
* * `labels`
* * `memorySizeGb`
* * `redisConfig`
* * `replica_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field. The elements of the repeated paths field may only include these
* fields from [Instance][google.cloud.redis.v1.Instance]:
*
* * `displayName`
* * `labels`
* * `memorySizeGb`
* * `redisConfig`
* * `replica_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field. The elements of the repeated paths field may only include these
* fields from [Instance][google.cloud.redis.v1.Instance]:
*
* * `displayName`
* * `labels`
* * `memorySizeGb`
* * `redisConfig`
* * `replica_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
public static final int INSTANCE_FIELD_NUMBER = 2;
private com.google.cloud.redis.v1.Instance instance_;
/**
*
*
* <pre>
* Required. Update description.
* Only fields specified in update_mask are updated.
* </pre>
*
* <code>.google.cloud.redis.v1.Instance 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. Update description.
* Only fields specified in update_mask are updated.
* </pre>
*
* <code>.google.cloud.redis.v1.Instance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
@java.lang.Override
public com.google.cloud.redis.v1.Instance getInstance() {
return instance_ == null ? com.google.cloud.redis.v1.Instance.getDefaultInstance() : instance_;
}
/**
*
*
* <pre>
* Required. Update description.
* Only fields specified in update_mask are updated.
* </pre>
*
* <code>.google.cloud.redis.v1.Instance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.redis.v1.InstanceOrBuilder getInstanceOrBuilder() {
return instance_ == null ? com.google.cloud.redis.v1.Instance.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, getUpdateMask());
}
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, getUpdateMask());
}
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.redis.v1.UpdateInstanceRequest)) {
return super.equals(obj);
}
com.google.cloud.redis.v1.UpdateInstanceRequest other =
(com.google.cloud.redis.v1.UpdateInstanceRequest) obj;
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask().equals(other.getUpdateMask())) 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 (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().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.redis.v1.UpdateInstanceRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.redis.v1.UpdateInstanceRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.redis.v1.UpdateInstanceRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.redis.v1.UpdateInstanceRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.redis.v1.UpdateInstanceRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.redis.v1.UpdateInstanceRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.redis.v1.UpdateInstanceRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.redis.v1.UpdateInstanceRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.redis.v1.UpdateInstanceRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.redis.v1.UpdateInstanceRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.redis.v1.UpdateInstanceRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.redis.v1.UpdateInstanceRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.redis.v1.UpdateInstanceRequest 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
* [UpdateInstance][google.cloud.redis.v1.CloudRedis.UpdateInstance].
* </pre>
*
* Protobuf type {@code google.cloud.redis.v1.UpdateInstanceRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.redis.v1.UpdateInstanceRequest)
com.google.cloud.redis.v1.UpdateInstanceRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.redis.v1.CloudRedisServiceV1Proto
.internal_static_google_cloud_redis_v1_UpdateInstanceRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.redis.v1.CloudRedisServiceV1Proto
.internal_static_google_cloud_redis_v1_UpdateInstanceRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.redis.v1.UpdateInstanceRequest.class,
com.google.cloud.redis.v1.UpdateInstanceRequest.Builder.class);
}
// Construct using com.google.cloud.redis.v1.UpdateInstanceRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getUpdateMaskFieldBuilder();
getInstanceFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = 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.redis.v1.CloudRedisServiceV1Proto
.internal_static_google_cloud_redis_v1_UpdateInstanceRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.redis.v1.UpdateInstanceRequest getDefaultInstanceForType() {
return com.google.cloud.redis.v1.UpdateInstanceRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.redis.v1.UpdateInstanceRequest build() {
com.google.cloud.redis.v1.UpdateInstanceRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.redis.v1.UpdateInstanceRequest buildPartial() {
com.google.cloud.redis.v1.UpdateInstanceRequest result =
new com.google.cloud.redis.v1.UpdateInstanceRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.redis.v1.UpdateInstanceRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.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.redis.v1.UpdateInstanceRequest) {
return mergeFrom((com.google.cloud.redis.v1.UpdateInstanceRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.redis.v1.UpdateInstanceRequest other) {
if (other == com.google.cloud.redis.v1.UpdateInstanceRequest.getDefaultInstance())
return this;
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
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(getUpdateMaskFieldBuilder().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.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
updateMaskBuilder_;
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field. The elements of the repeated paths field may only include these
* fields from [Instance][google.cloud.redis.v1.Instance]:
*
* * `displayName`
* * `labels`
* * `memorySizeGb`
* * `redisConfig`
* * `replica_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field. The elements of the repeated paths field may only include these
* fields from [Instance][google.cloud.redis.v1.Instance]:
*
* * `displayName`
* * `labels`
* * `memorySizeGb`
* * `redisConfig`
* * `replica_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field. The elements of the repeated paths field may only include these
* fields from [Instance][google.cloud.redis.v1.Instance]:
*
* * `displayName`
* * `labels`
* * `memorySizeGb`
* * `redisConfig`
* * `replica_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
} else {
updateMaskBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field. The elements of the repeated paths field may only include these
* fields from [Instance][google.cloud.redis.v1.Instance]:
*
* * `displayName`
* * `labels`
* * `memorySizeGb`
* * `redisConfig`
* * `replica_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field. The elements of the repeated paths field may only include these
* fields from [Instance][google.cloud.redis.v1.Instance]:
*
* * `displayName`
* * `labels`
* * `memorySizeGb`
* * `redisConfig`
* * `replica_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& updateMask_ != null
&& updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) {
getUpdateMaskBuilder().mergeFrom(value);
} else {
updateMask_ = value;
}
} else {
updateMaskBuilder_.mergeFrom(value);
}
if (updateMask_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field. The elements of the repeated paths field may only include these
* fields from [Instance][google.cloud.redis.v1.Instance]:
*
* * `displayName`
* * `labels`
* * `memorySizeGb`
* * `redisConfig`
* * `replica_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000001);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field. The elements of the repeated paths field may only include these
* fields from [Instance][google.cloud.redis.v1.Instance]:
*
* * `displayName`
* * `labels`
* * `memorySizeGb`
* * `redisConfig`
* * `replica_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field. The elements of the repeated paths field may only include these
* fields from [Instance][google.cloud.redis.v1.Instance]:
*
* * `displayName`
* * `labels`
* * `memorySizeGb`
* * `redisConfig`
* * `replica_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Required. Mask of fields to update. At least one path must be supplied in
* this field. The elements of the repeated paths field may only include these
* fields from [Instance][google.cloud.redis.v1.Instance]:
*
* * `displayName`
* * `labels`
* * `memorySizeGb`
* * `redisConfig`
* * `replica_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
private com.google.cloud.redis.v1.Instance instance_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.redis.v1.Instance,
com.google.cloud.redis.v1.Instance.Builder,
com.google.cloud.redis.v1.InstanceOrBuilder>
instanceBuilder_;
/**
*
*
* <pre>
* Required. Update description.
* Only fields specified in update_mask are updated.
* </pre>
*
* <code>.google.cloud.redis.v1.Instance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the instance field is set.
*/
public boolean hasInstance() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. Update description.
* Only fields specified in update_mask are updated.
* </pre>
*
* <code>.google.cloud.redis.v1.Instance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
public com.google.cloud.redis.v1.Instance getInstance() {
if (instanceBuilder_ == null) {
return instance_ == null
? com.google.cloud.redis.v1.Instance.getDefaultInstance()
: instance_;
} else {
return instanceBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Update description.
* Only fields specified in update_mask are updated.
* </pre>
*
* <code>.google.cloud.redis.v1.Instance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(com.google.cloud.redis.v1.Instance value) {
if (instanceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
instance_ = value;
} else {
instanceBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Update description.
* Only fields specified in update_mask are updated.
* </pre>
*
* <code>.google.cloud.redis.v1.Instance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(com.google.cloud.redis.v1.Instance.Builder builderForValue) {
if (instanceBuilder_ == null) {
instance_ = builderForValue.build();
} else {
instanceBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Update description.
* Only fields specified in update_mask are updated.
* </pre>
*
* <code>.google.cloud.redis.v1.Instance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeInstance(com.google.cloud.redis.v1.Instance value) {
if (instanceBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& instance_ != null
&& instance_ != com.google.cloud.redis.v1.Instance.getDefaultInstance()) {
getInstanceBuilder().mergeFrom(value);
} else {
instance_ = value;
}
} else {
instanceBuilder_.mergeFrom(value);
}
if (instance_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Update description.
* Only fields specified in update_mask are updated.
* </pre>
*
* <code>.google.cloud.redis.v1.Instance 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. Update description.
* Only fields specified in update_mask are updated.
* </pre>
*
* <code>.google.cloud.redis.v1.Instance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.redis.v1.Instance.Builder getInstanceBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getInstanceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Update description.
* Only fields specified in update_mask are updated.
* </pre>
*
* <code>.google.cloud.redis.v1.Instance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.redis.v1.InstanceOrBuilder getInstanceOrBuilder() {
if (instanceBuilder_ != null) {
return instanceBuilder_.getMessageOrBuilder();
} else {
return instance_ == null
? com.google.cloud.redis.v1.Instance.getDefaultInstance()
: instance_;
}
}
/**
*
*
* <pre>
* Required. Update description.
* Only fields specified in update_mask are updated.
* </pre>
*
* <code>.google.cloud.redis.v1.Instance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.redis.v1.Instance,
com.google.cloud.redis.v1.Instance.Builder,
com.google.cloud.redis.v1.InstanceOrBuilder>
getInstanceFieldBuilder() {
if (instanceBuilder_ == null) {
instanceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.redis.v1.Instance,
com.google.cloud.redis.v1.Instance.Builder,
com.google.cloud.redis.v1.InstanceOrBuilder>(
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.redis.v1.UpdateInstanceRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.redis.v1.UpdateInstanceRequest)
private static final com.google.cloud.redis.v1.UpdateInstanceRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.redis.v1.UpdateInstanceRequest();
}
public static com.google.cloud.redis.v1.UpdateInstanceRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateInstanceRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateInstanceRequest>() {
@java.lang.Override
public UpdateInstanceRequest 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<UpdateInstanceRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateInstanceRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.redis.v1.UpdateInstanceRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,402 | java-apigee-registry/proto-google-cloud-apigee-registry-v1/src/main/java/com/google/cloud/apigeeregistry/v1/ListApiSpecsResponse.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/apigeeregistry/v1/registry_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.apigeeregistry.v1;
/**
*
*
* <pre>
* Response message for ListApiSpecs.
* </pre>
*
* Protobuf type {@code google.cloud.apigeeregistry.v1.ListApiSpecsResponse}
*/
public final class ListApiSpecsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.apigeeregistry.v1.ListApiSpecsResponse)
ListApiSpecsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListApiSpecsResponse.newBuilder() to construct.
private ListApiSpecsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListApiSpecsResponse() {
apiSpecs_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListApiSpecsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.apigeeregistry.v1.RegistryServiceProto
.internal_static_google_cloud_apigeeregistry_v1_ListApiSpecsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.apigeeregistry.v1.RegistryServiceProto
.internal_static_google_cloud_apigeeregistry_v1_ListApiSpecsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse.class,
com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse.Builder.class);
}
public static final int API_SPECS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.apigeeregistry.v1.ApiSpec> apiSpecs_;
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.apigeeregistry.v1.ApiSpec> getApiSpecsList() {
return apiSpecs_;
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.apigeeregistry.v1.ApiSpecOrBuilder>
getApiSpecsOrBuilderList() {
return apiSpecs_;
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
@java.lang.Override
public int getApiSpecsCount() {
return apiSpecs_.size();
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
@java.lang.Override
public com.google.cloud.apigeeregistry.v1.ApiSpec getApiSpecs(int index) {
return apiSpecs_.get(index);
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
@java.lang.Override
public com.google.cloud.apigeeregistry.v1.ApiSpecOrBuilder getApiSpecsOrBuilder(int index) {
return apiSpecs_.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 < apiSpecs_.size(); i++) {
output.writeMessage(1, apiSpecs_.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 < apiSpecs_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, apiSpecs_.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.apigeeregistry.v1.ListApiSpecsResponse)) {
return super.equals(obj);
}
com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse other =
(com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse) obj;
if (!getApiSpecsList().equals(other.getApiSpecsList())) 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 (getApiSpecsCount() > 0) {
hash = (37 * hash) + API_SPECS_FIELD_NUMBER;
hash = (53 * hash) + getApiSpecsList().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.apigeeregistry.v1.ListApiSpecsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse 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.apigeeregistry.v1.ListApiSpecsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse 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.apigeeregistry.v1.ListApiSpecsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse 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.apigeeregistry.v1.ListApiSpecsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse 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.apigeeregistry.v1.ListApiSpecsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse 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.apigeeregistry.v1.ListApiSpecsResponse 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 ListApiSpecs.
* </pre>
*
* Protobuf type {@code google.cloud.apigeeregistry.v1.ListApiSpecsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.apigeeregistry.v1.ListApiSpecsResponse)
com.google.cloud.apigeeregistry.v1.ListApiSpecsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.apigeeregistry.v1.RegistryServiceProto
.internal_static_google_cloud_apigeeregistry_v1_ListApiSpecsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.apigeeregistry.v1.RegistryServiceProto
.internal_static_google_cloud_apigeeregistry_v1_ListApiSpecsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse.class,
com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse.Builder.class);
}
// Construct using com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (apiSpecsBuilder_ == null) {
apiSpecs_ = java.util.Collections.emptyList();
} else {
apiSpecs_ = null;
apiSpecsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.apigeeregistry.v1.RegistryServiceProto
.internal_static_google_cloud_apigeeregistry_v1_ListApiSpecsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse getDefaultInstanceForType() {
return com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse build() {
com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse buildPartial() {
com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse result =
new com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse result) {
if (apiSpecsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
apiSpecs_ = java.util.Collections.unmodifiableList(apiSpecs_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.apiSpecs_ = apiSpecs_;
} else {
result.apiSpecs_ = apiSpecsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse 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.apigeeregistry.v1.ListApiSpecsResponse) {
return mergeFrom((com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse other) {
if (other == com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse.getDefaultInstance())
return this;
if (apiSpecsBuilder_ == null) {
if (!other.apiSpecs_.isEmpty()) {
if (apiSpecs_.isEmpty()) {
apiSpecs_ = other.apiSpecs_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureApiSpecsIsMutable();
apiSpecs_.addAll(other.apiSpecs_);
}
onChanged();
}
} else {
if (!other.apiSpecs_.isEmpty()) {
if (apiSpecsBuilder_.isEmpty()) {
apiSpecsBuilder_.dispose();
apiSpecsBuilder_ = null;
apiSpecs_ = other.apiSpecs_;
bitField0_ = (bitField0_ & ~0x00000001);
apiSpecsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getApiSpecsFieldBuilder()
: null;
} else {
apiSpecsBuilder_.addAllMessages(other.apiSpecs_);
}
}
}
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.apigeeregistry.v1.ApiSpec m =
input.readMessage(
com.google.cloud.apigeeregistry.v1.ApiSpec.parser(), extensionRegistry);
if (apiSpecsBuilder_ == null) {
ensureApiSpecsIsMutable();
apiSpecs_.add(m);
} else {
apiSpecsBuilder_.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.apigeeregistry.v1.ApiSpec> apiSpecs_ =
java.util.Collections.emptyList();
private void ensureApiSpecsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
apiSpecs_ = new java.util.ArrayList<com.google.cloud.apigeeregistry.v1.ApiSpec>(apiSpecs_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.apigeeregistry.v1.ApiSpec,
com.google.cloud.apigeeregistry.v1.ApiSpec.Builder,
com.google.cloud.apigeeregistry.v1.ApiSpecOrBuilder>
apiSpecsBuilder_;
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public java.util.List<com.google.cloud.apigeeregistry.v1.ApiSpec> getApiSpecsList() {
if (apiSpecsBuilder_ == null) {
return java.util.Collections.unmodifiableList(apiSpecs_);
} else {
return apiSpecsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public int getApiSpecsCount() {
if (apiSpecsBuilder_ == null) {
return apiSpecs_.size();
} else {
return apiSpecsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public com.google.cloud.apigeeregistry.v1.ApiSpec getApiSpecs(int index) {
if (apiSpecsBuilder_ == null) {
return apiSpecs_.get(index);
} else {
return apiSpecsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public Builder setApiSpecs(int index, com.google.cloud.apigeeregistry.v1.ApiSpec value) {
if (apiSpecsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureApiSpecsIsMutable();
apiSpecs_.set(index, value);
onChanged();
} else {
apiSpecsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public Builder setApiSpecs(
int index, com.google.cloud.apigeeregistry.v1.ApiSpec.Builder builderForValue) {
if (apiSpecsBuilder_ == null) {
ensureApiSpecsIsMutable();
apiSpecs_.set(index, builderForValue.build());
onChanged();
} else {
apiSpecsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public Builder addApiSpecs(com.google.cloud.apigeeregistry.v1.ApiSpec value) {
if (apiSpecsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureApiSpecsIsMutable();
apiSpecs_.add(value);
onChanged();
} else {
apiSpecsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public Builder addApiSpecs(int index, com.google.cloud.apigeeregistry.v1.ApiSpec value) {
if (apiSpecsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureApiSpecsIsMutable();
apiSpecs_.add(index, value);
onChanged();
} else {
apiSpecsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public Builder addApiSpecs(com.google.cloud.apigeeregistry.v1.ApiSpec.Builder builderForValue) {
if (apiSpecsBuilder_ == null) {
ensureApiSpecsIsMutable();
apiSpecs_.add(builderForValue.build());
onChanged();
} else {
apiSpecsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public Builder addApiSpecs(
int index, com.google.cloud.apigeeregistry.v1.ApiSpec.Builder builderForValue) {
if (apiSpecsBuilder_ == null) {
ensureApiSpecsIsMutable();
apiSpecs_.add(index, builderForValue.build());
onChanged();
} else {
apiSpecsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public Builder addAllApiSpecs(
java.lang.Iterable<? extends com.google.cloud.apigeeregistry.v1.ApiSpec> values) {
if (apiSpecsBuilder_ == null) {
ensureApiSpecsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, apiSpecs_);
onChanged();
} else {
apiSpecsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public Builder clearApiSpecs() {
if (apiSpecsBuilder_ == null) {
apiSpecs_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
apiSpecsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public Builder removeApiSpecs(int index) {
if (apiSpecsBuilder_ == null) {
ensureApiSpecsIsMutable();
apiSpecs_.remove(index);
onChanged();
} else {
apiSpecsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public com.google.cloud.apigeeregistry.v1.ApiSpec.Builder getApiSpecsBuilder(int index) {
return getApiSpecsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public com.google.cloud.apigeeregistry.v1.ApiSpecOrBuilder getApiSpecsOrBuilder(int index) {
if (apiSpecsBuilder_ == null) {
return apiSpecs_.get(index);
} else {
return apiSpecsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public java.util.List<? extends com.google.cloud.apigeeregistry.v1.ApiSpecOrBuilder>
getApiSpecsOrBuilderList() {
if (apiSpecsBuilder_ != null) {
return apiSpecsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(apiSpecs_);
}
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public com.google.cloud.apigeeregistry.v1.ApiSpec.Builder addApiSpecsBuilder() {
return getApiSpecsFieldBuilder()
.addBuilder(com.google.cloud.apigeeregistry.v1.ApiSpec.getDefaultInstance());
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public com.google.cloud.apigeeregistry.v1.ApiSpec.Builder addApiSpecsBuilder(int index) {
return getApiSpecsFieldBuilder()
.addBuilder(index, com.google.cloud.apigeeregistry.v1.ApiSpec.getDefaultInstance());
}
/**
*
*
* <pre>
* The specs from the specified publisher.
* </pre>
*
* <code>repeated .google.cloud.apigeeregistry.v1.ApiSpec api_specs = 1;</code>
*/
public java.util.List<com.google.cloud.apigeeregistry.v1.ApiSpec.Builder>
getApiSpecsBuilderList() {
return getApiSpecsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.apigeeregistry.v1.ApiSpec,
com.google.cloud.apigeeregistry.v1.ApiSpec.Builder,
com.google.cloud.apigeeregistry.v1.ApiSpecOrBuilder>
getApiSpecsFieldBuilder() {
if (apiSpecsBuilder_ == null) {
apiSpecsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.apigeeregistry.v1.ApiSpec,
com.google.cloud.apigeeregistry.v1.ApiSpec.Builder,
com.google.cloud.apigeeregistry.v1.ApiSpecOrBuilder>(
apiSpecs_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
apiSpecs_ = null;
}
return apiSpecsBuilder_;
}
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.apigeeregistry.v1.ListApiSpecsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.apigeeregistry.v1.ListApiSpecsResponse)
private static final com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse();
}
public static com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListApiSpecsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListApiSpecsResponse>() {
@java.lang.Override
public ListApiSpecsResponse 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<ListApiSpecsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListApiSpecsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.apigeeregistry.v1.ListApiSpecsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,509 | java-dataproc/proto-google-cloud-dataproc-v1/src/main/java/com/google/cloud/dataproc/v1/AuxiliaryServicesConfig.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dataproc/v1/clusters.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.dataproc.v1;
/**
*
*
* <pre>
* Auxiliary services configuration for a Cluster.
* </pre>
*
* Protobuf type {@code google.cloud.dataproc.v1.AuxiliaryServicesConfig}
*/
public final class AuxiliaryServicesConfig extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dataproc.v1.AuxiliaryServicesConfig)
AuxiliaryServicesConfigOrBuilder {
private static final long serialVersionUID = 0L;
// Use AuxiliaryServicesConfig.newBuilder() to construct.
private AuxiliaryServicesConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private AuxiliaryServicesConfig() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new AuxiliaryServicesConfig();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dataproc.v1.ClustersProto
.internal_static_google_cloud_dataproc_v1_AuxiliaryServicesConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dataproc.v1.ClustersProto
.internal_static_google_cloud_dataproc_v1_AuxiliaryServicesConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dataproc.v1.AuxiliaryServicesConfig.class,
com.google.cloud.dataproc.v1.AuxiliaryServicesConfig.Builder.class);
}
private int bitField0_;
public static final int METASTORE_CONFIG_FIELD_NUMBER = 1;
private com.google.cloud.dataproc.v1.MetastoreConfig metastoreConfig_;
/**
*
*
* <pre>
* Optional. The Hive Metastore configuration for this workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.MetastoreConfig metastore_config = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the metastoreConfig field is set.
*/
@java.lang.Override
public boolean hasMetastoreConfig() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Optional. The Hive Metastore configuration for this workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.MetastoreConfig metastore_config = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The metastoreConfig.
*/
@java.lang.Override
public com.google.cloud.dataproc.v1.MetastoreConfig getMetastoreConfig() {
return metastoreConfig_ == null
? com.google.cloud.dataproc.v1.MetastoreConfig.getDefaultInstance()
: metastoreConfig_;
}
/**
*
*
* <pre>
* Optional. The Hive Metastore configuration for this workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.MetastoreConfig metastore_config = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
@java.lang.Override
public com.google.cloud.dataproc.v1.MetastoreConfigOrBuilder getMetastoreConfigOrBuilder() {
return metastoreConfig_ == null
? com.google.cloud.dataproc.v1.MetastoreConfig.getDefaultInstance()
: metastoreConfig_;
}
public static final int SPARK_HISTORY_SERVER_CONFIG_FIELD_NUMBER = 2;
private com.google.cloud.dataproc.v1.SparkHistoryServerConfig sparkHistoryServerConfig_;
/**
*
*
* <pre>
* Optional. The Spark History Server configuration for the workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.SparkHistoryServerConfig spark_history_server_config = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the sparkHistoryServerConfig field is set.
*/
@java.lang.Override
public boolean hasSparkHistoryServerConfig() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Optional. The Spark History Server configuration for the workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.SparkHistoryServerConfig spark_history_server_config = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The sparkHistoryServerConfig.
*/
@java.lang.Override
public com.google.cloud.dataproc.v1.SparkHistoryServerConfig getSparkHistoryServerConfig() {
return sparkHistoryServerConfig_ == null
? com.google.cloud.dataproc.v1.SparkHistoryServerConfig.getDefaultInstance()
: sparkHistoryServerConfig_;
}
/**
*
*
* <pre>
* Optional. The Spark History Server configuration for the workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.SparkHistoryServerConfig spark_history_server_config = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
@java.lang.Override
public com.google.cloud.dataproc.v1.SparkHistoryServerConfigOrBuilder
getSparkHistoryServerConfigOrBuilder() {
return sparkHistoryServerConfig_ == null
? com.google.cloud.dataproc.v1.SparkHistoryServerConfig.getDefaultInstance()
: sparkHistoryServerConfig_;
}
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, getMetastoreConfig());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getSparkHistoryServerConfig());
}
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, getMetastoreConfig());
}
if (((bitField0_ & 0x00000002) != 0)) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
2, getSparkHistoryServerConfig());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.dataproc.v1.AuxiliaryServicesConfig)) {
return super.equals(obj);
}
com.google.cloud.dataproc.v1.AuxiliaryServicesConfig other =
(com.google.cloud.dataproc.v1.AuxiliaryServicesConfig) obj;
if (hasMetastoreConfig() != other.hasMetastoreConfig()) return false;
if (hasMetastoreConfig()) {
if (!getMetastoreConfig().equals(other.getMetastoreConfig())) return false;
}
if (hasSparkHistoryServerConfig() != other.hasSparkHistoryServerConfig()) return false;
if (hasSparkHistoryServerConfig()) {
if (!getSparkHistoryServerConfig().equals(other.getSparkHistoryServerConfig())) 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 (hasMetastoreConfig()) {
hash = (37 * hash) + METASTORE_CONFIG_FIELD_NUMBER;
hash = (53 * hash) + getMetastoreConfig().hashCode();
}
if (hasSparkHistoryServerConfig()) {
hash = (37 * hash) + SPARK_HISTORY_SERVER_CONFIG_FIELD_NUMBER;
hash = (53 * hash) + getSparkHistoryServerConfig().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dataproc.v1.AuxiliaryServicesConfig parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataproc.v1.AuxiliaryServicesConfig parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dataproc.v1.AuxiliaryServicesConfig parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataproc.v1.AuxiliaryServicesConfig parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dataproc.v1.AuxiliaryServicesConfig parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataproc.v1.AuxiliaryServicesConfig parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dataproc.v1.AuxiliaryServicesConfig parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dataproc.v1.AuxiliaryServicesConfig parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dataproc.v1.AuxiliaryServicesConfig parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dataproc.v1.AuxiliaryServicesConfig parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dataproc.v1.AuxiliaryServicesConfig parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dataproc.v1.AuxiliaryServicesConfig parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.dataproc.v1.AuxiliaryServicesConfig 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>
* Auxiliary services configuration for a Cluster.
* </pre>
*
* Protobuf type {@code google.cloud.dataproc.v1.AuxiliaryServicesConfig}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dataproc.v1.AuxiliaryServicesConfig)
com.google.cloud.dataproc.v1.AuxiliaryServicesConfigOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dataproc.v1.ClustersProto
.internal_static_google_cloud_dataproc_v1_AuxiliaryServicesConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dataproc.v1.ClustersProto
.internal_static_google_cloud_dataproc_v1_AuxiliaryServicesConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dataproc.v1.AuxiliaryServicesConfig.class,
com.google.cloud.dataproc.v1.AuxiliaryServicesConfig.Builder.class);
}
// Construct using com.google.cloud.dataproc.v1.AuxiliaryServicesConfig.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getMetastoreConfigFieldBuilder();
getSparkHistoryServerConfigFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
metastoreConfig_ = null;
if (metastoreConfigBuilder_ != null) {
metastoreConfigBuilder_.dispose();
metastoreConfigBuilder_ = null;
}
sparkHistoryServerConfig_ = null;
if (sparkHistoryServerConfigBuilder_ != null) {
sparkHistoryServerConfigBuilder_.dispose();
sparkHistoryServerConfigBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dataproc.v1.ClustersProto
.internal_static_google_cloud_dataproc_v1_AuxiliaryServicesConfig_descriptor;
}
@java.lang.Override
public com.google.cloud.dataproc.v1.AuxiliaryServicesConfig getDefaultInstanceForType() {
return com.google.cloud.dataproc.v1.AuxiliaryServicesConfig.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dataproc.v1.AuxiliaryServicesConfig build() {
com.google.cloud.dataproc.v1.AuxiliaryServicesConfig result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dataproc.v1.AuxiliaryServicesConfig buildPartial() {
com.google.cloud.dataproc.v1.AuxiliaryServicesConfig result =
new com.google.cloud.dataproc.v1.AuxiliaryServicesConfig(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.dataproc.v1.AuxiliaryServicesConfig result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.metastoreConfig_ =
metastoreConfigBuilder_ == null ? metastoreConfig_ : metastoreConfigBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.sparkHistoryServerConfig_ =
sparkHistoryServerConfigBuilder_ == null
? sparkHistoryServerConfig_
: sparkHistoryServerConfigBuilder_.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.dataproc.v1.AuxiliaryServicesConfig) {
return mergeFrom((com.google.cloud.dataproc.v1.AuxiliaryServicesConfig) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dataproc.v1.AuxiliaryServicesConfig other) {
if (other == com.google.cloud.dataproc.v1.AuxiliaryServicesConfig.getDefaultInstance())
return this;
if (other.hasMetastoreConfig()) {
mergeMetastoreConfig(other.getMetastoreConfig());
}
if (other.hasSparkHistoryServerConfig()) {
mergeSparkHistoryServerConfig(other.getSparkHistoryServerConfig());
}
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(getMetastoreConfigFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(
getSparkHistoryServerConfigFieldBuilder().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.dataproc.v1.MetastoreConfig metastoreConfig_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dataproc.v1.MetastoreConfig,
com.google.cloud.dataproc.v1.MetastoreConfig.Builder,
com.google.cloud.dataproc.v1.MetastoreConfigOrBuilder>
metastoreConfigBuilder_;
/**
*
*
* <pre>
* Optional. The Hive Metastore configuration for this workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.MetastoreConfig metastore_config = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the metastoreConfig field is set.
*/
public boolean hasMetastoreConfig() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Optional. The Hive Metastore configuration for this workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.MetastoreConfig metastore_config = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The metastoreConfig.
*/
public com.google.cloud.dataproc.v1.MetastoreConfig getMetastoreConfig() {
if (metastoreConfigBuilder_ == null) {
return metastoreConfig_ == null
? com.google.cloud.dataproc.v1.MetastoreConfig.getDefaultInstance()
: metastoreConfig_;
} else {
return metastoreConfigBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Optional. The Hive Metastore configuration for this workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.MetastoreConfig metastore_config = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setMetastoreConfig(com.google.cloud.dataproc.v1.MetastoreConfig value) {
if (metastoreConfigBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
metastoreConfig_ = value;
} else {
metastoreConfigBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The Hive Metastore configuration for this workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.MetastoreConfig metastore_config = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setMetastoreConfig(
com.google.cloud.dataproc.v1.MetastoreConfig.Builder builderForValue) {
if (metastoreConfigBuilder_ == null) {
metastoreConfig_ = builderForValue.build();
} else {
metastoreConfigBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The Hive Metastore configuration for this workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.MetastoreConfig metastore_config = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder mergeMetastoreConfig(com.google.cloud.dataproc.v1.MetastoreConfig value) {
if (metastoreConfigBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& metastoreConfig_ != null
&& metastoreConfig_
!= com.google.cloud.dataproc.v1.MetastoreConfig.getDefaultInstance()) {
getMetastoreConfigBuilder().mergeFrom(value);
} else {
metastoreConfig_ = value;
}
} else {
metastoreConfigBuilder_.mergeFrom(value);
}
if (metastoreConfig_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Optional. The Hive Metastore configuration for this workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.MetastoreConfig metastore_config = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder clearMetastoreConfig() {
bitField0_ = (bitField0_ & ~0x00000001);
metastoreConfig_ = null;
if (metastoreConfigBuilder_ != null) {
metastoreConfigBuilder_.dispose();
metastoreConfigBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The Hive Metastore configuration for this workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.MetastoreConfig metastore_config = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.cloud.dataproc.v1.MetastoreConfig.Builder getMetastoreConfigBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getMetastoreConfigFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Optional. The Hive Metastore configuration for this workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.MetastoreConfig metastore_config = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.cloud.dataproc.v1.MetastoreConfigOrBuilder getMetastoreConfigOrBuilder() {
if (metastoreConfigBuilder_ != null) {
return metastoreConfigBuilder_.getMessageOrBuilder();
} else {
return metastoreConfig_ == null
? com.google.cloud.dataproc.v1.MetastoreConfig.getDefaultInstance()
: metastoreConfig_;
}
}
/**
*
*
* <pre>
* Optional. The Hive Metastore configuration for this workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.MetastoreConfig metastore_config = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dataproc.v1.MetastoreConfig,
com.google.cloud.dataproc.v1.MetastoreConfig.Builder,
com.google.cloud.dataproc.v1.MetastoreConfigOrBuilder>
getMetastoreConfigFieldBuilder() {
if (metastoreConfigBuilder_ == null) {
metastoreConfigBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dataproc.v1.MetastoreConfig,
com.google.cloud.dataproc.v1.MetastoreConfig.Builder,
com.google.cloud.dataproc.v1.MetastoreConfigOrBuilder>(
getMetastoreConfig(), getParentForChildren(), isClean());
metastoreConfig_ = null;
}
return metastoreConfigBuilder_;
}
private com.google.cloud.dataproc.v1.SparkHistoryServerConfig sparkHistoryServerConfig_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dataproc.v1.SparkHistoryServerConfig,
com.google.cloud.dataproc.v1.SparkHistoryServerConfig.Builder,
com.google.cloud.dataproc.v1.SparkHistoryServerConfigOrBuilder>
sparkHistoryServerConfigBuilder_;
/**
*
*
* <pre>
* Optional. The Spark History Server configuration for the workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.SparkHistoryServerConfig spark_history_server_config = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the sparkHistoryServerConfig field is set.
*/
public boolean hasSparkHistoryServerConfig() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Optional. The Spark History Server configuration for the workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.SparkHistoryServerConfig spark_history_server_config = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The sparkHistoryServerConfig.
*/
public com.google.cloud.dataproc.v1.SparkHistoryServerConfig getSparkHistoryServerConfig() {
if (sparkHistoryServerConfigBuilder_ == null) {
return sparkHistoryServerConfig_ == null
? com.google.cloud.dataproc.v1.SparkHistoryServerConfig.getDefaultInstance()
: sparkHistoryServerConfig_;
} else {
return sparkHistoryServerConfigBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Optional. The Spark History Server configuration for the workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.SparkHistoryServerConfig spark_history_server_config = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setSparkHistoryServerConfig(
com.google.cloud.dataproc.v1.SparkHistoryServerConfig value) {
if (sparkHistoryServerConfigBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
sparkHistoryServerConfig_ = value;
} else {
sparkHistoryServerConfigBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The Spark History Server configuration for the workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.SparkHistoryServerConfig spark_history_server_config = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setSparkHistoryServerConfig(
com.google.cloud.dataproc.v1.SparkHistoryServerConfig.Builder builderForValue) {
if (sparkHistoryServerConfigBuilder_ == null) {
sparkHistoryServerConfig_ = builderForValue.build();
} else {
sparkHistoryServerConfigBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The Spark History Server configuration for the workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.SparkHistoryServerConfig spark_history_server_config = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder mergeSparkHistoryServerConfig(
com.google.cloud.dataproc.v1.SparkHistoryServerConfig value) {
if (sparkHistoryServerConfigBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& sparkHistoryServerConfig_ != null
&& sparkHistoryServerConfig_
!= com.google.cloud.dataproc.v1.SparkHistoryServerConfig.getDefaultInstance()) {
getSparkHistoryServerConfigBuilder().mergeFrom(value);
} else {
sparkHistoryServerConfig_ = value;
}
} else {
sparkHistoryServerConfigBuilder_.mergeFrom(value);
}
if (sparkHistoryServerConfig_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Optional. The Spark History Server configuration for the workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.SparkHistoryServerConfig spark_history_server_config = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder clearSparkHistoryServerConfig() {
bitField0_ = (bitField0_ & ~0x00000002);
sparkHistoryServerConfig_ = null;
if (sparkHistoryServerConfigBuilder_ != null) {
sparkHistoryServerConfigBuilder_.dispose();
sparkHistoryServerConfigBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The Spark History Server configuration for the workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.SparkHistoryServerConfig spark_history_server_config = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.cloud.dataproc.v1.SparkHistoryServerConfig.Builder
getSparkHistoryServerConfigBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getSparkHistoryServerConfigFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Optional. The Spark History Server configuration for the workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.SparkHistoryServerConfig spark_history_server_config = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.cloud.dataproc.v1.SparkHistoryServerConfigOrBuilder
getSparkHistoryServerConfigOrBuilder() {
if (sparkHistoryServerConfigBuilder_ != null) {
return sparkHistoryServerConfigBuilder_.getMessageOrBuilder();
} else {
return sparkHistoryServerConfig_ == null
? com.google.cloud.dataproc.v1.SparkHistoryServerConfig.getDefaultInstance()
: sparkHistoryServerConfig_;
}
}
/**
*
*
* <pre>
* Optional. The Spark History Server configuration for the workload.
* </pre>
*
* <code>
* .google.cloud.dataproc.v1.SparkHistoryServerConfig spark_history_server_config = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dataproc.v1.SparkHistoryServerConfig,
com.google.cloud.dataproc.v1.SparkHistoryServerConfig.Builder,
com.google.cloud.dataproc.v1.SparkHistoryServerConfigOrBuilder>
getSparkHistoryServerConfigFieldBuilder() {
if (sparkHistoryServerConfigBuilder_ == null) {
sparkHistoryServerConfigBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dataproc.v1.SparkHistoryServerConfig,
com.google.cloud.dataproc.v1.SparkHistoryServerConfig.Builder,
com.google.cloud.dataproc.v1.SparkHistoryServerConfigOrBuilder>(
getSparkHistoryServerConfig(), getParentForChildren(), isClean());
sparkHistoryServerConfig_ = null;
}
return sparkHistoryServerConfigBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.dataproc.v1.AuxiliaryServicesConfig)
}
// @@protoc_insertion_point(class_scope:google.cloud.dataproc.v1.AuxiliaryServicesConfig)
private static final com.google.cloud.dataproc.v1.AuxiliaryServicesConfig DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dataproc.v1.AuxiliaryServicesConfig();
}
public static com.google.cloud.dataproc.v1.AuxiliaryServicesConfig getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<AuxiliaryServicesConfig> PARSER =
new com.google.protobuf.AbstractParser<AuxiliaryServicesConfig>() {
@java.lang.Override
public AuxiliaryServicesConfig 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<AuxiliaryServicesConfig> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<AuxiliaryServicesConfig> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dataproc.v1.AuxiliaryServicesConfig getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,401 | java-assured-workloads/proto-google-cloud-assured-workloads-v1/src/main/java/com/google/cloud/assuredworkloads/v1/ListWorkloadsResponse.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/assuredworkloads/v1/assuredworkloads.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.assuredworkloads.v1;
/**
*
*
* <pre>
* Response of ListWorkloads endpoint.
* </pre>
*
* Protobuf type {@code google.cloud.assuredworkloads.v1.ListWorkloadsResponse}
*/
public final class ListWorkloadsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.assuredworkloads.v1.ListWorkloadsResponse)
ListWorkloadsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListWorkloadsResponse.newBuilder() to construct.
private ListWorkloadsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListWorkloadsResponse() {
workloads_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListWorkloadsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.assuredworkloads.v1.AssuredworkloadsProto
.internal_static_google_cloud_assuredworkloads_v1_ListWorkloadsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.assuredworkloads.v1.AssuredworkloadsProto
.internal_static_google_cloud_assuredworkloads_v1_ListWorkloadsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse.class,
com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse.Builder.class);
}
public static final int WORKLOADS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.assuredworkloads.v1.Workload> workloads_;
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.assuredworkloads.v1.Workload> getWorkloadsList() {
return workloads_;
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.assuredworkloads.v1.WorkloadOrBuilder>
getWorkloadsOrBuilderList() {
return workloads_;
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
@java.lang.Override
public int getWorkloadsCount() {
return workloads_.size();
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
@java.lang.Override
public com.google.cloud.assuredworkloads.v1.Workload getWorkloads(int index) {
return workloads_.get(index);
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
@java.lang.Override
public com.google.cloud.assuredworkloads.v1.WorkloadOrBuilder getWorkloadsOrBuilder(int index) {
return workloads_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* The next page token. Return empty if reached the last page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* The next page token. Return empty if reached the last page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < workloads_.size(); i++) {
output.writeMessage(1, workloads_.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 < workloads_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, workloads_.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.assuredworkloads.v1.ListWorkloadsResponse)) {
return super.equals(obj);
}
com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse other =
(com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse) obj;
if (!getWorkloadsList().equals(other.getWorkloadsList())) 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 (getWorkloadsCount() > 0) {
hash = (37 * hash) + WORKLOADS_FIELD_NUMBER;
hash = (53 * hash) + getWorkloadsList().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.assuredworkloads.v1.ListWorkloadsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse 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.assuredworkloads.v1.ListWorkloadsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse 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.assuredworkloads.v1.ListWorkloadsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse 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.assuredworkloads.v1.ListWorkloadsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse 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.assuredworkloads.v1.ListWorkloadsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse 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.assuredworkloads.v1.ListWorkloadsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response of ListWorkloads endpoint.
* </pre>
*
* Protobuf type {@code google.cloud.assuredworkloads.v1.ListWorkloadsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.assuredworkloads.v1.ListWorkloadsResponse)
com.google.cloud.assuredworkloads.v1.ListWorkloadsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.assuredworkloads.v1.AssuredworkloadsProto
.internal_static_google_cloud_assuredworkloads_v1_ListWorkloadsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.assuredworkloads.v1.AssuredworkloadsProto
.internal_static_google_cloud_assuredworkloads_v1_ListWorkloadsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse.class,
com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse.Builder.class);
}
// Construct using com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (workloadsBuilder_ == null) {
workloads_ = java.util.Collections.emptyList();
} else {
workloads_ = null;
workloadsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.assuredworkloads.v1.AssuredworkloadsProto
.internal_static_google_cloud_assuredworkloads_v1_ListWorkloadsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse getDefaultInstanceForType() {
return com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse build() {
com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse buildPartial() {
com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse result =
new com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse result) {
if (workloadsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
workloads_ = java.util.Collections.unmodifiableList(workloads_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.workloads_ = workloads_;
} else {
result.workloads_ = workloadsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse 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.assuredworkloads.v1.ListWorkloadsResponse) {
return mergeFrom((com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse other) {
if (other == com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse.getDefaultInstance())
return this;
if (workloadsBuilder_ == null) {
if (!other.workloads_.isEmpty()) {
if (workloads_.isEmpty()) {
workloads_ = other.workloads_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureWorkloadsIsMutable();
workloads_.addAll(other.workloads_);
}
onChanged();
}
} else {
if (!other.workloads_.isEmpty()) {
if (workloadsBuilder_.isEmpty()) {
workloadsBuilder_.dispose();
workloadsBuilder_ = null;
workloads_ = other.workloads_;
bitField0_ = (bitField0_ & ~0x00000001);
workloadsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getWorkloadsFieldBuilder()
: null;
} else {
workloadsBuilder_.addAllMessages(other.workloads_);
}
}
}
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.assuredworkloads.v1.Workload m =
input.readMessage(
com.google.cloud.assuredworkloads.v1.Workload.parser(), extensionRegistry);
if (workloadsBuilder_ == null) {
ensureWorkloadsIsMutable();
workloads_.add(m);
} else {
workloadsBuilder_.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.assuredworkloads.v1.Workload> workloads_ =
java.util.Collections.emptyList();
private void ensureWorkloadsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
workloads_ =
new java.util.ArrayList<com.google.cloud.assuredworkloads.v1.Workload>(workloads_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.assuredworkloads.v1.Workload,
com.google.cloud.assuredworkloads.v1.Workload.Builder,
com.google.cloud.assuredworkloads.v1.WorkloadOrBuilder>
workloadsBuilder_;
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public java.util.List<com.google.cloud.assuredworkloads.v1.Workload> getWorkloadsList() {
if (workloadsBuilder_ == null) {
return java.util.Collections.unmodifiableList(workloads_);
} else {
return workloadsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public int getWorkloadsCount() {
if (workloadsBuilder_ == null) {
return workloads_.size();
} else {
return workloadsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public com.google.cloud.assuredworkloads.v1.Workload getWorkloads(int index) {
if (workloadsBuilder_ == null) {
return workloads_.get(index);
} else {
return workloadsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public Builder setWorkloads(int index, com.google.cloud.assuredworkloads.v1.Workload value) {
if (workloadsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureWorkloadsIsMutable();
workloads_.set(index, value);
onChanged();
} else {
workloadsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public Builder setWorkloads(
int index, com.google.cloud.assuredworkloads.v1.Workload.Builder builderForValue) {
if (workloadsBuilder_ == null) {
ensureWorkloadsIsMutable();
workloads_.set(index, builderForValue.build());
onChanged();
} else {
workloadsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public Builder addWorkloads(com.google.cloud.assuredworkloads.v1.Workload value) {
if (workloadsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureWorkloadsIsMutable();
workloads_.add(value);
onChanged();
} else {
workloadsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public Builder addWorkloads(int index, com.google.cloud.assuredworkloads.v1.Workload value) {
if (workloadsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureWorkloadsIsMutable();
workloads_.add(index, value);
onChanged();
} else {
workloadsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public Builder addWorkloads(
com.google.cloud.assuredworkloads.v1.Workload.Builder builderForValue) {
if (workloadsBuilder_ == null) {
ensureWorkloadsIsMutable();
workloads_.add(builderForValue.build());
onChanged();
} else {
workloadsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public Builder addWorkloads(
int index, com.google.cloud.assuredworkloads.v1.Workload.Builder builderForValue) {
if (workloadsBuilder_ == null) {
ensureWorkloadsIsMutable();
workloads_.add(index, builderForValue.build());
onChanged();
} else {
workloadsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public Builder addAllWorkloads(
java.lang.Iterable<? extends com.google.cloud.assuredworkloads.v1.Workload> values) {
if (workloadsBuilder_ == null) {
ensureWorkloadsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, workloads_);
onChanged();
} else {
workloadsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public Builder clearWorkloads() {
if (workloadsBuilder_ == null) {
workloads_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
workloadsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public Builder removeWorkloads(int index) {
if (workloadsBuilder_ == null) {
ensureWorkloadsIsMutable();
workloads_.remove(index);
onChanged();
} else {
workloadsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public com.google.cloud.assuredworkloads.v1.Workload.Builder getWorkloadsBuilder(int index) {
return getWorkloadsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public com.google.cloud.assuredworkloads.v1.WorkloadOrBuilder getWorkloadsOrBuilder(int index) {
if (workloadsBuilder_ == null) {
return workloads_.get(index);
} else {
return workloadsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public java.util.List<? extends com.google.cloud.assuredworkloads.v1.WorkloadOrBuilder>
getWorkloadsOrBuilderList() {
if (workloadsBuilder_ != null) {
return workloadsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(workloads_);
}
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public com.google.cloud.assuredworkloads.v1.Workload.Builder addWorkloadsBuilder() {
return getWorkloadsFieldBuilder()
.addBuilder(com.google.cloud.assuredworkloads.v1.Workload.getDefaultInstance());
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public com.google.cloud.assuredworkloads.v1.Workload.Builder addWorkloadsBuilder(int index) {
return getWorkloadsFieldBuilder()
.addBuilder(index, com.google.cloud.assuredworkloads.v1.Workload.getDefaultInstance());
}
/**
*
*
* <pre>
* List of Workloads under a given parent.
* </pre>
*
* <code>repeated .google.cloud.assuredworkloads.v1.Workload workloads = 1;</code>
*/
public java.util.List<com.google.cloud.assuredworkloads.v1.Workload.Builder>
getWorkloadsBuilderList() {
return getWorkloadsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.assuredworkloads.v1.Workload,
com.google.cloud.assuredworkloads.v1.Workload.Builder,
com.google.cloud.assuredworkloads.v1.WorkloadOrBuilder>
getWorkloadsFieldBuilder() {
if (workloadsBuilder_ == null) {
workloadsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.assuredworkloads.v1.Workload,
com.google.cloud.assuredworkloads.v1.Workload.Builder,
com.google.cloud.assuredworkloads.v1.WorkloadOrBuilder>(
workloads_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
workloads_ = null;
}
return workloadsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* The next page token. Return empty if reached the last page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The next page token. Return empty if reached the last page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The next page token. Return empty if reached the last page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The next page token. Return empty if reached the last page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The next page token. Return empty if reached the last page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.assuredworkloads.v1.ListWorkloadsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.assuredworkloads.v1.ListWorkloadsResponse)
private static final com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse();
}
public static com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListWorkloadsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListWorkloadsResponse>() {
@java.lang.Override
public ListWorkloadsResponse 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<ListWorkloadsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListWorkloadsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.assuredworkloads.v1.ListWorkloadsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
oracle/graal | 36,673 | regex/src/com.oracle.truffle.regex/src/com/oracle/truffle/regex/flavor/python/PythonRegexLexer.java | /*
* Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.oracle.truffle.regex.flavor.python;
import static com.oracle.truffle.regex.flavor.python.PythonFlavor.UNICODE;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.graalvm.shadowed.com.ibm.icu.lang.UCharacter;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.regex.RegexSource;
import com.oracle.truffle.regex.RegexSyntaxException;
import com.oracle.truffle.regex.RegexSyntaxException.ErrorCode;
import com.oracle.truffle.regex.UnsupportedRegexException;
import com.oracle.truffle.regex.chardata.UnicodeCharacterAliases;
import com.oracle.truffle.regex.charset.ClassSetContents;
import com.oracle.truffle.regex.charset.CodePointSet;
import com.oracle.truffle.regex.charset.CodePointSetAccumulator;
import com.oracle.truffle.regex.charset.Constants;
import com.oracle.truffle.regex.charset.UnicodeProperties;
import com.oracle.truffle.regex.tregex.buffer.CompilationBuffer;
import com.oracle.truffle.regex.tregex.parser.CaseFoldData;
import com.oracle.truffle.regex.tregex.parser.RegexLexer;
import com.oracle.truffle.regex.tregex.parser.Token;
import com.oracle.truffle.regex.tregex.string.Encodings;
import com.oracle.truffle.regex.util.TBitSet;
public final class PythonRegexLexer extends RegexLexer {
private static final CodePointSet ASCII_WHITESPACE = CodePointSet.createNoDedup(0x09, 0x0d, 0x20, 0x20);
private static final CodePointSet ASCII_NON_WHITESPACE = CodePointSet.createNoDedup(0x00, 0x08, 0x0e, 0x1f, 0x21, 0x10ffff);
/**
* The (slightly modified) version of the XID_Start Unicode property used to check names of
* capture groups.
*/
private static final CodePointSet XID_START = UNICODE.getProperty("XID_Start").union(CodePointSet.create('_'));
/**
* The XID_Continue Unicode character property.
*/
private static final CodePointSet XID_CONTINUE = UNICODE.getProperty("XID_Continue");
/**
* Maps Python's predefined Unicode character classes to sets containing the characters to be
* matched.
*/
private static final Map<Character, CodePointSet> UNICODE_CHAR_CLASS_SETS;
// "[^\n]"
private static final CodePointSet PYTHON_DOT = CodePointSet.createNoDedup(0, '\n' - 1, '\n' + 1, 0x10ffff);
static {
UNICODE_CHAR_CLASS_SETS = new HashMap<>();
// Digits: \d
// Python accepts characters with the Numeric_Type=Decimal property.
// As of Unicode 11.0.0, these happen to be exactly the characters
// in the Decimal_Number General Category.
UNICODE_CHAR_CLASS_SETS.put('d', UNICODE.getProperty("General_Category=Decimal_Number"));
// Non-digits: \D
UNICODE_CHAR_CLASS_SETS.put('D', UNICODE.getProperty("General_Category=Decimal_Number").createInverse(Encodings.UTF_32));
// Spaces: \s
// Python accepts characters with either the Space_Separator General Category
// or one of the WS, B or S Bidi_Classes. A close analogue available in
// ECMAScript regular expressions is the White_Space Unicode property,
// which is only missing the characters \\u001c-\\u001f (as of Unicode 11.0.0).
// Non-spaces: \S
// If we are translating an occurrence of \S inside a character class, we cannot
// use the negated Unicode character property \P{White_Space}, because then we would
// need to subtract the code points \\u001c-\\u001f from the resulting character class,
// which is not possible in ECMAScript regular expressions. Therefore, we have to expand
// the definition of the White_Space property, do the set subtraction and then list the
// contents of the resulting set.
CodePointSet unicodeSpaces = UNICODE.getProperty("White_Space");
CodePointSet spaces = unicodeSpaces.union(CodePointSet.createNoDedup('\u001c', '\u001f'));
CodePointSet nonSpaces = spaces.createInverse(Encodings.UTF_32);
UNICODE_CHAR_CLASS_SETS.put('s', spaces);
UNICODE_CHAR_CLASS_SETS.put('S', nonSpaces);
// Word characters: \w
// As alphabetic characters, Python accepts those in the general category L.
// As numeric, it takes any character with either Numeric_Type=Decimal,
// Numeric_Type=Digit or Numeric_Type=Numeric. As of Unicode 11.0.0, this
// corresponds to the general category Number, along with the following
// code points:
// F96B;CJK COMPATIBILITY IDEOGRAPH-F96B;Lo;0;L;53C3;;;3;N;;;;;
// F973;CJK COMPATIBILITY IDEOGRAPH-F973;Lo;0;L;62FE;;;10;N;;;;;
// F978;CJK COMPATIBILITY IDEOGRAPH-F978;Lo;0;L;5169;;;2;N;;;;;
// F9B2;CJK COMPATIBILITY IDEOGRAPH-F9B2;Lo;0;L;96F6;;;0;N;;;;;
// F9D1;CJK COMPATIBILITY IDEOGRAPH-F9D1;Lo;0;L;516D;;;6;N;;;;;
// F9D3;CJK COMPATIBILITY IDEOGRAPH-F9D3;Lo;0;L;9678;;;6;N;;;;;
// F9FD;CJK COMPATIBILITY IDEOGRAPH-F9FD;Lo;0;L;4EC0;;;10;N;;;;;
// 2F890;CJK COMPATIBILITY IDEOGRAPH-2F890;Lo;0;L;5EFE;;;9;N;;;;;
// Non-word characters: \W
// Similarly as for \S, we will not be able to produce a replacement string for \W.
// We will need to construct the set ourselves.
CodePointSet alpha = UNICODE.getProperty("General_Category=Letter");
CodePointSet numericExtras = CodePointSet.createNoDedup(
0xf96b, 0xf96b,
0xf973, 0xf973,
0xf978, 0xf978,
0xf9b2, 0xf9b2,
0xf9d1, 0xf9d1,
0xf9d3, 0xf9d3,
0xf9fd, 0xf9fd,
0x2f890, 0x2f890);
CodePointSet numeric = UNICODE.getProperty("General_Category=Number").union(numericExtras);
CodePointSet wordChars = alpha.union(numeric).union(CodePointSet.create('_'));
CodePointSet nonWordChars = wordChars.createInverse(Encodings.UTF_32);
UNICODE_CHAR_CLASS_SETS.put('w', wordChars);
UNICODE_CHAR_CLASS_SETS.put('W', nonWordChars);
}
/**
* Indicates whether the regex being parsed is a 'str' pattern or a 'bytes' pattern.
*/
private final PythonREMode mode;
/**
* A stack of the locally enabled flags. Python enables the setting and unsetting of the flags
* for subexpressions of the regex.
* <p>
* The currently active flags are at the top, the flags that would become active after the end
* of the next (?aiLmsux-imsx:...) expression are just below.
*/
private final Deque<PythonFlags> flagsStack = new ArrayDeque<>();
/**
* The global flags are the flags given when compiling the regular expression. Note that these
* flags <em>can</em> be changed inline, in the pattern.
*/
private PythonFlags globalFlags;
private final CodePointSetAccumulator caseFoldTmp = new CodePointSetAccumulator();
private PythonLocaleData localeData;
public PythonRegexLexer(RegexSource source, PythonREMode mode, CompilationBuffer compilationBuffer) {
super(source, compilationBuffer);
this.mode = mode;
this.globalFlags = new PythonFlags(source.getFlags());
}
private static int lookupCharacterByName(String characterName) {
// CPython's logic for resolving these character names goes like this:
// 1) handle Hangul Syllables in region AC00-D7A3
// 2) handle CJK Ideographs
// 3) handle character names as given in UnicodeData.txt
// 4) handle all aliases as given in NameAliases.txt
// With ICU's UCharacter, we get cases 1), 2) and 3). As for 4), the aliases, ICU only
// handles aliases of type 'correction'. Therefore, we extract the contents of
// NameAliases.txt and handle aliases by ourselves.
String normalizedName = characterName.trim().toUpperCase(Locale.ROOT);
if (UnicodeCharacterAliases.CHARACTER_ALIASES.containsKey(normalizedName)) {
return UnicodeCharacterAliases.CHARACTER_ALIASES.get(normalizedName);
} else {
return UCharacter.getCharFromName(characterName);
}
}
public PythonLocaleData getLocaleData() {
if (localeData == null) {
try {
localeData = PythonLocaleData.getLocaleData(source.getOptions().getPythonLocale());
} catch (IllegalArgumentException e) {
throw new UnsupportedRegexException(e.getMessage(), source);
}
}
return localeData;
}
public void fixFlags() {
globalFlags = globalFlags.fixFlags(source, mode);
}
public PythonFlags getGlobalFlags() {
return globalFlags;
}
public void addGlobalFlags(PythonFlags newGlobalFlags) {
globalFlags = globalFlags.addFlags(newGlobalFlags);
}
public PythonFlags getLocalFlags() {
return flagsStack.isEmpty() ? globalFlags : flagsStack.peek();
}
public void pushLocalFlags(PythonFlags localFlags) {
flagsStack.push(localFlags);
}
public void popLocalFlags() {
flagsStack.pop();
}
@Override
protected UnicodeProperties getUnicodeProperties() {
return UNICODE;
}
@Override
protected boolean featureEnabledIgnoreCase() {
return getLocalFlags().isIgnoreCase();
}
@Override
protected boolean featureEnabledAZPositionAssertions() {
return true;
}
@Override
protected boolean featureEnabledZLowerCaseAssertion() {
return false;
}
@Override
protected boolean featureEnabledBoundedQuantifierEmptyMin() {
return true;
}
@Override
protected boolean featureEnabledPossessiveQuantifiers() {
return true;
}
@Override
protected boolean featureEnabledCharClassFirstBracketIsLiteral() {
return true;
}
@Override
protected boolean featureEnabledCCRangeWithPredefCharClass() {
return true;
}
@Override
protected boolean featureEnabledNestedCharClasses() {
return false;
}
@Override
protected boolean featureEnabledPOSIXCharClasses() {
return false;
}
@Override
protected boolean featureEnabledForwardReferences() {
return false;
}
@Override
protected boolean featureEnabledGroupComments() {
return true;
}
@Override
protected boolean featureEnabledLineComments() {
return getLocalFlags().isVerbose();
}
@Override
protected boolean featureEnabledIgnoreWhiteSpace() {
return false;
}
@Override
protected TBitSet getWhitespace() {
return DEFAULT_WHITESPACE;
}
@Override
protected boolean featureEnabledOctalEscapes() {
return true;
}
@Override
protected boolean featureEnabledSpecialGroups() {
return true;
}
@Override
protected boolean featureEnabledUnicodePropertyEscapes() {
return false;
}
@Override
protected boolean featureEnabledClassSetExpressions() {
return false;
}
@Override
protected CodePointSet getDotCodePointSet() {
return getLocalFlags().isDotAll() ? Constants.DOT_ALL : PYTHON_DOT;
}
@Override
protected CodePointSet getIdContinue() {
return XID_CONTINUE;
}
@Override
protected CodePointSet getIdStart() {
return XID_START;
}
@Override
protected int getMaxBackReferenceDigits() {
return 2;
}
@Override
protected void caseFoldUnfold(CodePointSetAccumulator charClass) {
if (getLocalFlags().isLocale()) {
getLocaleData().caseFoldUnfold(charClass, caseFoldTmp);
} else {
CaseFoldData.CaseFoldUnfoldAlgorithm caseFolding = getLocalFlags().isUnicode(mode) ? CaseFoldData.CaseFoldUnfoldAlgorithm.PythonUnicode : CaseFoldData.CaseFoldUnfoldAlgorithm.Ascii;
CaseFoldData.applyCaseFoldUnfold(charClass, caseFoldTmp, caseFolding);
}
}
@Override
protected CodePointSet complementClassSet(CodePointSet codePointSet) {
throw CompilerDirectives.shouldNotReachHere();
}
@Override
protected ClassSetContents caseFoldClassSetAtom(ClassSetContents classSetContents) {
throw CompilerDirectives.shouldNotReachHere();
}
@Override
protected CodePointSet getPredefinedCharClass(char c) {
if (getLocalFlags().isUnicode(mode)) {
return UNICODE_CHAR_CLASS_SETS.get(c);
}
switch (c) {
case 'd':
return Constants.DIGITS;
case 'D':
return Constants.NON_DIGITS;
case 's':
if (mode == PythonREMode.Bytes || getLocalFlags().isAscii()) {
return ASCII_WHITESPACE;
}
return Constants.WHITE_SPACE;
case 'S':
if (mode == PythonREMode.Bytes || getLocalFlags().isAscii()) {
return ASCII_NON_WHITESPACE;
}
return Constants.NON_WHITE_SPACE;
case 'w':
if (getLocalFlags().isLocale()) {
return getLocaleData().getWordCharacters();
} else {
return Constants.WORD_CHARS;
}
case 'W':
if (getLocalFlags().isLocale()) {
return getLocaleData().getNonWordCharacters();
} else {
return Constants.NON_WORD_CHARS;
}
default:
throw CompilerDirectives.shouldNotReachHere();
}
}
@Override
protected void checkClassSetCharacter(int codePoint) throws RegexSyntaxException {
}
@Override
protected long boundedQuantifierMaxValue() {
return Integer.MAX_VALUE;
}
private RegexSyntaxException handleBadCharacterInGroupName(ParseGroupNameResult result) {
return syntaxErrorAtRel(PyErrorMessages.badCharacterInGroupName(result.groupName), result.groupName.length() + 1, ErrorCode.InvalidNamedGroup);
}
@Override
protected RegexSyntaxException handleBoundedQuantifierOutOfOrder() {
return syntaxErrorAtAbs(PyErrorMessages.MIN_REPEAT_GREATER_THAN_MAX_REPEAT, getLastTokenPosition() + 1, ErrorCode.InvalidQuantifier);
}
@Override
protected Token handleBoundedQuantifierEmptyOrMissingMin() throws RegexSyntaxException {
position = getLastTokenPosition() + 1;
return literalChar('{');
}
@Override
protected Token handleBoundedQuantifierInvalidCharacter() {
return handleBoundedQuantifierEmptyOrMissingMin();
}
@Override
protected Token handleBoundedQuantifierOverflow(long min, long max) {
return null;
}
@Override
protected Token handleBoundedQuantifierOverflowMin(long min, long max) {
return null;
}
@Override
protected RegexSyntaxException handleCCRangeOutOfOrder(int rangeStart) {
return syntaxErrorAtAbs(PyErrorMessages.badCharacterRange(pattern.substring(rangeStart, position)), rangeStart, ErrorCode.InvalidCharacterClass);
}
@Override
protected void handleCCRangeWithPredefCharClass(int rangeStart, ClassSetContents firstAtom, ClassSetContents secondAtom) {
throw syntaxErrorAtAbs(PyErrorMessages.badCharacterRange(pattern.substring(rangeStart, position)), rangeStart, ErrorCode.InvalidCharacterClass);
}
@Override
protected CodePointSet getPOSIXCharClass(String name) {
throw CompilerDirectives.shouldNotReachHere();
}
@Override
protected void validatePOSIXCollationElement(String sequence) {
throw CompilerDirectives.shouldNotReachHere();
}
@Override
protected void validatePOSIXEquivalenceClass(String sequence) {
throw CompilerDirectives.shouldNotReachHere();
}
@Override
protected RegexSyntaxException handleComplementOfStringSet() {
throw CompilerDirectives.shouldNotReachHere();
}
@Override
protected void handleGroupRedefinition(String name, int newId, int oldId) {
throw syntaxErrorAtRel(PyErrorMessages.redefinitionOfGroupName(name, newId, oldId), name.length() + 1, ErrorCode.InvalidNamedGroup);
}
@Override
protected void handleIncompleteEscapeX() {
throw syntaxError(PyErrorMessages.incompleteEscape(substring(2 + count(RegexLexer::isHexDigit))), ErrorCode.InvalidEscape);
}
@Override
protected Token handleInvalidBackReference(int reference) {
String ref = Integer.toString(reference);
throw syntaxErrorAtRel(PyErrorMessages.invalidGroupReference(ref), ref.length(), ErrorCode.InvalidBackReference);
}
@Override
protected RegexSyntaxException handleInvalidCharInCharClass() {
throw CompilerDirectives.shouldNotReachHere();
}
@Override
protected RegexSyntaxException handleInvalidGroupBeginQ() {
retreat();
return syntaxErrorAtAbs(PyErrorMessages.unknownExtensionQ(curChar()), getLastTokenPosition() + 1, ErrorCode.InvalidGroup);
}
@Override
protected RegexSyntaxException handleMixedClassSetOperators(ClassSetOperator leftOperator, ClassSetOperator rightOperator) {
throw CompilerDirectives.shouldNotReachHere();
}
@Override
protected RegexSyntaxException handleMissingClassSetOperand(ClassSetOperator operator) {
throw CompilerDirectives.shouldNotReachHere();
}
@Override
protected void handleOctalOutOfRange() {
throw syntaxError(PyErrorMessages.invalidOctalEscape(substring(4)), ErrorCode.InvalidEscape);
}
@Override
protected RegexSyntaxException handleRangeAsClassSetOperand(ClassSetOperator operator) {
throw CompilerDirectives.shouldNotReachHere();
}
@Override
protected void handleUnfinishedEscape() {
throw syntaxError(PyErrorMessages.BAD_ESCAPE_END_OF_PATTERN, ErrorCode.InvalidEscape);
}
@Override
protected void handleUnfinishedGroupComment() {
throw syntaxError(PyErrorMessages.UNTERMINATED_COMMENT, ErrorCode.UnmatchedParenthesis);
}
@Override
protected RegexSyntaxException handleUnfinishedGroupQ() {
return syntaxErrorHere(PyErrorMessages.UNEXPECTED_END_OF_PATTERN, ErrorCode.UnmatchedParenthesis);
}
@Override
protected RegexSyntaxException handleUnfinishedRangeInClassSet() {
throw CompilerDirectives.shouldNotReachHere();
}
@Override
protected void handleUnmatchedRightBrace() {
// not an error in python
}
@Override
protected RegexSyntaxException handleUnmatchedLeftBracket() {
return syntaxErrorAtAbs(PyErrorMessages.UNTERMINATED_CHARACTER_SET, getLastCharacterClassBeginPosition(), ErrorCode.UnmatchedBracket);
}
@Override
protected void handleUnmatchedRightBracket() {
// not an error in python
}
@Override
protected int parseCodePointInGroupName() throws RegexSyntaxException {
final char c = consumeChar();
return Character.isHighSurrogate(c) ? finishSurrogatePair(c) : c;
}
@Override
protected Token parseCustomEscape(char c) {
if (c == 'b') {
return Token.createWordBoundary();
} else if (c == 'B') {
return Token.createNonWordBoundary();
} else if (isOctalDigit(c) && lookahead(RegexLexer::isOctalDigit, 2)) {
int codePoint = (c - '0') * 64 + (consumeChar() - '0') * 8 + (consumeChar() - '0');
if (codePoint > 0xff) {
handleOctalOutOfRange();
}
return literalChar(codePoint);
}
return null;
}
@Override
protected int parseCustomEscapeChar(char c, boolean inCharClass) {
switch (c) {
case 'a':
return '\u0007';
case 'u':
case 'U':
// 'u' and 'U' escapes are supported only in 'str' patterns
if (mode == PythonREMode.Str) {
int escapeLength;
switch (c) {
case 'u':
escapeLength = 4;
break;
case 'U':
escapeLength = 8;
break;
default:
throw CompilerDirectives.shouldNotReachHere();
}
int length = countUpTo(RegexLexer::isHexDigit, escapeLength);
if (length != escapeLength) {
throw syntaxError(PyErrorMessages.incompleteEscape(substring(2 + length)), ErrorCode.InvalidEscape);
}
advance(length);
try {
int codePoint = Integer.parseInt(pattern, position - length, position, 16);
if (codePoint > 0x10FFFF) {
throw syntaxError(PyErrorMessages.invalidUnicodeEscape(substring(2 + length)), ErrorCode.InvalidEscape);
}
return codePoint;
} catch (NumberFormatException e) {
throw syntaxError(PyErrorMessages.incompleteEscape(substring(2 + length)), ErrorCode.InvalidEscape);
}
} else {
// \\u or \\U in 'bytes' patterns
throw syntaxError(PyErrorMessages.badEscape(c), ErrorCode.InvalidEscape);
}
case 'N': {
if (mode != PythonREMode.Str) {
throw syntaxError(PyErrorMessages.badEscape(c), ErrorCode.InvalidEscape);
}
if (!consumingLookahead("{")) {
throw syntaxErrorHere(PyErrorMessages.missing("{"), ErrorCode.InvalidEscape);
}
int nameStart = position;
int nameEnd = pattern.indexOf('}', position);
if (atEnd() || nameEnd == position) {
throw syntaxErrorHere(PyErrorMessages.missing("character name"), ErrorCode.InvalidEscape);
}
if (nameEnd < 0) {
throw syntaxErrorHere(PyErrorMessages.missingUnterminatedName('}'), ErrorCode.InvalidEscape);
}
String characterName = pattern.substring(nameStart, nameEnd);
position = nameEnd + 1;
int codePoint = lookupCharacterByName(characterName);
if (codePoint == -1) {
throw syntaxError(PyErrorMessages.undefinedCharacterName(characterName), ErrorCode.InvalidEscape);
}
return codePoint;
}
default:
return -1;
}
}
@Override
protected int parseCustomEscapeCharFallback(int c, boolean inCharClass) {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') {
throw syntaxError(PyErrorMessages.badEscape(c), ErrorCode.InvalidEscape);
}
return c;
}
@Override
protected Token parseCustomGroupBeginQ(char charAfterQuestionMark) {
switch (charAfterQuestionMark) {
case 'P': {
mustHaveMore();
final int ch2 = consumeChar();
switch (ch2) {
case '<': {
int pos = position;
ParseGroupNameResult result = parseGroupName('>');
switch (result.state) {
case empty:
throw syntaxErrorHere(PyErrorMessages.MISSING_GROUP_NAME, ErrorCode.InvalidNamedGroup);
case unterminated:
throw syntaxErrorAtAbs(PyErrorMessages.UNTERMINATED_NAME_ANGLE_BRACKET, pos, ErrorCode.InvalidNamedGroup);
case invalidStart:
case invalidRest:
throw handleBadCharacterInGroupName(result);
case valid:
registerNamedCaptureGroup(result.groupName);
break;
default:
throw CompilerDirectives.shouldNotReachHere();
}
return Token.createCaptureGroupBegin();
}
case '=': {
return parseNamedBackReference();
}
default:
throw syntaxErrorAtRel(PyErrorMessages.unknownExtensionP(ch2), 3, ErrorCode.InvalidGroup);
}
}
case '>':
return Token.createAtomicGroupBegin();
case '(':
return parseConditionalBackReference();
case '-':
case 'i':
case 'L':
case 'm':
case 's':
case 'x':
case 'a':
case 'u':
return parseInlineFlags(charAfterQuestionMark);
default:
return null;
}
}
@Override
protected Token parseGroupLt() {
if (atEnd()) {
throw syntaxErrorHere(PyErrorMessages.UNEXPECTED_END_OF_PATTERN, ErrorCode.InvalidGroup);
}
throw syntaxErrorAtAbs(PyErrorMessages.unknownExtensionLt(curChar()), getLastTokenPosition() + 1, ErrorCode.InvalidGroup);
}
/**
* Parses a conditional back-reference, assuming that the prefix '(?(' was already parsed.
*/
private Token parseConditionalBackReference() {
final int groupNumber;
final boolean namedReference;
ParseGroupNameResult result = parseGroupName(')');
switch (result.state) {
case empty:
throw syntaxErrorHere(PyErrorMessages.MISSING_GROUP_NAME, ErrorCode.InvalidNamedGroup);
case unterminated:
throw syntaxErrorAtRel(PyErrorMessages.UNTERMINATED_NAME, result.groupName.length(), ErrorCode.InvalidNamedGroup);
case invalidStart:
case invalidRest:
position -= result.groupName.length() + 1;
assert lookahead(result.groupName + ")");
int groupNumberLength = countDecimalDigits();
if (groupNumberLength != result.groupName.length()) {
position += result.groupName.length() + 1;
throw handleBadCharacterInGroupName(result);
}
groupNumber = parseIntSaturated(0, result.groupName.length(), -1);
namedReference = false;
assert curChar() == ')';
advance();
if (groupNumber == 0) {
throw syntaxErrorAtRel(PyErrorMessages.BAD_GROUP_NUMBER, result.groupName.length() + 1, ErrorCode.InvalidBackReference);
} else if (groupNumber == -1) {
throw syntaxErrorAtRel(PyErrorMessages.invalidGroupReference(result.groupName), result.groupName.length() + 1, ErrorCode.InvalidBackReference);
}
break;
case valid:
// group referenced by name
if (namedCaptureGroups.containsKey(result.groupName)) {
groupNumber = getSingleNamedGroupNumber(result.groupName);
namedReference = true;
} else {
throw syntaxErrorAtRel(PyErrorMessages.unknownGroupName(result.groupName, mode), result.groupName.length() + 1, ErrorCode.InvalidBackReference);
}
break;
default:
throw CompilerDirectives.shouldNotReachHere();
}
return Token.createConditionalBackReference(groupNumber, namedReference);
}
/**
* Parses a local flag block or an inline declaration of a global flags. Assumes that the prefix
* '(?' was already parsed, as well as the first flag which is passed as the argument.
*/
private Token parseInlineFlags(int ch0) {
int ch = ch0;
PythonFlags positiveFlags = PythonFlags.EMPTY_INSTANCE;
while (PythonFlags.isValidFlagChar(ch)) {
positiveFlags = addFlag(positiveFlags, ch);
ch = consumeChar();
}
switch (ch) {
case ')':
return Token.createInlineFlags(positiveFlags, true);
case ':':
return parseLocalFlags(positiveFlags, PythonFlags.EMPTY_INSTANCE);
case '-':
if (atEnd()) {
throw syntaxErrorHere(PyErrorMessages.MISSING_FLAG, ErrorCode.InvalidInlineFlag);
}
ch = consumeChar();
if (!PythonFlags.isValidFlagChar(ch)) {
if (Character.isAlphabetic(ch)) {
throw syntaxErrorAtRel(PyErrorMessages.UNKNOWN_FLAG, 1, ErrorCode.InvalidInlineFlag);
} else {
throw syntaxErrorAtRel(PyErrorMessages.MISSING_FLAG, 1, ErrorCode.InvalidInlineFlag);
}
}
PythonFlags negativeFlags = PythonFlags.EMPTY_INSTANCE;
while (PythonFlags.isValidFlagChar(ch)) {
negativeFlags = negativeFlags.addFlag(ch);
if (PythonFlags.isTypeFlagChar(ch)) {
throw syntaxErrorHere(PyErrorMessages.INLINE_FLAGS_CANNOT_TURN_OFF_FLAGS_A_U_AND_L, ErrorCode.InvalidInlineFlag);
}
if (atEnd()) {
throw syntaxErrorHere(PyErrorMessages.MISSING_COLON, ErrorCode.InvalidInlineFlag);
}
ch = consumeChar();
}
if (ch != ':') {
if (Character.isAlphabetic(ch)) {
throw syntaxErrorAtRel(PyErrorMessages.UNKNOWN_FLAG, 1, ErrorCode.InvalidInlineFlag);
} else {
throw syntaxErrorAtRel(PyErrorMessages.MISSING_COLON, 1, ErrorCode.InvalidInlineFlag);
}
}
return parseLocalFlags(positiveFlags, negativeFlags);
default:
if (Character.isAlphabetic(ch)) {
throw syntaxErrorAtRel(PyErrorMessages.UNKNOWN_FLAG, 1, ErrorCode.InvalidInlineFlag);
} else {
throw syntaxErrorAtRel(PyErrorMessages.MISSING_DASH_COLON_PAREN, 1, ErrorCode.InvalidInlineFlag);
}
}
}
private PythonFlags addFlag(PythonFlags flagsArg, int ch) {
PythonFlags flags = flagsArg.addFlag(ch);
if (mode == PythonREMode.Str && ch == 'L') {
throw syntaxErrorHere(PyErrorMessages.INLINE_FLAGS_CANNOT_USE_L_FLAG_WITH_A_STR_PATTERN, ErrorCode.InvalidInlineFlag);
}
if (mode == PythonREMode.Bytes && ch == 'u') {
throw syntaxErrorHere(PyErrorMessages.INLINE_FLAGS_CANNOT_USE_U_FLAG_WITH_A_BYTES_PATTERN, ErrorCode.InvalidInlineFlag);
}
if (flags.numberOfTypeFlags() > 1) {
throw syntaxErrorHere(PyErrorMessages.INLINE_FLAGS_FLAGS_A_U_AND_L_ARE_INCOMPATIBLE, ErrorCode.InvalidInlineFlag);
}
if (atEnd()) {
throw syntaxErrorHere(PyErrorMessages.MISSING_DASH_COLON_PAREN, ErrorCode.InvalidInlineFlag);
}
return flags;
}
/**
* Parses a block with local flags, assuming that the opening parenthesis, the flags and the ':'
* have been parsed.
*
* @param positiveFlags - the flags to be turned on in the block
* @param negativeFlags - the flags to be turned off in the block
*/
private Token parseLocalFlags(PythonFlags positiveFlags, PythonFlags negativeFlags) {
if (positiveFlags.overlaps(negativeFlags)) {
throw syntaxErrorAtRel(PyErrorMessages.INLINE_FLAGS_FLAG_TURNED_ON_AND_OFF, 1, ErrorCode.InvalidInlineFlag);
}
PythonFlags newFlags = getLocalFlags().addFlags(positiveFlags).delFlags(negativeFlags);
if (positiveFlags.numberOfTypeFlags() > 0) {
PythonFlags otherTypes = PythonFlags.TYPE_FLAGS_INSTANCE.delFlags(positiveFlags);
newFlags = newFlags.delFlags(otherTypes);
}
return Token.createInlineFlags(newFlags, false);
}
private void mustHaveMore() {
if (atEnd()) {
throw syntaxErrorHere(PyErrorMessages.UNEXPECTED_END_OF_PATTERN, ErrorCode.InvalidGroup);
}
}
/**
* Parses a named backreference, assuming that the prefix '(?P=' was already parsed.
*/
private Token parseNamedBackReference() {
ParseGroupNameResult result = parseGroupName(')');
switch (result.state) {
case empty:
throw syntaxErrorHere(PyErrorMessages.MISSING_GROUP_NAME, ErrorCode.InvalidBackReference);
case unterminated:
throw syntaxErrorAtRel(PyErrorMessages.UNTERMINATED_NAME, result.groupName.length(), ErrorCode.InvalidBackReference);
case invalidStart:
case invalidRest:
throw handleBadCharacterInGroupName(result);
case valid:
if (namedCaptureGroups.containsKey(result.groupName)) {
assert namedCaptureGroups.get(result.groupName).size() == 1;
return Token.createBackReference(namedCaptureGroups.get(result.groupName).get(0), true);
} else {
throw syntaxErrorAtRel(PyErrorMessages.unknownGroupName(result.groupName, mode), result.groupName.length() + 1, ErrorCode.InvalidBackReference);
}
default:
throw CompilerDirectives.shouldNotReachHere();
}
}
private String substring(int length) {
return pattern.substring(getLastAtomPosition(), getLastAtomPosition() + length);
}
public RegexSyntaxException syntaxErrorAtAbs(String msg, int i, ErrorCode errorCode) {
return RegexSyntaxException.createPattern(source, msg, i, errorCode);
}
private RegexSyntaxException syntaxErrorAtRel(String msg, int i, ErrorCode errorCode) {
return RegexSyntaxException.createPattern(source, msg, position - i, errorCode);
}
public RegexSyntaxException syntaxErrorHere(String msg, ErrorCode errorCode) {
return RegexSyntaxException.createPattern(source, msg, position, errorCode);
}
}
|
google/guava | 36,539 | android/guava/src/com/google/common/collect/CompactHashMap.java | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.collect.CollectPreconditions.checkRemove;
import static com.google.common.collect.CompactHashing.UNSET;
import static com.google.common.collect.Hashing.smearedHash;
import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
import static com.google.common.collect.NullnessCasts.unsafeNull;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.WeakOuter;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import org.jspecify.annotations.Nullable;
/**
* CompactHashMap is an implementation of a Map. All optional operations (put and remove) are
* supported. Null keys and values are supported.
*
* <p>{@code containsKey(k)}, {@code put(k, v)} and {@code remove(k)} are all (expected and
* amortized) constant time operations. Expected in the hashtable sense (depends on the hash
* function doing a good job of distributing the elements to the buckets to a distribution not far
* from uniform), and amortized since some operations can trigger a hash table resize.
*
* <p>Unlike {@code java.util.HashMap}, iteration is only proportional to the actual {@code size()},
* which is optimal, and <i>not</i> the size of the internal hashtable, which could be much larger
* than {@code size()}. Furthermore, this structure places significantly reduced load on the garbage
* collector by only using a constant number of internal objects.
*
* <p>If there are no removals, then iteration order for the {@link #entrySet}, {@link #keySet}, and
* {@link #values} views is the same as insertion order. Any removal invalidates any ordering
* guarantees.
*
* <p>This class should not be assumed to be universally superior to {@code java.util.HashMap}.
* Generally speaking, this class reduces object allocation and memory consumption at the price of
* moderately increased constant factors of CPU. Only use this class when there is a specific reason
* to prioritize memory over CPU.
*
* @author Louis Wasserman
* @author Jon Noack
*/
@GwtIncompatible // not worth using in GWT for now
class CompactHashMap<K extends @Nullable Object, V extends @Nullable Object>
extends AbstractMap<K, V> implements Serializable {
/*
* TODO: Make this a drop-in replacement for j.u. versions, actually drop them in, and test the
* world. Figure out what sort of space-time tradeoff we're actually going to get here with the
* *Map variants. This class is particularly hard to benchmark, because the benefit is not only in
* less allocation, but also having the GC do less work to scan the heap because of fewer
* references, which is particularly hard to quantify.
*/
/** Creates an empty {@code CompactHashMap} instance. */
public static <K extends @Nullable Object, V extends @Nullable Object>
CompactHashMap<K, V> create() {
return new CompactHashMap<>();
}
/**
* Creates a {@code CompactHashMap} instance, with a high enough "initial capacity" that it
* <i>should</i> hold {@code expectedSize} elements without growth.
*
* @param expectedSize the number of elements you expect to add to the returned set
* @return a new, empty {@code CompactHashMap} with enough capacity to hold {@code expectedSize}
* elements without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
CompactHashMap<K, V> createWithExpectedSize(int expectedSize) {
return new CompactHashMap<>(expectedSize);
}
private static final Object NOT_FOUND = new Object();
/**
* Maximum allowed false positive probability of detecting a hash flooding attack given random
* input.
*/
@VisibleForTesting(
)
static final double HASH_FLOODING_FPP = 0.001;
/**
* Maximum allowed length of a hash table bucket before falling back to a j.u.LinkedHashMap-based
* implementation. Experimentally determined.
*/
private static final int MAX_HASH_BUCKET_LENGTH = 9;
// The way the `table`, `entries`, `keys`, and `values` arrays work together is as follows.
//
// The `table` array always has a size that is a power of 2. The hashcode of a key in the map
// is masked in order to correspond to the current table size. For example, if the table size
// is 128 then the mask is 127 == 0x7f, keeping the bottom 7 bits of the hash value.
// If a key hashes to 0x89abcdef the mask reduces it to 0x89abcdef & 0x7f == 0x6f. We'll call this
// the "short hash".
//
// The `keys`, `values`, and `entries` arrays always have the same size as each other. They can be
// seen as fields of an imaginary `Entry` object like this:
//
// class Entry {
// int hash;
// Entry next;
// K key;
// V value;
// }
//
// The imaginary `hash` and `next` values are combined into a single `int` value in the `entries`
// array. The top bits of this value are the remaining bits of the hash value that were not used
// in the short hash. We saw that a mask of 0x7f would keep the 7-bit value 0x6f from a full
// hashcode of 0x89abcdef. The imaginary `hash` value would then be the remaining top 25 bits,
// 0x89abcd80. To this is added (or'd) the `next` value, which is an index within `entries`
// (and therefore within `keys` and `values`) of another entry that has the same short hash
// value. In our example, it would be another entry for a key whose short hash is also 0x6f.
//
// Essentially, then, `table[h]` gives us the start of a linked list in `entries`, where every
// element of the list has the short hash value h.
//
// A wrinkle here is that the value 0 (called UNSET in the code) is used as the equivalent of a
// null pointer. If `table[h] == 0` that means there are no keys in the map whose short hash is h.
// If the `next` bits in `entries[i]` are 0 that means there are no further entries for the given
// short hash. But 0 is also a valid index in `entries`, so we add 1 to these indices before
// putting them in `table` or in `next` bits, and subtract 1 again when we need an index value.
//
// The elements of `keys`, `values`, and `entries` are added sequentially, so that elements 0 to
// `size() - 1` are used and remaining elements are not. This makes iteration straightforward.
// Removing an entry generally involves moving the last element of each array to where the removed
// entry was, and adjusting index links accordingly.
/**
* The hashtable object. This can be either:
*
* <ul>
* <li>a byte[], short[], or int[], with size a power of two, created by
* CompactHashing.createTable, whose values are either
* <ul>
* <li>UNSET, meaning "null pointer"
* <li>one plus an index into the keys, values, and entries arrays
* </ul>
* <li>another java.util.Map delegate implementation. In most modern JDKs, normal java.util hash
* collections intelligently fall back to a binary search tree if hash table collisions are
* detected. Rather than going to all the trouble of reimplementing this ourselves, we
* simply switch over to use the JDK implementation wholesale if probable hash flooding is
* detected, sacrificing the compactness guarantee in very rare cases in exchange for much
* more reliable worst-case behavior.
* <li>null, if no entries have yet been added to the map
* </ul>
*/
private transient @Nullable Object table;
/**
* Contains the logical entries, in the range of [0, size()). The high bits of each int are the
* part of the smeared hash of the key not covered by the hashtable mask, whereas the low bits are
* the "next" pointer (pointing to the next entry in the bucket chain), which will always be less
* than or equal to the hashtable mask.
*
* <pre>
* hash = aaaaaaaa
* mask = 00000fff
* next = 00000bbb
* entry = aaaaabbb
* </pre>
*
* <p>The pointers in [size(), entries.length) are all "null" (UNSET).
*/
@VisibleForTesting transient int @Nullable [] entries;
/**
* The keys of the entries in the map, in the range of [0, size()). The keys in [size(),
* keys.length) are all {@code null}.
*/
@VisibleForTesting transient @Nullable Object @Nullable [] keys;
/**
* The values of the entries in the map, in the range of [0, size()). The values in [size(),
* values.length) are all {@code null}.
*/
@VisibleForTesting transient @Nullable Object @Nullable [] values;
/**
* Keeps track of metadata like the number of hash table bits and modifications of this data
* structure (to make it possible to throw ConcurrentModificationException in the iterator). Note
* that we choose not to make this volatile, so we do less of a "best effort" to track such
* errors, for better performance.
*
* <p>For a new instance, where the arrays above have not yet been allocated, the value of {@code
* metadata} is the size that the arrays should be allocated with. Once the arrays have been
* allocated, the value of {@code metadata} combines the number of bits in the "short hash", in
* its bottom {@value CompactHashing#HASH_TABLE_BITS_MAX_BITS} bits, with a modification count in
* the remaining bits that is used to detect concurrent modification during iteration.
*/
private transient int metadata;
/** The number of elements contained in the set. */
private transient int size;
/** Constructs a new empty instance of {@code CompactHashMap}. */
CompactHashMap() {
init(CompactHashing.DEFAULT_SIZE);
}
/**
* Constructs a new instance of {@code CompactHashMap} with the specified capacity.
*
* @param expectedSize the initial capacity of this {@code CompactHashMap}.
*/
CompactHashMap(int expectedSize) {
init(expectedSize);
}
/** Pseudoconstructor for serialization support. */
void init(int expectedSize) {
Preconditions.checkArgument(expectedSize >= 0, "Expected size must be >= 0");
// Save expectedSize for use in allocArrays()
this.metadata = Ints.constrainToRange(expectedSize, 1, CompactHashing.MAX_SIZE);
}
/** Returns whether arrays need to be allocated. */
boolean needsAllocArrays() {
return table == null;
}
/** Handle lazy allocation of arrays. */
@CanIgnoreReturnValue
int allocArrays() {
Preconditions.checkState(needsAllocArrays(), "Arrays already allocated");
int expectedSize = metadata;
int buckets = CompactHashing.tableSize(expectedSize);
this.table = CompactHashing.createTable(buckets);
setHashTableMask(buckets - 1);
this.entries = new int[expectedSize];
this.keys = new Object[expectedSize];
this.values = new Object[expectedSize];
return expectedSize;
}
@SuppressWarnings("unchecked")
@VisibleForTesting
@Nullable Map<K, V> delegateOrNull() {
if (table instanceof Map) {
return (Map<K, V>) table;
}
return null;
}
Map<K, V> createHashFloodingResistantDelegate(int tableSize) {
return new LinkedHashMap<>(tableSize, 1.0f);
}
@CanIgnoreReturnValue
Map<K, V> convertToHashFloodingResistantImplementation() {
Map<K, V> newDelegate = createHashFloodingResistantDelegate(hashTableMask() + 1);
for (int i = firstEntryIndex(); i >= 0; i = getSuccessor(i)) {
newDelegate.put(key(i), value(i));
}
this.table = newDelegate;
this.entries = null;
this.keys = null;
this.values = null;
incrementModCount();
return newDelegate;
}
/** Stores the hash table mask as the number of bits needed to represent an index. */
private void setHashTableMask(int mask) {
int hashTableBits = Integer.SIZE - Integer.numberOfLeadingZeros(mask);
metadata =
CompactHashing.maskCombine(metadata, hashTableBits, CompactHashing.HASH_TABLE_BITS_MASK);
}
/** Gets the hash table mask using the stored number of hash table bits. */
private int hashTableMask() {
return (1 << (metadata & CompactHashing.HASH_TABLE_BITS_MASK)) - 1;
}
void incrementModCount() {
metadata += CompactHashing.MODIFICATION_COUNT_INCREMENT;
}
/**
* Mark an access of the specified entry. Used only in {@code CompactLinkedHashMap} for LRU
* ordering.
*/
void accessEntry(int index) {
// no-op by default
}
@CanIgnoreReturnValue
@Override
public @Nullable V put(@ParametricNullness K key, @ParametricNullness V value) {
if (needsAllocArrays()) {
allocArrays();
}
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.put(key, value);
}
int[] entries = requireEntries();
@Nullable Object[] keys = requireKeys();
@Nullable Object[] values = requireValues();
int newEntryIndex = this.size; // current size, and pointer to the entry to be appended
int newSize = newEntryIndex + 1;
int hash = smearedHash(key);
int mask = hashTableMask();
int tableIndex = hash & mask;
int next = CompactHashing.tableGet(requireTable(), tableIndex);
if (next == UNSET) { // uninitialized bucket
if (newSize > mask) {
// Resize and add new entry
mask = resizeTable(mask, CompactHashing.newCapacity(mask), hash, newEntryIndex);
} else {
CompactHashing.tableSet(requireTable(), tableIndex, newEntryIndex + 1);
}
} else {
int entryIndex;
int entry;
int hashPrefix = CompactHashing.getHashPrefix(hash, mask);
int bucketLength = 0;
do {
entryIndex = next - 1;
entry = entries[entryIndex];
if (CompactHashing.getHashPrefix(entry, mask) == hashPrefix
&& Objects.equals(key, keys[entryIndex])) {
@SuppressWarnings("unchecked") // known to be a V
V oldValue = (V) values[entryIndex];
values[entryIndex] = value;
accessEntry(entryIndex);
return oldValue;
}
next = CompactHashing.getNext(entry, mask);
bucketLength++;
} while (next != UNSET);
if (bucketLength >= MAX_HASH_BUCKET_LENGTH) {
return convertToHashFloodingResistantImplementation().put(key, value);
}
if (newSize > mask) {
// Resize and add new entry
mask = resizeTable(mask, CompactHashing.newCapacity(mask), hash, newEntryIndex);
} else {
entries[entryIndex] = CompactHashing.maskCombine(entry, newEntryIndex + 1, mask);
}
}
resizeMeMaybe(newSize);
insertEntry(newEntryIndex, key, value, hash, mask);
this.size = newSize;
incrementModCount();
return null;
}
/**
* Creates a fresh entry with the specified object at the specified position in the entry arrays.
*/
void insertEntry(
int entryIndex, @ParametricNullness K key, @ParametricNullness V value, int hash, int mask) {
this.setEntry(entryIndex, CompactHashing.maskCombine(hash, UNSET, mask));
this.setKey(entryIndex, key);
this.setValue(entryIndex, value);
}
/** Resizes the entries storage if necessary. */
private void resizeMeMaybe(int newSize) {
int entriesSize = requireEntries().length;
if (newSize > entriesSize) {
// 1.5x but round up to nearest odd (this is optimal for memory consumption on Android)
int newCapacity = min(CompactHashing.MAX_SIZE, (entriesSize + max(1, entriesSize >>> 1)) | 1);
if (newCapacity != entriesSize) {
resizeEntries(newCapacity);
}
}
}
/**
* Resizes the internal entries array to the specified capacity, which may be greater or less than
* the current capacity.
*/
void resizeEntries(int newCapacity) {
this.entries = Arrays.copyOf(requireEntries(), newCapacity);
this.keys = Arrays.copyOf(requireKeys(), newCapacity);
this.values = Arrays.copyOf(requireValues(), newCapacity);
}
@CanIgnoreReturnValue
private int resizeTable(int oldMask, int newCapacity, int targetHash, int targetEntryIndex) {
Object newTable = CompactHashing.createTable(newCapacity);
int newMask = newCapacity - 1;
if (targetEntryIndex != UNSET) {
// Add target first; it must be last in the chain because its entry hasn't yet been created
CompactHashing.tableSet(newTable, targetHash & newMask, targetEntryIndex + 1);
}
Object oldTable = requireTable();
int[] entries = requireEntries();
// Loop over `oldTable` to construct its replacement, ``newTable`. The entries do not move, so
// the `keys` and `values` arrays do not need to change. But because the "short hash" now has a
// different number of bits, we must rewrite each element of `entries` so that its contribution
// to the full hashcode reflects the change, and so that its `next` link corresponds to the new
// linked list of entries with the new short hash.
for (int oldTableIndex = 0; oldTableIndex <= oldMask; oldTableIndex++) {
int oldNext = CompactHashing.tableGet(oldTable, oldTableIndex);
// Each element of `oldTable` is the head of a (possibly empty) linked list of elements in
// `entries`. The `oldNext` loop is going to traverse that linked list.
// We need to rewrite the `next` link of each of the elements so that it is in the appropriate
// linked list starting from `newTable`. In general, each element from the old linked list
// belongs to a different linked list from `newTable`. We insert each element in turn at the
// head of its appropriate `newTable` linked list.
while (oldNext != UNSET) {
int entryIndex = oldNext - 1;
int oldEntry = entries[entryIndex];
// Rebuild the full 32-bit hash using entry hashPrefix and oldTableIndex ("hashSuffix").
int hash = CompactHashing.getHashPrefix(oldEntry, oldMask) | oldTableIndex;
int newTableIndex = hash & newMask;
int newNext = CompactHashing.tableGet(newTable, newTableIndex);
CompactHashing.tableSet(newTable, newTableIndex, oldNext);
entries[entryIndex] = CompactHashing.maskCombine(hash, newNext, newMask);
oldNext = CompactHashing.getNext(oldEntry, oldMask);
}
}
this.table = newTable;
setHashTableMask(newMask);
return newMask;
}
private int indexOf(@Nullable Object key) {
if (needsAllocArrays()) {
return -1;
}
int hash = smearedHash(key);
int mask = hashTableMask();
int next = CompactHashing.tableGet(requireTable(), hash & mask);
if (next == UNSET) {
return -1;
}
int hashPrefix = CompactHashing.getHashPrefix(hash, mask);
do {
int entryIndex = next - 1;
int entry = entry(entryIndex);
if (CompactHashing.getHashPrefix(entry, mask) == hashPrefix
&& Objects.equals(key, key(entryIndex))) {
return entryIndex;
}
next = CompactHashing.getNext(entry, mask);
} while (next != UNSET);
return -1;
}
@Override
public boolean containsKey(@Nullable Object key) {
Map<K, V> delegate = delegateOrNull();
return (delegate != null) ? delegate.containsKey(key) : indexOf(key) != -1;
}
@Override
public @Nullable V get(@Nullable Object key) {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.get(key);
}
int index = indexOf(key);
if (index == -1) {
return null;
}
accessEntry(index);
return value(index);
}
@CanIgnoreReturnValue
@SuppressWarnings("unchecked") // known to be a V
@Override
public @Nullable V remove(@Nullable Object key) {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.remove(key);
}
Object oldValue = removeHelper(key);
return (oldValue == NOT_FOUND) ? null : (V) oldValue;
}
private @Nullable Object removeHelper(@Nullable Object key) {
if (needsAllocArrays()) {
return NOT_FOUND;
}
int mask = hashTableMask();
int index =
CompactHashing.remove(
key,
/* value= */ null,
mask,
requireTable(),
requireEntries(),
requireKeys(),
/* values= */ null);
if (index == -1) {
return NOT_FOUND;
}
Object oldValue = value(index);
moveLastEntry(index, mask);
size--;
incrementModCount();
return oldValue;
}
/**
* Moves the last entry in the entry array into {@code dstIndex}, and nulls out its old position.
*/
void moveLastEntry(int dstIndex, int mask) {
Object table = requireTable();
int[] entries = requireEntries();
@Nullable Object[] keys = requireKeys();
@Nullable Object[] values = requireValues();
int srcIndex = size() - 1;
if (dstIndex < srcIndex) {
// move last entry to deleted spot
Object key = keys[srcIndex];
keys[dstIndex] = key;
values[dstIndex] = values[srcIndex];
keys[srcIndex] = null;
values[srcIndex] = null;
// move the last entry to the removed spot, just like we moved the element
entries[dstIndex] = entries[srcIndex];
entries[srcIndex] = 0;
// also need to update whoever's "next" pointer was pointing to the last entry place
int tableIndex = smearedHash(key) & mask;
int next = CompactHashing.tableGet(table, tableIndex);
int srcNext = srcIndex + 1;
if (next == srcNext) {
// we need to update the root pointer
CompactHashing.tableSet(table, tableIndex, dstIndex + 1);
} else {
// we need to update a pointer in an entry
int entryIndex;
int entry;
do {
entryIndex = next - 1;
entry = entries[entryIndex];
next = CompactHashing.getNext(entry, mask);
} while (next != srcNext);
// here, entries[entryIndex] points to the old entry location; update it
entries[entryIndex] = CompactHashing.maskCombine(entry, dstIndex + 1, mask);
}
} else {
keys[dstIndex] = null;
values[dstIndex] = null;
entries[dstIndex] = 0;
}
}
int firstEntryIndex() {
return isEmpty() ? -1 : 0;
}
int getSuccessor(int entryIndex) {
return (entryIndex + 1 < size) ? entryIndex + 1 : -1;
}
/**
* Updates the index an iterator is pointing to after a call to remove: returns the index of the
* entry that should be looked at after a removal on indexRemoved, with indexBeforeRemove as the
* index that *was* the next entry that would be looked at.
*/
int adjustAfterRemove(int indexBeforeRemove, @SuppressWarnings("unused") int indexRemoved) {
return indexBeforeRemove - 1;
}
private abstract class Itr<T extends @Nullable Object> implements Iterator<T> {
int expectedMetadata = metadata;
int currentIndex = firstEntryIndex();
int indexToRemove = -1;
@Override
public boolean hasNext() {
return currentIndex >= 0;
}
@ParametricNullness
abstract T getOutput(int entry);
@Override
@ParametricNullness
public T next() {
checkForConcurrentModification();
if (!hasNext()) {
throw new NoSuchElementException();
}
indexToRemove = currentIndex;
T result = getOutput(currentIndex);
currentIndex = getSuccessor(currentIndex);
return result;
}
@Override
public void remove() {
checkForConcurrentModification();
checkRemove(indexToRemove >= 0);
incrementExpectedModCount();
CompactHashMap.this.remove(key(indexToRemove));
currentIndex = adjustAfterRemove(currentIndex, indexToRemove);
indexToRemove = -1;
}
void incrementExpectedModCount() {
expectedMetadata += CompactHashing.MODIFICATION_COUNT_INCREMENT;
}
private void checkForConcurrentModification() {
if (metadata != expectedMetadata) {
throw new ConcurrentModificationException();
}
}
}
@LazyInit private transient @Nullable Set<K> keySetView;
@Override
public Set<K> keySet() {
return (keySetView == null) ? keySetView = createKeySet() : keySetView;
}
Set<K> createKeySet() {
return new KeySetView();
}
@WeakOuter
private final class KeySetView extends AbstractSet<K> {
@Override
public int size() {
return CompactHashMap.this.size();
}
@Override
public boolean contains(@Nullable Object o) {
return CompactHashMap.this.containsKey(o);
}
@Override
public boolean remove(@Nullable Object o) {
Map<K, V> delegate = delegateOrNull();
return (delegate != null)
? delegate.keySet().remove(o)
: CompactHashMap.this.removeHelper(o) != NOT_FOUND;
}
@Override
public Iterator<K> iterator() {
return keySetIterator();
}
@Override
public void clear() {
CompactHashMap.this.clear();
}
}
Iterator<K> keySetIterator() {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.keySet().iterator();
}
return new Itr<K>() {
@Override
@ParametricNullness
K getOutput(int entry) {
return key(entry);
}
};
}
@LazyInit private transient @Nullable Set<Entry<K, V>> entrySetView;
@Override
public Set<Entry<K, V>> entrySet() {
return (entrySetView == null) ? entrySetView = createEntrySet() : entrySetView;
}
Set<Entry<K, V>> createEntrySet() {
return new EntrySetView();
}
@WeakOuter
private final class EntrySetView extends AbstractSet<Entry<K, V>> {
@Override
public int size() {
return CompactHashMap.this.size();
}
@Override
public void clear() {
CompactHashMap.this.clear();
}
@Override
public Iterator<Entry<K, V>> iterator() {
return entrySetIterator();
}
@Override
public boolean contains(@Nullable Object o) {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.entrySet().contains(o);
} else if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
int index = indexOf(entry.getKey());
return index != -1 && Objects.equals(value(index), entry.getValue());
}
return false;
}
@Override
public boolean remove(@Nullable Object o) {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.entrySet().remove(o);
} else if (o instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) o;
if (needsAllocArrays()) {
return false;
}
int mask = hashTableMask();
int index =
CompactHashing.remove(
entry.getKey(),
entry.getValue(),
mask,
requireTable(),
requireEntries(),
requireKeys(),
requireValues());
if (index == -1) {
return false;
}
moveLastEntry(index, mask);
size--;
incrementModCount();
return true;
}
return false;
}
}
Iterator<Entry<K, V>> entrySetIterator() {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.entrySet().iterator();
}
return new Itr<Entry<K, V>>() {
@Override
Entry<K, V> getOutput(int entry) {
return new MapEntry(entry);
}
};
}
final class MapEntry extends AbstractMapEntry<K, V> {
@ParametricNullness private final K key;
private int lastKnownIndex;
MapEntry(int index) {
this.key = key(index);
this.lastKnownIndex = index;
}
@Override
@ParametricNullness
public K getKey() {
return key;
}
private void updateLastKnownIndex() {
if (lastKnownIndex == -1
|| lastKnownIndex >= size()
|| !Objects.equals(key, key(lastKnownIndex))) {
lastKnownIndex = indexOf(key);
}
}
@Override
@ParametricNullness
public V getValue() {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
/*
* The cast is safe because the entry is present in the map. Or, if it has been removed by a
* concurrent modification, behavior is undefined.
*/
return uncheckedCastNullableTToT(delegate.get(key));
}
updateLastKnownIndex();
/*
* If the entry has been removed from the map, we return null, even though that might not be a
* valid value. That's the best we can do, short of holding a reference to the most recently
* seen value. And while we *could* do that, we aren't required to: Map.Entry explicitly says
* that behavior is undefined when the backing map is modified through another API. (It even
* permits us to throw IllegalStateException. Maybe we should have done that, but we probably
* shouldn't change now for fear of breaking people.)
*/
return (lastKnownIndex == -1) ? unsafeNull() : value(lastKnownIndex);
}
@Override
@ParametricNullness
public V setValue(@ParametricNullness V value) {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return uncheckedCastNullableTToT(delegate.put(key, value)); // See discussion in getValue().
}
updateLastKnownIndex();
if (lastKnownIndex == -1) {
put(key, value);
return unsafeNull(); // See discussion in getValue().
} else {
V old = value(lastKnownIndex);
CompactHashMap.this.setValue(lastKnownIndex, value);
return old;
}
}
}
@Override
public int size() {
Map<K, V> delegate = delegateOrNull();
return (delegate != null) ? delegate.size() : size;
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public boolean containsValue(@Nullable Object value) {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.containsValue(value);
}
for (int i = 0; i < size; i++) {
if (Objects.equals(value, value(i))) {
return true;
}
}
return false;
}
@LazyInit private transient @Nullable Collection<V> valuesView;
@Override
public Collection<V> values() {
return (valuesView == null) ? valuesView = createValues() : valuesView;
}
Collection<V> createValues() {
return new ValuesView();
}
@WeakOuter
private final class ValuesView extends AbstractCollection<V> {
@Override
public int size() {
return CompactHashMap.this.size();
}
@Override
public void clear() {
CompactHashMap.this.clear();
}
@Override
public Iterator<V> iterator() {
return valuesIterator();
}
}
Iterator<V> valuesIterator() {
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
return delegate.values().iterator();
}
return new Itr<V>() {
@Override
@ParametricNullness
V getOutput(int entry) {
return value(entry);
}
};
}
/**
* Ensures that this {@code CompactHashMap} has the smallest representation in memory, given its
* current size.
*/
public void trimToSize() {
if (needsAllocArrays()) {
return;
}
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
Map<K, V> newDelegate = createHashFloodingResistantDelegate(size());
newDelegate.putAll(delegate);
this.table = newDelegate;
return;
}
int size = this.size;
if (size < requireEntries().length) {
resizeEntries(size);
}
int minimumTableSize = CompactHashing.tableSize(size);
int mask = hashTableMask();
if (minimumTableSize < mask) { // smaller table size will always be less than current mask
resizeTable(mask, minimumTableSize, UNSET, UNSET);
}
}
@Override
public void clear() {
if (needsAllocArrays()) {
return;
}
incrementModCount();
Map<K, V> delegate = delegateOrNull();
if (delegate != null) {
metadata =
Ints.constrainToRange(size(), CompactHashing.DEFAULT_SIZE, CompactHashing.MAX_SIZE);
delegate.clear(); // invalidate any iterators left over!
table = null;
size = 0;
} else {
Arrays.fill(requireKeys(), 0, size, null);
Arrays.fill(requireValues(), 0, size, null);
CompactHashing.tableClear(requireTable());
Arrays.fill(requireEntries(), 0, size, 0);
this.size = 0;
}
}
@J2ktIncompatible
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(size());
Iterator<Entry<K, V>> entryIterator = entrySetIterator();
while (entryIterator.hasNext()) {
Entry<K, V> e = entryIterator.next();
stream.writeObject(e.getKey());
stream.writeObject(e.getValue());
}
}
@SuppressWarnings("unchecked")
@J2ktIncompatible
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int elementCount = stream.readInt();
if (elementCount < 0) {
throw new InvalidObjectException("Invalid size: " + elementCount);
}
init(elementCount);
for (int i = 0; i < elementCount; i++) {
K key = (K) stream.readObject();
V value = (V) stream.readObject();
put(key, value);
}
}
/*
* The following methods are safe to call as long as both of the following hold:
*
* - allocArrays() has been called. Callers can confirm this by checking needsAllocArrays().
*
* - The map has not switched to delegating to a java.util implementation to mitigate hash
* flooding. Callers can confirm this by null-checking delegateOrNull().
*
* In an ideal world, we would document why we know those things are true every time we call these
* methods. But that is a bit too painful....
*/
private Object requireTable() {
return requireNonNull(table);
}
private int[] requireEntries() {
return requireNonNull(entries);
}
private @Nullable Object[] requireKeys() {
return requireNonNull(keys);
}
private @Nullable Object[] requireValues() {
return requireNonNull(values);
}
/*
* The following methods are safe to call as long as the conditions in the *previous* comment are
* met *and* the index is less than size().
*
* (The above explains when these methods are safe from a `nullness` perspective. From an
* `unchecked` perspective, they're safe because we put only K/V elements into each array.)
*/
@SuppressWarnings("unchecked")
private K key(int i) {
return (K) requireKeys()[i];
}
@SuppressWarnings("unchecked")
private V value(int i) {
return (V) requireValues()[i];
}
private int entry(int i) {
return requireEntries()[i];
}
private void setKey(int i, K key) {
requireKeys()[i] = key;
}
private void setValue(int i, V value) {
requireValues()[i] = value;
}
private void setEntry(int i, int value) {
requireEntries()[i] = value;
}
}
|
googleapis/google-cloud-java | 36,423 | java-trace/proto-google-cloud-trace-v1/src/main/java/com/google/devtools/cloudtrace/v1/ListTracesResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/devtools/cloudtrace/v1/trace.proto
// Protobuf Java Version: 3.25.8
package com.google.devtools.cloudtrace.v1;
/**
*
*
* <pre>
* The response message for the `ListTraces` method.
* </pre>
*
* Protobuf type {@code google.devtools.cloudtrace.v1.ListTracesResponse}
*/
public final class ListTracesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.devtools.cloudtrace.v1.ListTracesResponse)
ListTracesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListTracesResponse.newBuilder() to construct.
private ListTracesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListTracesResponse() {
traces_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListTracesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.devtools.cloudtrace.v1.TraceProto
.internal_static_google_devtools_cloudtrace_v1_ListTracesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.devtools.cloudtrace.v1.TraceProto
.internal_static_google_devtools_cloudtrace_v1_ListTracesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.devtools.cloudtrace.v1.ListTracesResponse.class,
com.google.devtools.cloudtrace.v1.ListTracesResponse.Builder.class);
}
public static final int TRACES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.devtools.cloudtrace.v1.Trace> traces_;
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.devtools.cloudtrace.v1.Trace> getTracesList() {
return traces_;
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.devtools.cloudtrace.v1.TraceOrBuilder>
getTracesOrBuilderList() {
return traces_;
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
@java.lang.Override
public int getTracesCount() {
return traces_.size();
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
@java.lang.Override
public com.google.devtools.cloudtrace.v1.Trace getTraces(int index) {
return traces_.get(index);
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
@java.lang.Override
public com.google.devtools.cloudtrace.v1.TraceOrBuilder getTracesOrBuilder(int index) {
return traces_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* If defined, indicates that there are more traces that match the request
* and that this value should be passed to the next request to continue
* retrieving additional traces.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* If defined, indicates that there are more traces that match the request
* and that this value should be passed to the next request to continue
* retrieving additional traces.
* </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 < traces_.size(); i++) {
output.writeMessage(1, traces_.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 < traces_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, traces_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.devtools.cloudtrace.v1.ListTracesResponse)) {
return super.equals(obj);
}
com.google.devtools.cloudtrace.v1.ListTracesResponse other =
(com.google.devtools.cloudtrace.v1.ListTracesResponse) obj;
if (!getTracesList().equals(other.getTracesList())) 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 (getTracesCount() > 0) {
hash = (37 * hash) + TRACES_FIELD_NUMBER;
hash = (53 * hash) + getTracesList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.devtools.cloudtrace.v1.ListTracesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.cloudtrace.v1.ListTracesResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.devtools.cloudtrace.v1.ListTracesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.cloudtrace.v1.ListTracesResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.devtools.cloudtrace.v1.ListTracesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.cloudtrace.v1.ListTracesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.devtools.cloudtrace.v1.ListTracesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.devtools.cloudtrace.v1.ListTracesResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.devtools.cloudtrace.v1.ListTracesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.devtools.cloudtrace.v1.ListTracesResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.devtools.cloudtrace.v1.ListTracesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.devtools.cloudtrace.v1.ListTracesResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.devtools.cloudtrace.v1.ListTracesResponse 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 the `ListTraces` method.
* </pre>
*
* Protobuf type {@code google.devtools.cloudtrace.v1.ListTracesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.devtools.cloudtrace.v1.ListTracesResponse)
com.google.devtools.cloudtrace.v1.ListTracesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.devtools.cloudtrace.v1.TraceProto
.internal_static_google_devtools_cloudtrace_v1_ListTracesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.devtools.cloudtrace.v1.TraceProto
.internal_static_google_devtools_cloudtrace_v1_ListTracesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.devtools.cloudtrace.v1.ListTracesResponse.class,
com.google.devtools.cloudtrace.v1.ListTracesResponse.Builder.class);
}
// Construct using com.google.devtools.cloudtrace.v1.ListTracesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (tracesBuilder_ == null) {
traces_ = java.util.Collections.emptyList();
} else {
traces_ = null;
tracesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.devtools.cloudtrace.v1.TraceProto
.internal_static_google_devtools_cloudtrace_v1_ListTracesResponse_descriptor;
}
@java.lang.Override
public com.google.devtools.cloudtrace.v1.ListTracesResponse getDefaultInstanceForType() {
return com.google.devtools.cloudtrace.v1.ListTracesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.devtools.cloudtrace.v1.ListTracesResponse build() {
com.google.devtools.cloudtrace.v1.ListTracesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.devtools.cloudtrace.v1.ListTracesResponse buildPartial() {
com.google.devtools.cloudtrace.v1.ListTracesResponse result =
new com.google.devtools.cloudtrace.v1.ListTracesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.devtools.cloudtrace.v1.ListTracesResponse result) {
if (tracesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
traces_ = java.util.Collections.unmodifiableList(traces_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.traces_ = traces_;
} else {
result.traces_ = tracesBuilder_.build();
}
}
private void buildPartial0(com.google.devtools.cloudtrace.v1.ListTracesResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.devtools.cloudtrace.v1.ListTracesResponse) {
return mergeFrom((com.google.devtools.cloudtrace.v1.ListTracesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.devtools.cloudtrace.v1.ListTracesResponse other) {
if (other == com.google.devtools.cloudtrace.v1.ListTracesResponse.getDefaultInstance())
return this;
if (tracesBuilder_ == null) {
if (!other.traces_.isEmpty()) {
if (traces_.isEmpty()) {
traces_ = other.traces_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureTracesIsMutable();
traces_.addAll(other.traces_);
}
onChanged();
}
} else {
if (!other.traces_.isEmpty()) {
if (tracesBuilder_.isEmpty()) {
tracesBuilder_.dispose();
tracesBuilder_ = null;
traces_ = other.traces_;
bitField0_ = (bitField0_ & ~0x00000001);
tracesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getTracesFieldBuilder()
: null;
} else {
tracesBuilder_.addAllMessages(other.traces_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.devtools.cloudtrace.v1.Trace m =
input.readMessage(
com.google.devtools.cloudtrace.v1.Trace.parser(), extensionRegistry);
if (tracesBuilder_ == null) {
ensureTracesIsMutable();
traces_.add(m);
} else {
tracesBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.devtools.cloudtrace.v1.Trace> traces_ =
java.util.Collections.emptyList();
private void ensureTracesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
traces_ = new java.util.ArrayList<com.google.devtools.cloudtrace.v1.Trace>(traces_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.devtools.cloudtrace.v1.Trace,
com.google.devtools.cloudtrace.v1.Trace.Builder,
com.google.devtools.cloudtrace.v1.TraceOrBuilder>
tracesBuilder_;
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public java.util.List<com.google.devtools.cloudtrace.v1.Trace> getTracesList() {
if (tracesBuilder_ == null) {
return java.util.Collections.unmodifiableList(traces_);
} else {
return tracesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public int getTracesCount() {
if (tracesBuilder_ == null) {
return traces_.size();
} else {
return tracesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public com.google.devtools.cloudtrace.v1.Trace getTraces(int index) {
if (tracesBuilder_ == null) {
return traces_.get(index);
} else {
return tracesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public Builder setTraces(int index, com.google.devtools.cloudtrace.v1.Trace value) {
if (tracesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTracesIsMutable();
traces_.set(index, value);
onChanged();
} else {
tracesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public Builder setTraces(
int index, com.google.devtools.cloudtrace.v1.Trace.Builder builderForValue) {
if (tracesBuilder_ == null) {
ensureTracesIsMutable();
traces_.set(index, builderForValue.build());
onChanged();
} else {
tracesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public Builder addTraces(com.google.devtools.cloudtrace.v1.Trace value) {
if (tracesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTracesIsMutable();
traces_.add(value);
onChanged();
} else {
tracesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public Builder addTraces(int index, com.google.devtools.cloudtrace.v1.Trace value) {
if (tracesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTracesIsMutable();
traces_.add(index, value);
onChanged();
} else {
tracesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public Builder addTraces(com.google.devtools.cloudtrace.v1.Trace.Builder builderForValue) {
if (tracesBuilder_ == null) {
ensureTracesIsMutable();
traces_.add(builderForValue.build());
onChanged();
} else {
tracesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public Builder addTraces(
int index, com.google.devtools.cloudtrace.v1.Trace.Builder builderForValue) {
if (tracesBuilder_ == null) {
ensureTracesIsMutable();
traces_.add(index, builderForValue.build());
onChanged();
} else {
tracesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public Builder addAllTraces(
java.lang.Iterable<? extends com.google.devtools.cloudtrace.v1.Trace> values) {
if (tracesBuilder_ == null) {
ensureTracesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, traces_);
onChanged();
} else {
tracesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public Builder clearTraces() {
if (tracesBuilder_ == null) {
traces_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
tracesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public Builder removeTraces(int index) {
if (tracesBuilder_ == null) {
ensureTracesIsMutable();
traces_.remove(index);
onChanged();
} else {
tracesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public com.google.devtools.cloudtrace.v1.Trace.Builder getTracesBuilder(int index) {
return getTracesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public com.google.devtools.cloudtrace.v1.TraceOrBuilder getTracesOrBuilder(int index) {
if (tracesBuilder_ == null) {
return traces_.get(index);
} else {
return tracesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public java.util.List<? extends com.google.devtools.cloudtrace.v1.TraceOrBuilder>
getTracesOrBuilderList() {
if (tracesBuilder_ != null) {
return tracesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(traces_);
}
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public com.google.devtools.cloudtrace.v1.Trace.Builder addTracesBuilder() {
return getTracesFieldBuilder()
.addBuilder(com.google.devtools.cloudtrace.v1.Trace.getDefaultInstance());
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public com.google.devtools.cloudtrace.v1.Trace.Builder addTracesBuilder(int index) {
return getTracesFieldBuilder()
.addBuilder(index, com.google.devtools.cloudtrace.v1.Trace.getDefaultInstance());
}
/**
*
*
* <pre>
* List of trace records as specified by the view parameter.
* </pre>
*
* <code>repeated .google.devtools.cloudtrace.v1.Trace traces = 1;</code>
*/
public java.util.List<com.google.devtools.cloudtrace.v1.Trace.Builder> getTracesBuilderList() {
return getTracesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.devtools.cloudtrace.v1.Trace,
com.google.devtools.cloudtrace.v1.Trace.Builder,
com.google.devtools.cloudtrace.v1.TraceOrBuilder>
getTracesFieldBuilder() {
if (tracesBuilder_ == null) {
tracesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.devtools.cloudtrace.v1.Trace,
com.google.devtools.cloudtrace.v1.Trace.Builder,
com.google.devtools.cloudtrace.v1.TraceOrBuilder>(
traces_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
traces_ = null;
}
return tracesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* If defined, indicates that there are more traces that match the request
* and that this value should be passed to the next request to continue
* retrieving additional traces.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* If defined, indicates that there are more traces that match the request
* and that this value should be passed to the next request to continue
* retrieving additional traces.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* If defined, indicates that there are more traces that match the request
* and that this value should be passed to the next request to continue
* retrieving additional traces.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* If defined, indicates that there are more traces that match the request
* and that this value should be passed to the next request to continue
* retrieving additional traces.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* If defined, indicates that there are more traces that match the request
* and that this value should be passed to the next request to continue
* retrieving additional traces.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.devtools.cloudtrace.v1.ListTracesResponse)
}
// @@protoc_insertion_point(class_scope:google.devtools.cloudtrace.v1.ListTracesResponse)
private static final com.google.devtools.cloudtrace.v1.ListTracesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.devtools.cloudtrace.v1.ListTracesResponse();
}
public static com.google.devtools.cloudtrace.v1.ListTracesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListTracesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListTracesResponse>() {
@java.lang.Override
public ListTracesResponse 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<ListTracesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListTracesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.devtools.cloudtrace.v1.ListTracesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/drill | 36,572 | exec/vector/src/main/codegen/templates/VariableLengthVectors.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.
*/
import java.lang.Override;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Set;
import org.apache.drill.common.exceptions.DrillRuntimeException;
import org.apache.drill.exec.exception.OutOfMemoryException;
import org.apache.drill.exec.memory.AllocationManager.BufferLedger;
import org.apache.drill.exec.vector.BaseDataValueVector;
import org.apache.drill.exec.vector.BaseValueVector;
import org.apache.drill.exec.vector.VariableWidthVector;
<@pp.dropOutputFile />
<#list vv.types as type>
<#list type.minor as minor>
<#assign friendlyType = (minor.friendlyType!minor.boxedType!type.boxedType) />
<#if type.major == "VarLen">
<@pp.changeOutputFile name="/org/apache/drill/exec/vector/${minor.class}Vector.java" />
<#include "/@includes/license.ftl" />
package org.apache.drill.exec.vector;
<#include "/@includes/vv_imports.ftl" />
import java.util.Iterator;
import java.nio.ByteOrder;
/**
* ${minor.class}Vector implements a vector of variable width values. Elements in the vector
* are accessed by position from the logical start of the vector. A fixed width offsetVector
* is used to convert an element's position to it's offset from the start of the (0-based)
* DrillBuf. Size is inferred from adjacent elements.
* <ul>
* <li>The width of each element is ${type.width} byte(s). Note that the actual width is
* variable, this width is used as a guess for certain calculations.</li>
* <li>The equivalent Java primitive is '${minor.javaType!type.javaType}'<li>
* </ul>
* NB: this class is automatically generated from <tt>${.template_name}</tt>
* and <tt>ValueVectorTypes.tdd</tt> using FreeMarker.
*/
public final class ${minor.class}Vector extends BaseDataValueVector implements VariableWidthVector {
private static final int INITIAL_BYTE_COUNT = Math.min(INITIAL_VALUE_ALLOCATION * DEFAULT_RECORD_BYTE_COUNT, MAX_BUFFER_SIZE);
private final UInt${type.width}Vector offsetVector = new UInt${type.width}Vector(offsetsField, allocator);
private final FieldReader reader = new ${minor.class}ReaderImpl(${minor.class}Vector.this);
private final Accessor accessor;
private final Mutator mutator;
private int allocationSizeInBytes = INITIAL_BYTE_COUNT;
private int allocationMonitor = 0;
public ${minor.class}Vector(MaterializedField field, BufferAllocator allocator) {
super(field, allocator);
this.accessor = new Accessor();
this.mutator = new Mutator();
}
@Override
public FieldReader getReader(){
return reader;
}
@Override
public int getBufferSize(){
if (getAccessor().getValueCount() == 0) {
return 0;
}
return offsetVector.getBufferSize() + data.writerIndex();
}
@Override
public int getAllocatedSize() {
return offsetVector.getAllocatedSize() + data.capacity();
}
@Override
public int getBufferSizeFor(int valueCount) {
if (valueCount == 0) {
return 0;
}
int idx = offsetVector.getAccessor().get(valueCount);
return offsetVector.getBufferSizeFor(valueCount + 1) + idx;
}
@Override
public int getValueCapacity(){
return Math.max(offsetVector.getValueCapacity() - 1, 0);
}
@Override
public int getByteCapacity(){
return data.capacity();
}
/**
* Return the number of bytes contained in the current var len byte vector.
* TODO: Remove getVarByteLength with it's implementation after all client's are moved to using getCurrentSizeInBytes.
* It's kept as is to preserve backward compatibility
* @return
*/
@Override
public int getCurrentSizeInBytes() {
return getVarByteLength();
}
/**
* Return the number of bytes contained in the current var len byte vector.
* @return
*/
public int getVarByteLength(){
int valueCount = getAccessor().getValueCount();
if(valueCount == 0) {
return 0;
}
return offsetVector.getAccessor().get(valueCount);
}
@Override
public SerializedField getMetadata() {
return getMetadataBuilder()
.addChild(offsetVector.getMetadata())
.setValueCount(getAccessor().getValueCount())
.setBufferLength(getBufferSize())
.build();
}
@Override
public void load(SerializedField metadata, DrillBuf buffer) {
// the bits vector is the first child (the order in which the children are added in getMetadataBuilder is significant)
SerializedField offsetField = metadata.getChild(0);
offsetVector.load(offsetField, buffer);
int capacity = buffer.capacity();
int offsetsLength = offsetField.getBufferLength();
data = buffer.slice(offsetsLength, capacity - offsetsLength);
data.retain();
}
@Override
public void clear() {
super.clear();
offsetVector.clear();
}
@Override
public DrillBuf[] getBuffers(boolean clear) {
DrillBuf[] buffers = ObjectArrays.concat(offsetVector.getBuffers(false), super.getBuffers(false), DrillBuf.class);
if (clear) {
// does not make much sense but we have to retain buffers even when clear is set. refactor this interface.
for (DrillBuf buffer:buffers) {
buffer.retain(1);
}
clear();
}
return buffers;
}
public long getOffsetAddr(){
return offsetVector.getBuffer().memoryAddress();
}
@Override
public UInt${type.width}Vector getOffsetVector(){
return offsetVector;
}
@Override
public TransferPair getTransferPair(BufferAllocator allocator){
return new TransferImpl(getField(), allocator);
}
@Override
public TransferPair getTransferPair(String ref, BufferAllocator allocator){
return new TransferImpl(getField().withPath(ref), allocator);
}
@Override
public TransferPair makeTransferPair(ValueVector to) {
return new TransferImpl((${minor.class}Vector) to);
}
public void transferTo(${minor.class}Vector target){
target.clear();
this.offsetVector.transferTo(target.offsetVector);
target.data = data.transferOwnership(target.allocator).buffer;
target.data.writerIndex(data.writerIndex());
clear();
}
public void splitAndTransferTo(int startIndex, int length, ${minor.class}Vector target) {
UInt${type.width}Vector.Accessor offsetVectorAccessor = this.offsetVector.getAccessor();
int startPoint = offsetVectorAccessor.get(startIndex);
int sliceLength = offsetVectorAccessor.get(startIndex + length) - startPoint;
target.clear();
target.offsetVector.allocateNew(length + 1);
offsetVectorAccessor = this.offsetVector.getAccessor();
UInt4Vector.Mutator targetOffsetVectorMutator = target.offsetVector.getMutator();
for (int i = 0; i < length + 1; i++) {
targetOffsetVectorMutator.set(i, offsetVectorAccessor.get(startIndex + i) - startPoint);
}
target.data = data.slice(startPoint, sliceLength).transferOwnership(target.allocator).buffer;
target.getMutator().setValueCount(length);
}
protected void copyFrom(int fromIndex, int thisIndex, ${minor.class}Vector from){
UInt4Vector.Accessor fromOffsetVectorAccessor = from.offsetVector.getAccessor();
int start = fromOffsetVectorAccessor.get(fromIndex);
int end = fromOffsetVectorAccessor.get(fromIndex + 1);
int len = end - start;
int outputStart = offsetVector.data.get${(minor.javaType!type.javaType)?cap_first}(thisIndex * ${type.width});
from.data.getBytes(start, data, outputStart, len);
offsetVector.data.set${(minor.javaType!type.javaType)?cap_first}( (thisIndex+1) * ${type.width}, outputStart + len);
}
public void copyFromSafe(int fromIndex, int thisIndex, ${minor.class}Vector from){
UInt${type.width}Vector.Accessor fromOffsetVectorAccessor = from.offsetVector.getAccessor();
int start = fromOffsetVectorAccessor.get(fromIndex);
int end = fromOffsetVectorAccessor.get(fromIndex + 1);
int len = end - start;
int outputStart = offsetVector.getAccessor().get(thisIndex);
while(data.capacity() < outputStart + len) {
reAlloc();
}
offsetVector.getMutator().setSafe(thisIndex + 1, outputStart + len);
from.data.getBytes(start, data, outputStart, len);
}
@Override
public void copyEntry(int toIndex, ValueVector from, int fromIndex) {
copyFromSafe(fromIndex, toIndex, (${minor.class}Vector) from);
}
@Override
public void collectLedgers(Set<BufferLedger> ledgers) {
offsetVector.collectLedgers(ledgers);
super.collectLedgers(ledgers);
}
@Override
public int getPayloadByteCount(int valueCount) {
if (valueCount == 0) {
return 0;
}
// If 1 or more values, then the last value is set to
// the offset of the next value, which is the same as
// the length of existing values.
// In addition to the actual data bytes, we must also
// include the "overhead" bytes: the offset vector entries
// that accompany each column value. Thus, total payload
// size is consumed text bytes + consumed offset vector
// bytes.
return offsetVector.getAccessor().get(valueCount) +
offsetVector.getPayloadByteCount(valueCount);
}
private class TransferImpl implements TransferPair{
private final ${minor.class}Vector to;
public TransferImpl(MaterializedField field, BufferAllocator allocator){
to = new ${minor.class}Vector(field, allocator);
}
public TransferImpl(${minor.class}Vector to){
this.to = to;
}
@Override
public ${minor.class}Vector getTo(){
return to;
}
@Override
public void transfer(){
transferTo(to);
}
@Override
public void splitAndTransfer(int startIndex, int length) {
splitAndTransferTo(startIndex, length, to);
}
@Override
public void copyValueSafe(int fromIndex, int toIndex) {
to.copyFromSafe(fromIndex, toIndex, ${minor.class}Vector.this);
}
}
@Override
public void setInitialCapacity(int valueCount) {
long size = 1L * valueCount * ${type.width};
if (size > MAX_ALLOCATION_SIZE) {
throw new OversizedAllocationException("Requested amount of memory is more than max allowed allocation size");
}
allocationSizeInBytes = (int) size;
offsetVector.setInitialCapacity(valueCount + 1);
}
@Override
public void allocateNew() {
if(!allocateNewSafe()){
throw new OutOfMemoryException("Failure while allocating buffer.");
}
}
@Override
public boolean allocateNewSafe() {
long curAllocationSize = allocationSizeInBytes;
if (allocationMonitor > 10) {
curAllocationSize = Math.max(MIN_BYTE_COUNT, curAllocationSize / 2);
allocationMonitor = 0;
} else if (allocationMonitor < -2) {
curAllocationSize = curAllocationSize * 2L;
allocationMonitor = 0;
}
if (curAllocationSize > MAX_ALLOCATION_SIZE) {
return false;
}
clear();
/* Boolean to keep track if all the memory allocations were successful
* Used in the case of composite vectors when we need to allocate multiple
* buffers for multiple vectors. If one of the allocations failed we need to
* clear all the memory that we allocated
*/
try {
int requestedSize = (int)curAllocationSize;
data = allocator.buffer(requestedSize);
allocationSizeInBytes = requestedSize;
offsetVector.allocateNew();
} catch (OutOfMemoryException e) {
clear();
return false;
}
data.readerIndex(0);
offsetVector.zeroVector();
return true;
}
@Override
public void allocateNew(int totalBytes, int valueCount) {
clear();
assert totalBytes >= 0;
try {
data = allocator.buffer(totalBytes);
offsetVector.allocateNew(valueCount + 1);
} catch (RuntimeException e) {
clear();
throw e;
}
data.readerIndex(0);
allocationSizeInBytes = totalBytes;
offsetVector.zeroVector();
}
@Override
public void reset() {
allocationSizeInBytes = INITIAL_BYTE_COUNT;
allocationMonitor = 0;
data.readerIndex(0);
offsetVector.zeroVector();
super.reset();
}
public void reAlloc() {
long newAllocationSize = allocationSizeInBytes*2L;
// Some operations, such as Value Vector#exchange, can be change DrillBuf data field without corresponding allocation size changes.
// Check that the size of the allocation is sufficient to copy the old buffer.
while (newAllocationSize < data.capacity()) {
newAllocationSize *= 2L;
}
if (newAllocationSize > MAX_ALLOCATION_SIZE) {
throw new OversizedAllocationException("Unable to expand the buffer. Max allowed buffer size is reached.");
}
reallocRaw((int) newAllocationSize);
}
@Override
public DrillBuf reallocRaw(int newAllocationSize) {
DrillBuf newBuf = allocator.buffer(newAllocationSize);
newBuf.setBytes(0, data, 0, data.capacity());
data.release();
data = newBuf;
allocationSizeInBytes = newAllocationSize;
return data;
}
public void decrementAllocationMonitor() {
if (allocationMonitor > 0) {
allocationMonitor = 0;
}
--allocationMonitor;
}
private void incrementAllocationMonitor() {
++allocationMonitor;
}
@Override
public Accessor getAccessor(){
return accessor;
}
@Override
public Mutator getMutator() {
return mutator;
}
@Override
public void exchange(ValueVector other) {
super.exchange(other);
${minor.class}Vector target = (${minor.class}Vector) other;
offsetVector.exchange(target.offsetVector);
}
@Override
public void toNullable(ValueVector nullableVector) {
Nullable${minor.class}Vector dest = (Nullable${minor.class}Vector) nullableVector;
dest.getMutator().fromNotNullable(this);
}
public final class Accessor extends BaseValueVector.BaseAccessor implements VariableWidthAccessor {
final UInt${type.width}Vector.Accessor oAccessor = offsetVector.getAccessor();
public long getStartEnd(int index){
return oAccessor.getTwoAsLong(index);
}
public byte[] get(int index) {
assert index >= 0;
int startIdx = oAccessor.get(index);
int length = oAccessor.get(index + 1) - startIdx;
assert length >= 0;
byte[] dst = new byte[length];
data.getBytes(startIdx, dst, 0, length);
return dst;
}
@Override
public int getValueLength(int index) {
UInt${type.width}Vector.Accessor offsetVectorAccessor = offsetVector.getAccessor();
return offsetVectorAccessor.get(index + 1) - offsetVectorAccessor.get(index);
}
public void get(int index, ${minor.class}Holder holder){
holder.start = oAccessor.get(index);
holder.end = oAccessor.get(index + 1);
holder.buffer = data;
<#if minor.class.contains("Decimal")>
holder.scale = field.getScale();
holder.precision = field.getPrecision();
</#if>
}
public void get(int index, Nullable${minor.class}Holder holder){
holder.isSet = 1;
holder.start = oAccessor.get(index);
holder.end = oAccessor.get(index + 1);
holder.buffer = data;
<#if minor.class.contains("Decimal")>
holder.scale = field.getScale();
holder.precision = field.getPrecision();
</#if>
}
<#switch minor.class>
<#case "VarDecimal">
@Override
public ${friendlyType} getObject(int index) {
byte[] b = get(index);
BigInteger bi = b.length == 0 ? BigInteger.ZERO : new BigInteger(b);
BigDecimal bd = new BigDecimal(bi, getField().getScale());
return bd;
}
<#break>
<#case "VarChar">
@Override
public ${friendlyType} getObject(int index) {
Text text = new Text();
text.set(get(index));
return text;
}
<#break>
<#case "Var16Char">
@Override
public ${friendlyType} getObject(int index) {
return new String(get(index), StandardCharsets.UTF_16);
}
<#break>
<#default>
@Override
public ${friendlyType} getObject(int index) {
return get(index);
}
</#switch>
@Override
public int getValueCount() {
return Math.max(offsetVector.getAccessor().getValueCount()-1, 0);
}
@Override
public boolean isNull(int index){
return false;
}
public UInt${type.width}Vector getOffsetVector(){
return offsetVector;
}
}
/**
* <h4>Overview</h4>
* <p>
* Mutable${minor.class} implements a vector of variable width values. Elements in the vector
* are accessed by position from the logical start of the vector. A fixed width offsetVector
* is used to convert an element's position to it's offset from the start of the (0-based)
* DrillBuf. Size is inferred by adjacent elements.
* The width of each element is ${type.width} byte(s)
* The equivalent Java primitive is '${minor.javaType!type.javaType}'
*
* NB: this class is automatically generated from ValueVectorTypes.tdd using FreeMarker.
* </p>
* <h4>Contract</h4>
* <p>
* <ol>
* <li>
* <b>Supported Writes:</b> {@link VariableWidthVector}s do not support random writes. In contrast {@link org.apache.drill.exec.vector.FixedWidthVector}s do
* allow random writes but special care is needed.
* </li>
* <li>
* <b>Writing Values:</b> All set methods must be called with a consecutive sequence of indices. With a few exceptions:
* <ol>
* <li>You can update the last index you just set.</li>
* <li>You can reset a previous index (call it Idx), but you must assume all the data after Idx is corrupt. Also
* note that the memory consumed by data that came after Idx is not released.</li>
* </ol>
* </li>
* <li>
* <b>Setting Value Count:</b> Vectors aren't explicitly aware of how many values they contain. So you must keep track of the
* number of values you've written to the vector and once you are done writing to the vector you must call {@link Mutator#setValueCount(int)}.
* It is possible to trim the vector by setting the value count to be less than the number of values currently contained in the vector. Note the extra memory consumed in
* the data buffer is not freed when this is done.
* </li>
* <li>
* <b>Memory Allocation:</b> When setting a value at an index you must do one of the following to ensure you do not get an {@link IndexOutOfBoundsException}.
* <ol>
* <li>
* Allocate the exact amount of memory you need when using the {@link Mutator#set(int, byte[])} methods. If you do not
* manually allocate sufficient memory an {@link IndexOutOfBoundsException} can be thrown when the data buffer runs out of space.
* </li>
* <li>
* Or you can use the {@link Mutator#setSafe(int, byte[])} methods, which will automatically grow your data buffer to
* fit your data.
* </li>
* </ol>
* </li>
* <li>
* <b>Immutability:</b> Once a vector has been populated with data and {@link #setValueCount(int)} has been called, it should be considered immutable.
* </li>
* </ol>
* </p>
*/
public final class Mutator extends BaseValueVector.BaseMutator implements VariableWidthVector.VariableWidthMutator {
/**
* Set the variable length element at the specified index to the supplied byte array.
*
* @param index position of the bit to set
* @param bytes array of bytes to write
*/
protected void set(int index, byte[] bytes) {
assert index >= 0;
int currentOffset = offsetVector.getAccessor().get(index);
offsetVector.getMutator().set(index + 1, currentOffset + bytes.length);
data.setBytes(currentOffset, bytes, 0, bytes.length);
}
public void setSafe(int index, byte[] bytes) {
assert index >= 0;
int currentOffset = offsetVector.getAccessor().get(index);
while (data.capacity() < currentOffset + bytes.length) {
reAlloc();
}
offsetVector.getMutator().setSafe(index + 1, currentOffset + bytes.length);
data.setBytes(currentOffset, bytes, 0, bytes.length);
}
/**
* Copies the bulk input into this value vector and extends its capacity if necessary.
* @param input bulk input
*/
public <T extends VarLenBulkEntry> void setSafe(VarLenBulkInput<T> input) {
setSafe(input, null);
}
/**
* Copies the bulk input into this value vector and extends its capacity if necessary. The callback
* mechanism allows decoration as caller is invoked for each bulk entry.
*
* @param input bulk input
* @param callback a bulk input callback object (optional)
*/
public <T extends VarLenBulkEntry> void setSafe(VarLenBulkInput<T> input, VarLenBulkInput.BulkInputCallback<T> callback) {
// Let's allocate a buffered mutator to optimize memory copy performance
BufferedMutator bufferedMutator = new BufferedMutator(input.getStartIndex(), ${minor.class}Vector.this);
// Let's process the input
while (input.hasNext()) {
T entry = input.next();
if (entry == null || entry.getNumValues() == 0) {
break; // this could happen when handling columnar batch sizing constraints
}
bufferedMutator.setSafe(entry);
if (callback != null) {
callback.onNewBulkEntry(entry);
}
DrillRuntimeException.checkInterrupted(); // Ensures fast handling of query cancellation
}
// Flush any data not yet copied to this VL container
bufferedMutator.flush();
// Inform the input object we're done reading
input.done();
if (callback != null) {
callback.onEndBulkInput();
}
}
/**
* Set the variable length element at the specified index to the supplied byte array.
*
* @param index position of the bit to set
* @param bytes array of bytes to write
* @param start start index of bytes to write
* @param length length of bytes to write
*/
protected void set(int index, byte[] bytes, int start, int length) {
assert index >= 0;
int currentOffset = offsetVector.getAccessor().get(index);
offsetVector.getMutator().set(index + 1, currentOffset + length);
data.setBytes(currentOffset, bytes, start, length);
}
public void setSafe(int index, ByteBuffer bytes, int start, int length) {
assert index >= 0;
int currentOffset = offsetVector.getAccessor().get(index);
while (data.capacity() < currentOffset + length) {
reAlloc();
}
offsetVector.getMutator().setSafe(index + 1, currentOffset + length);
data.setBytes(currentOffset, bytes, start, length);
}
public void setSafe(int index, byte[] bytes, int start, int length) {
assert index >= 0;
int currentOffset = offsetVector.getAccessor().get(index);
while (data.capacity() < currentOffset + length) {
reAlloc();
}
offsetVector.getMutator().setSafe(index + 1, currentOffset + length);
data.setBytes(currentOffset, bytes, start, length);
}
@Override
public void setValueLengthSafe(int index, int length) {
int offset = offsetVector.getAccessor().get(index);
while(data.capacity() < offset + length ) {
reAlloc();
}
offsetVector.getMutator().setSafe(index + 1, offsetVector.getAccessor().get(index) + length);
}
public void setSafe(int index, int start, int end, DrillBuf buffer) {
int len = end - start;
int outputStart = offsetVector.data.get${(minor.javaType!type.javaType)?cap_first}(index * ${type.width});
while (data.capacity() < outputStart + len) {
reAlloc();
}
offsetVector.getMutator().setSafe(index + 1, outputStart + len);
buffer.getBytes(start, data, outputStart, len);
}
public void setSafe(int index, Nullable${minor.class}Holder holder) {
assert holder.isSet == 1;
int start = holder.start;
int end = holder.end;
int len = end - start;
int outputStart = offsetVector.data.get${(minor.javaType!type.javaType)?cap_first}(index * ${type.width});
while (data.capacity() < outputStart + len) {
reAlloc();
}
holder.buffer.getBytes(start, data, outputStart, len);
offsetVector.getMutator().setSafe(index + 1, outputStart + len);
}
<#if minor.class == "VarDecimal">
public void set(int index, BigDecimal value) {
byte[] bytes = value.unscaledValue().toByteArray();
set(index, bytes, 0, bytes.length);
}
public void setSafe(int index, BigDecimal value) {
byte[] bytes = value.unscaledValue().toByteArray();
setSafe(index, bytes, 0, bytes.length);
}
</#if>
public void setSafe(int index, ${minor.class}Holder holder) {
int start = holder.start;
int end = holder.end;
int len = end - start;
int outputStart = offsetVector.data.get${(minor.javaType!type.javaType)?cap_first}(index * ${type.width});
while(data.capacity() < outputStart + len) {
reAlloc();
}
holder.buffer.getBytes(start, data, outputStart, len);
offsetVector.getMutator().setSafe(index + 1, outputStart + len);
}
/**
* Backfill missing offsets from the given last written position up to, but
* not including the given current write position. Used by nullable
* vectors to allow skipping values. The <tt>set()</tt> and
* <tt>setSafe()</tt> <b>do not</b> fill empties. See DRILL-5529.
*
* @param lastWrite
* the position of the last valid write: the offset to be copied
* forward
* @param index
* the current write position filling occurs up to, but not
* including, this position
*/
public void fillEmpties(int lastWrite, int index) {
// If last write was 2, offsets are [0, 3, 6]
// If next write is 4, offsets must be: [0, 3, 6, 6, 6]
// Remember the offsets are one more than row count.
int startWrite = lastWrite + 1;
if (startWrite < index) {
// Don't access the offset vector if nothing to fill.
// This handles the special case of a zero-size batch
// in which the 0th position of the offset vector does
// not even exist.
int fillOffset = offsetVector.getAccessor().get(startWrite);
UInt4Vector.Mutator offsetMutator = offsetVector.getMutator();
for (int i = startWrite; i < index; i++) {
offsetMutator.setSafe(i + 1, fillOffset);
}
}
}
protected void set(int index, int start, int length, DrillBuf buffer){
assert index >= 0;
int currentOffset = offsetVector.getAccessor().get(index);
offsetVector.getMutator().set(index + 1, currentOffset + length);
DrillBuf bb = buffer.slice(start, length);
data.setBytes(currentOffset, bb);
}
protected void set(int index, Nullable${minor.class}Holder holder){
int length = holder.end - holder.start;
int currentOffset = offsetVector.getAccessor().get(index);
offsetVector.getMutator().set(index + 1, currentOffset + length);
data.setBytes(currentOffset, holder.buffer, holder.start, length);
}
protected void set(int index, ${minor.class}Holder holder){
int length = holder.end - holder.start;
int currentOffset = offsetVector.getAccessor().get(index);
offsetVector.getMutator().set(index + 1, currentOffset + length);
data.setBytes(currentOffset, holder.buffer, holder.start, length);
}
/**
* <h4>Notes on Usage</h4>
* <p>
* For {@link VariableWidthVector}s this method can be used in the following
* cases:
* <ul>
* <li>Setting the actual number of elements currently contained in the
* vector.</li>
* <li>Trimming the vector to have fewer elements than it current does.</li>
* </ul>
* </p>
* <h4>Caveats</h4>
* <p>
* It is important to note that for
* {@link org.apache.drill.exec.vector.FixedWidthVector}s this method can
* also be used to expand the vector. However, {@link VariableWidthVector}
* do not support this usage and this method will throw an
* {@link IndexOutOfBoundsException} if you attempt to use it in this way.
* Expansion of valueCounts is not supported mainly because there is no
* benefit, since you would still have to rely on the setSafe methods to
* appropriately expand the data buffer and populate the vector anyway
* (since by definition we do not know the width of elements). See
* DRILL-6234 for details.
* </p>
* <h4>Method Documentation</h4> {@inheritDoc}
*/
@Override
public void setValueCount(int valueCount) {
int currentByteCapacity = getByteCapacity();
// Check if valueCount to be set is zero and current capacity is also zero. If yes then
// we should not call get to read start index from offset vector at that value count.
int idx = (valueCount == 0 && currentByteCapacity == 0)
? 0
: offsetVector.getAccessor().get(valueCount);
data.writerIndex(idx);
if (valueCount > 0 && currentByteCapacity > idx * 2) {
incrementAllocationMonitor();
} else if (allocationMonitor > 0) {
allocationMonitor = 0;
}
offsetVector.getMutator().setValueCount(valueCount == 0 ? 0 : valueCount+1);
}
@Override
public void generateTestData(int size){
boolean even = true;
<#switch minor.class>
<#case "Var16Char">
java.nio.charset.Charset charset = StandardCharsets.UTF_16;
<#break>
<#case "VarChar">
<#default>
java.nio.charset.Charset charset = StandardCharsets.UTF_8;
</#switch>
byte[] evenValue = "aaaaa".getBytes(charset);
byte[] oddValue = "bbbbbbbbbb".getBytes(charset);
for(int i =0; i < size; i++, even = !even){
set(i, even ? evenValue : oddValue);
}
setValueCount(size);
}
}
/**
* Helper class to buffer container mutation as a means to optimize native memory copy operations. Ideally, this
* should be done transparently as part of the Mutator and Accessor APIs.
*
* NB: this class is automatically generated from ValueVectorTypes.tdd using FreeMarker.
*/
public static final class BufferedMutator {
/** The default buffer size */
private static final int DEFAULT_BUFF_SZ = 1024 << 2;
/** Byte buffer */
private final ByteBuffer buffer;
/** Indicator on whether to enable data buffering */
private final boolean enableDataBuffering = false;
/** Current offset within the data buffer */
private int dataBuffOff;
/** Total data length (contained within data and buffer) */
private int totalDataLen;
/** Parent container */
private final ${minor.class}Vector parent;
/** A buffered mutator to the offsets vector */
private final UInt4Vector.BufferedMutator offsetsMutator;
/** @see {@link #BufferedMutator(int startIdx, int buffSz, ${minor.class}Vector parent)} */
public BufferedMutator(int startIdx, ${minor.class}Vector parent) {
this(startIdx, DEFAULT_BUFF_SZ, parent);
}
/**
* Buffered mutator to optimize bulk access to the underlying vector container
* @param startIdx start idex of the first value to be copied
* @param buffSz buffer length to us
* @param parent parent container object
*/
public BufferedMutator(int startIdx, int buffSz, ${minor.class}Vector parent) {
if (enableDataBuffering) {
this.buffer = ByteBuffer.allocate(buffSz);
// set the buffer to the native byte order
this.buffer.order(ByteOrder.nativeOrder());
} else {
this.buffer = null;
}
this.parent = parent;
this.dataBuffOff = this.parent.offsetVector.getAccessor().get(startIdx);
this.totalDataLen = this.dataBuffOff;
this.offsetsMutator = new UInt4Vector.BufferedMutator(startIdx, buffSz, parent.offsetVector);
// Forcing the offsetsMutator to operate at index+1
this.offsetsMutator.setSafe(this.dataBuffOff);
}
public void setSafe(VarLenBulkEntry bulkEntry) {
// The new entry doesn't fit in remaining space
if (enableDataBuffering && buffer.remaining() < bulkEntry.getTotalLength()) {
flushInternal();
}
// Now update the offsets vector with new information
int[] lengths = bulkEntry.getValuesLength();
int numValues = bulkEntry.getNumValues();
setOffsets(lengths, numValues, bulkEntry.hasNulls());
// Now we're able to buffer the new bulk entry
if (enableDataBuffering && buffer.remaining() >= bulkEntry.getTotalLength() && bulkEntry.arrayBacked()) {
buffer.put(bulkEntry.getArrayData(), bulkEntry.getDataStartOffset(), bulkEntry.getTotalLength());
} else {
// The new entry is larger than the buffer (note at this point we know the buffer has been flushed)
while (parent.data.capacity() < totalDataLen) {
parent.reAlloc();
}
if (bulkEntry.arrayBacked()) {
parent.data.setBytes(dataBuffOff,
bulkEntry.getArrayData(),
bulkEntry.getDataStartOffset(),
bulkEntry.getTotalLength());
} else {
parent.data.setBytes(dataBuffOff,
bulkEntry.getData(),
bulkEntry.getDataStartOffset(),
bulkEntry.getTotalLength());
}
// Update the underlying DrillBuf offset
dataBuffOff += bulkEntry.getTotalLength();
}
}
public void flush() {
flushInternal();
offsetsMutator.flush();
}
private void flushInternal() {
if (!enableDataBuffering) {
return; // NOOP
}
int numElements = buffer.position();
if (numElements == 0) {
return; // NOOP
}
while (parent.data.capacity() < totalDataLen) {
parent.reAlloc();
}
try {
parent.data.setBytes(dataBuffOff, buffer.array(), 0, buffer.position());
} catch (Exception e) {
throw new RuntimeException(e);
}
// Update counters
dataBuffOff += buffer.position();
assert dataBuffOff == totalDataLen;
// Reset the byte buffer
buffer.clear();
}
private void setOffsets(int[] lengths, int numValues, boolean hasNulls) {
// We need to compute source offsets using the current larget offset and the value length array.
ByteBuffer offByteBuff = offsetsMutator.getByteBuffer();
byte[] bufferArray = offByteBuff.array();
int remaining = numValues;
int srcPos = 0;
do {
if (offByteBuff.remaining() < 4) {
offsetsMutator.flush();
}
int toCopy = Math.min(remaining, offByteBuff.remaining() / 4);
int tgtPos = offByteBuff.position();
if (!hasNulls) {
for (int idx = 0; idx < toCopy; idx++, tgtPos += 4, srcPos++) {
totalDataLen += lengths[srcPos];
UInt4Vector.BufferedMutator.writeInt(totalDataLen, bufferArray, tgtPos);
}
} else {
for (int idx = 0; idx < toCopy; idx++, tgtPos += 4, srcPos++) {
int curr_len = lengths[srcPos];
totalDataLen += (curr_len >= 0) ? curr_len : 0;
UInt4Vector.BufferedMutator.writeInt(totalDataLen, bufferArray, tgtPos);
}
}
// Update counters
offByteBuff.position(tgtPos);
remaining -= toCopy;
} while (remaining > 0);
// We need to flush as offset data can be accessed during loading to
// figure out current payload size.
offsetsMutator.flush();
}
}
}
</#if> <#-- type.major -->
</#list>
</#list>
|
openjdk/jdk8 | 36,713 | jdk/src/share/classes/java/net/ServerSocket.java | /*
* Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.net;
import java.io.FileDescriptor;
import java.io.IOException;
import java.nio.channels.ServerSocketChannel;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
/**
* This class implements server sockets. A server socket waits for
* requests to come in over the network. It performs some operation
* based on that request, and then possibly returns a result to the requester.
* <p>
* The actual work of the server socket is performed by an instance
* of the {@code SocketImpl} class. An application can
* change the socket factory that creates the socket
* implementation to configure itself to create sockets
* appropriate to the local firewall.
*
* @author unascribed
* @see java.net.SocketImpl
* @see java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
* @see java.nio.channels.ServerSocketChannel
* @since JDK1.0
*/
public
class ServerSocket implements java.io.Closeable {
/**
* Various states of this socket.
*/
private boolean created = false;
private boolean bound = false;
private boolean closed = false;
private Object closeLock = new Object();
/**
* The implementation of this Socket.
*/
private SocketImpl impl;
/**
* Are we using an older SocketImpl?
*/
private boolean oldImpl = false;
/**
* Package-private constructor to create a ServerSocket associated with
* the given SocketImpl.
*/
ServerSocket(SocketImpl impl) {
this.impl = impl;
impl.setServerSocket(this);
}
/**
* Creates an unbound server socket.
*
* @exception IOException IO error when opening the socket.
* @revised 1.4
*/
public ServerSocket() throws IOException {
setImpl();
}
/**
* Creates a server socket, bound to the specified port. A port number
* of {@code 0} means that the port number is automatically
* allocated, typically from an ephemeral port range. This port
* number can then be retrieved by calling {@link #getLocalPort getLocalPort}.
* <p>
* The maximum queue length for incoming connection indications (a
* request to connect) is set to {@code 50}. If a connection
* indication arrives when the queue is full, the connection is refused.
* <p>
* If the application has specified a server socket factory, that
* factory's {@code createSocketImpl} method is called to create
* the actual socket implementation. Otherwise a "plain" socket is created.
* <p>
* If there is a security manager,
* its {@code checkListen} method is called
* with the {@code port} argument
* as its argument to ensure the operation is allowed.
* This could result in a SecurityException.
*
*
* @param port the port number, or {@code 0} to use a port
* number that is automatically allocated.
*
* @exception IOException if an I/O error occurs when opening the socket.
* @exception SecurityException
* if a security manager exists and its {@code checkListen}
* method doesn't allow the operation.
* @exception IllegalArgumentException if the port parameter is outside
* the specified range of valid port values, which is between
* 0 and 65535, inclusive.
*
* @see java.net.SocketImpl
* @see java.net.SocketImplFactory#createSocketImpl()
* @see java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
* @see SecurityManager#checkListen
*/
public ServerSocket(int port) throws IOException {
this(port, 50, null);
}
/**
* Creates a server socket and binds it to the specified local port
* number, with the specified backlog.
* A port number of {@code 0} means that the port number is
* automatically allocated, typically from an ephemeral port range.
* This port number can then be retrieved by calling
* {@link #getLocalPort getLocalPort}.
* <p>
* The maximum queue length for incoming connection indications (a
* request to connect) is set to the {@code backlog} parameter. If
* a connection indication arrives when the queue is full, the
* connection is refused.
* <p>
* If the application has specified a server socket factory, that
* factory's {@code createSocketImpl} method is called to create
* the actual socket implementation. Otherwise a "plain" socket is created.
* <p>
* If there is a security manager,
* its {@code checkListen} method is called
* with the {@code port} argument
* as its argument to ensure the operation is allowed.
* This could result in a SecurityException.
*
* The {@code backlog} argument is the requested maximum number of
* pending connections on the socket. Its exact semantics are implementation
* specific. In particular, an implementation may impose a maximum length
* or may choose to ignore the parameter altogther. The value provided
* should be greater than {@code 0}. If it is less than or equal to
* {@code 0}, then an implementation specific default will be used.
* <P>
*
* @param port the port number, or {@code 0} to use a port
* number that is automatically allocated.
* @param backlog requested maximum length of the queue of incoming
* connections.
*
* @exception IOException if an I/O error occurs when opening the socket.
* @exception SecurityException
* if a security manager exists and its {@code checkListen}
* method doesn't allow the operation.
* @exception IllegalArgumentException if the port parameter is outside
* the specified range of valid port values, which is between
* 0 and 65535, inclusive.
*
* @see java.net.SocketImpl
* @see java.net.SocketImplFactory#createSocketImpl()
* @see java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
* @see SecurityManager#checkListen
*/
public ServerSocket(int port, int backlog) throws IOException {
this(port, backlog, null);
}
/**
* Create a server with the specified port, listen backlog, and
* local IP address to bind to. The <i>bindAddr</i> argument
* can be used on a multi-homed host for a ServerSocket that
* will only accept connect requests to one of its addresses.
* If <i>bindAddr</i> is null, it will default accepting
* connections on any/all local addresses.
* The port must be between 0 and 65535, inclusive.
* A port number of {@code 0} means that the port number is
* automatically allocated, typically from an ephemeral port range.
* This port number can then be retrieved by calling
* {@link #getLocalPort getLocalPort}.
*
* <P>If there is a security manager, this method
* calls its {@code checkListen} method
* with the {@code port} argument
* as its argument to ensure the operation is allowed.
* This could result in a SecurityException.
*
* The {@code backlog} argument is the requested maximum number of
* pending connections on the socket. Its exact semantics are implementation
* specific. In particular, an implementation may impose a maximum length
* or may choose to ignore the parameter altogther. The value provided
* should be greater than {@code 0}. If it is less than or equal to
* {@code 0}, then an implementation specific default will be used.
* <P>
* @param port the port number, or {@code 0} to use a port
* number that is automatically allocated.
* @param backlog requested maximum length of the queue of incoming
* connections.
* @param bindAddr the local InetAddress the server will bind to
*
* @throws SecurityException if a security manager exists and
* its {@code checkListen} method doesn't allow the operation.
*
* @throws IOException if an I/O error occurs when opening the socket.
* @exception IllegalArgumentException if the port parameter is outside
* the specified range of valid port values, which is between
* 0 and 65535, inclusive.
*
* @see SocketOptions
* @see SocketImpl
* @see SecurityManager#checkListen
* @since JDK1.1
*/
public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException {
setImpl();
if (port < 0 || port > 0xFFFF)
throw new IllegalArgumentException(
"Port value out of range: " + port);
if (backlog < 1)
backlog = 50;
try {
bind(new InetSocketAddress(bindAddr, port), backlog);
} catch(SecurityException e) {
close();
throw e;
} catch(IOException e) {
close();
throw e;
}
}
/**
* Get the {@code SocketImpl} attached to this socket, creating
* it if necessary.
*
* @return the {@code SocketImpl} attached to that ServerSocket.
* @throws SocketException if creation fails.
* @since 1.4
*/
SocketImpl getImpl() throws SocketException {
if (!created)
createImpl();
return impl;
}
private void checkOldImpl() {
if (impl == null)
return;
// SocketImpl.connect() is a protected method, therefore we need to use
// getDeclaredMethod, therefore we need permission to access the member
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction<Void>() {
public Void run() throws NoSuchMethodException {
impl.getClass().getDeclaredMethod("connect",
SocketAddress.class,
int.class);
return null;
}
});
} catch (java.security.PrivilegedActionException e) {
oldImpl = true;
}
}
private void setImpl() {
if (factory != null) {
impl = factory.createSocketImpl();
checkOldImpl();
} else {
// No need to do a checkOldImpl() here, we know it's an up to date
// SocketImpl!
impl = new SocksSocketImpl();
}
if (impl != null)
impl.setServerSocket(this);
}
/**
* Creates the socket implementation.
*
* @throws IOException if creation fails
* @since 1.4
*/
void createImpl() throws SocketException {
if (impl == null)
setImpl();
try {
impl.create(true);
created = true;
} catch (IOException e) {
throw new SocketException(e.getMessage());
}
}
/**
*
* Binds the {@code ServerSocket} to a specific address
* (IP address and port number).
* <p>
* If the address is {@code null}, then the system will pick up
* an ephemeral port and a valid local address to bind the socket.
* <p>
* @param endpoint The IP address and port number to bind to.
* @throws IOException if the bind operation fails, or if the socket
* is already bound.
* @throws SecurityException if a {@code SecurityManager} is present and
* its {@code checkListen} method doesn't allow the operation.
* @throws IllegalArgumentException if endpoint is a
* SocketAddress subclass not supported by this socket
* @since 1.4
*/
public void bind(SocketAddress endpoint) throws IOException {
bind(endpoint, 50);
}
/**
*
* Binds the {@code ServerSocket} to a specific address
* (IP address and port number).
* <p>
* If the address is {@code null}, then the system will pick up
* an ephemeral port and a valid local address to bind the socket.
* <P>
* The {@code backlog} argument is the requested maximum number of
* pending connections on the socket. Its exact semantics are implementation
* specific. In particular, an implementation may impose a maximum length
* or may choose to ignore the parameter altogther. The value provided
* should be greater than {@code 0}. If it is less than or equal to
* {@code 0}, then an implementation specific default will be used.
* @param endpoint The IP address and port number to bind to.
* @param backlog requested maximum length of the queue of
* incoming connections.
* @throws IOException if the bind operation fails, or if the socket
* is already bound.
* @throws SecurityException if a {@code SecurityManager} is present and
* its {@code checkListen} method doesn't allow the operation.
* @throws IllegalArgumentException if endpoint is a
* SocketAddress subclass not supported by this socket
* @since 1.4
*/
public void bind(SocketAddress endpoint, int backlog) throws IOException {
if (isClosed())
throw new SocketException("Socket is closed");
if (!oldImpl && isBound())
throw new SocketException("Already bound");
if (endpoint == null)
endpoint = new InetSocketAddress(0);
if (!(endpoint instanceof InetSocketAddress))
throw new IllegalArgumentException("Unsupported address type");
InetSocketAddress epoint = (InetSocketAddress) endpoint;
if (epoint.isUnresolved())
throw new SocketException("Unresolved address");
if (backlog < 1)
backlog = 50;
try {
SecurityManager security = System.getSecurityManager();
if (security != null)
security.checkListen(epoint.getPort());
getImpl().bind(epoint.getAddress(), epoint.getPort());
getImpl().listen(backlog);
bound = true;
} catch(SecurityException e) {
bound = false;
throw e;
} catch(IOException e) {
bound = false;
throw e;
}
}
/**
* Returns the local address of this server socket.
* <p>
* If the socket was bound prior to being {@link #close closed},
* then this method will continue to return the local address
* after the socket is closed.
* <p>
* If there is a security manager set, its {@code checkConnect} method is
* called with the local address and {@code -1} as its arguments to see
* if the operation is allowed. If the operation is not allowed,
* the {@link InetAddress#getLoopbackAddress loopback} address is returned.
*
* @return the address to which this socket is bound,
* or the loopback address if denied by the security manager,
* or {@code null} if the socket is unbound.
*
* @see SecurityManager#checkConnect
*/
public InetAddress getInetAddress() {
if (!isBound())
return null;
try {
InetAddress in = getImpl().getInetAddress();
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkConnect(in.getHostAddress(), -1);
return in;
} catch (SecurityException e) {
return InetAddress.getLoopbackAddress();
} catch (SocketException e) {
// nothing
// If we're bound, the impl has been created
// so we shouldn't get here
}
return null;
}
/**
* Returns the port number on which this socket is listening.
* <p>
* If the socket was bound prior to being {@link #close closed},
* then this method will continue to return the port number
* after the socket is closed.
*
* @return the port number to which this socket is listening or
* -1 if the socket is not bound yet.
*/
public int getLocalPort() {
if (!isBound())
return -1;
try {
return getImpl().getLocalPort();
} catch (SocketException e) {
// nothing
// If we're bound, the impl has been created
// so we shouldn't get here
}
return -1;
}
/**
* Returns the address of the endpoint this socket is bound to.
* <p>
* If the socket was bound prior to being {@link #close closed},
* then this method will continue to return the address of the endpoint
* after the socket is closed.
* <p>
* If there is a security manager set, its {@code checkConnect} method is
* called with the local address and {@code -1} as its arguments to see
* if the operation is allowed. If the operation is not allowed,
* a {@code SocketAddress} representing the
* {@link InetAddress#getLoopbackAddress loopback} address and the local
* port to which the socket is bound is returned.
*
* @return a {@code SocketAddress} representing the local endpoint of
* this socket, or a {@code SocketAddress} representing the
* loopback address if denied by the security manager,
* or {@code null} if the socket is not bound yet.
*
* @see #getInetAddress()
* @see #getLocalPort()
* @see #bind(SocketAddress)
* @see SecurityManager#checkConnect
* @since 1.4
*/
public SocketAddress getLocalSocketAddress() {
if (!isBound())
return null;
return new InetSocketAddress(getInetAddress(), getLocalPort());
}
/**
* Listens for a connection to be made to this socket and accepts
* it. The method blocks until a connection is made.
*
* <p>A new Socket {@code s} is created and, if there
* is a security manager,
* the security manager's {@code checkAccept} method is called
* with {@code s.getInetAddress().getHostAddress()} and
* {@code s.getPort()}
* as its arguments to ensure the operation is allowed.
* This could result in a SecurityException.
*
* @exception IOException if an I/O error occurs when waiting for a
* connection.
* @exception SecurityException if a security manager exists and its
* {@code checkAccept} method doesn't allow the operation.
* @exception SocketTimeoutException if a timeout was previously set with setSoTimeout and
* the timeout has been reached.
* @exception java.nio.channels.IllegalBlockingModeException
* if this socket has an associated channel, the channel is in
* non-blocking mode, and there is no connection ready to be
* accepted
*
* @return the new Socket
* @see SecurityManager#checkAccept
* @revised 1.4
* @spec JSR-51
*/
public Socket accept() throws IOException {
if (isClosed())
throw new SocketException("Socket is closed");
if (!isBound())
throw new SocketException("Socket is not bound yet");
Socket s = new Socket((SocketImpl) null);
implAccept(s);
return s;
}
/**
* Subclasses of ServerSocket use this method to override accept()
* to return their own subclass of socket. So a FooServerSocket
* will typically hand this method an <i>empty</i> FooSocket. On
* return from implAccept the FooSocket will be connected to a client.
*
* @param s the Socket
* @throws java.nio.channels.IllegalBlockingModeException
* if this socket has an associated channel,
* and the channel is in non-blocking mode
* @throws IOException if an I/O error occurs when waiting
* for a connection.
* @since JDK1.1
* @revised 1.4
* @spec JSR-51
*/
protected final void implAccept(Socket s) throws IOException {
SocketImpl si = null;
try {
if (s.impl == null)
s.setImpl();
else {
s.impl.reset();
}
si = s.impl;
s.impl = null;
si.address = new InetAddress();
si.fd = new FileDescriptor();
getImpl().accept(si);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkAccept(si.getInetAddress().getHostAddress(),
si.getPort());
}
} catch (IOException e) {
if (si != null)
si.reset();
s.impl = si;
throw e;
} catch (SecurityException e) {
if (si != null)
si.reset();
s.impl = si;
throw e;
}
s.impl = si;
s.postAccept();
}
/**
* Closes this socket.
*
* Any thread currently blocked in {@link #accept()} will throw
* a {@link SocketException}.
*
* <p> If this socket has an associated channel then the channel is closed
* as well.
*
* @exception IOException if an I/O error occurs when closing the socket.
* @revised 1.4
* @spec JSR-51
*/
public void close() throws IOException {
synchronized(closeLock) {
if (isClosed())
return;
if (created)
impl.close();
closed = true;
}
}
/**
* Returns the unique {@link java.nio.channels.ServerSocketChannel} object
* associated with this socket, if any.
*
* <p> A server socket will have a channel if, and only if, the channel
* itself was created via the {@link
* java.nio.channels.ServerSocketChannel#open ServerSocketChannel.open}
* method.
*
* @return the server-socket channel associated with this socket,
* or {@code null} if this socket was not created
* for a channel
*
* @since 1.4
* @spec JSR-51
*/
public ServerSocketChannel getChannel() {
return null;
}
/**
* Returns the binding state of the ServerSocket.
*
* @return true if the ServerSocket successfully bound to an address
* @since 1.4
*/
public boolean isBound() {
// Before 1.3 ServerSockets were always bound during creation
return bound || oldImpl;
}
/**
* Returns the closed state of the ServerSocket.
*
* @return true if the socket has been closed
* @since 1.4
*/
public boolean isClosed() {
synchronized(closeLock) {
return closed;
}
}
/**
* Enable/disable {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} with the
* specified timeout, in milliseconds. With this option set to a non-zero
* timeout, a call to accept() for this ServerSocket
* will block for only this amount of time. If the timeout expires,
* a <B>java.net.SocketTimeoutException</B> is raised, though the
* ServerSocket is still valid. The option <B>must</B> be enabled
* prior to entering the blocking operation to have effect. The
* timeout must be {@code > 0}.
* A timeout of zero is interpreted as an infinite timeout.
* @param timeout the specified timeout, in milliseconds
* @exception SocketException if there is an error in
* the underlying protocol, such as a TCP error.
* @since JDK1.1
* @see #getSoTimeout()
*/
public synchronized void setSoTimeout(int timeout) throws SocketException {
if (isClosed())
throw new SocketException("Socket is closed");
getImpl().setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
}
/**
* Retrieve setting for {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}.
* 0 returns implies that the option is disabled (i.e., timeout of infinity).
* @return the {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} value
* @exception IOException if an I/O error occurs
* @since JDK1.1
* @see #setSoTimeout(int)
*/
public synchronized int getSoTimeout() throws IOException {
if (isClosed())
throw new SocketException("Socket is closed");
Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT);
/* extra type safety */
if (o instanceof Integer) {
return ((Integer) o).intValue();
} else {
return 0;
}
}
/**
* Enable/disable the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
* socket option.
* <p>
* When a TCP connection is closed the connection may remain
* in a timeout state for a period of time after the connection
* is closed (typically known as the {@code TIME_WAIT} state
* or {@code 2MSL} wait state).
* For applications using a well known socket address or port
* it may not be possible to bind a socket to the required
* {@code SocketAddress} if there is a connection in the
* timeout state involving the socket address or port.
* <p>
* Enabling {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} prior to
* binding the socket using {@link #bind(SocketAddress)} allows the socket
* to be bound even though a previous connection is in a timeout state.
* <p>
* When a {@code ServerSocket} is created the initial setting
* of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is not defined.
* Applications can use {@link #getReuseAddress()} to determine the initial
* setting of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}.
* <p>
* The behaviour when {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is
* enabled or disabled after a socket is bound (See {@link #isBound()})
* is not defined.
*
* @param on whether to enable or disable the socket option
* @exception SocketException if an error occurs enabling or
* disabling the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
* socket option, or the socket is closed.
* @since 1.4
* @see #getReuseAddress()
* @see #bind(SocketAddress)
* @see #isBound()
* @see #isClosed()
*/
public void setReuseAddress(boolean on) throws SocketException {
if (isClosed())
throw new SocketException("Socket is closed");
getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on));
}
/**
* Tests if {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
*
* @return a {@code boolean} indicating whether or not
* {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
* @exception SocketException if there is an error
* in the underlying protocol, such as a TCP error.
* @since 1.4
* @see #setReuseAddress(boolean)
*/
public boolean getReuseAddress() throws SocketException {
if (isClosed())
throw new SocketException("Socket is closed");
return ((Boolean) (getImpl().getOption(SocketOptions.SO_REUSEADDR))).booleanValue();
}
/**
* Returns the implementation address and implementation port of
* this socket as a {@code String}.
* <p>
* If there is a security manager set, its {@code checkConnect} method is
* called with the local address and {@code -1} as its arguments to see
* if the operation is allowed. If the operation is not allowed,
* an {@code InetAddress} representing the
* {@link InetAddress#getLoopbackAddress loopback} address is returned as
* the implementation address.
*
* @return a string representation of this socket.
*/
public String toString() {
if (!isBound())
return "ServerSocket[unbound]";
InetAddress in;
if (System.getSecurityManager() != null)
in = InetAddress.getLoopbackAddress();
else
in = impl.getInetAddress();
return "ServerSocket[addr=" + in +
",localport=" + impl.getLocalPort() + "]";
}
void setBound() {
bound = true;
}
void setCreated() {
created = true;
}
/**
* The factory for all server sockets.
*/
private static SocketImplFactory factory = null;
/**
* Sets the server socket implementation factory for the
* application. The factory can be specified only once.
* <p>
* When an application creates a new server socket, the socket
* implementation factory's {@code createSocketImpl} method is
* called to create the actual socket implementation.
* <p>
* Passing {@code null} to the method is a no-op unless the factory
* was already set.
* <p>
* If there is a security manager, this method first calls
* the security manager's {@code checkSetFactory} method
* to ensure the operation is allowed.
* This could result in a SecurityException.
*
* @param fac the desired factory.
* @exception IOException if an I/O error occurs when setting the
* socket factory.
* @exception SocketException if the factory has already been defined.
* @exception SecurityException if a security manager exists and its
* {@code checkSetFactory} method doesn't allow the operation.
* @see java.net.SocketImplFactory#createSocketImpl()
* @see SecurityManager#checkSetFactory
*/
public static synchronized void setSocketFactory(SocketImplFactory fac) throws IOException {
if (factory != null) {
throw new SocketException("factory already defined");
}
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkSetFactory();
}
factory = fac;
}
/**
* Sets a default proposed value for the
* {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option for sockets
* accepted from this {@code ServerSocket}. The value actually set
* in the accepted socket must be determined by calling
* {@link Socket#getReceiveBufferSize()} after the socket
* is returned by {@link #accept()}.
* <p>
* The value of {@link SocketOptions#SO_RCVBUF SO_RCVBUF} is used both to
* set the size of the internal socket receive buffer, and to set the size
* of the TCP receive window that is advertized to the remote peer.
* <p>
* It is possible to change the value subsequently, by calling
* {@link Socket#setReceiveBufferSize(int)}. However, if the application
* wishes to allow a receive window larger than 64K bytes, as defined by RFC1323
* then the proposed value must be set in the ServerSocket <B>before</B>
* it is bound to a local address. This implies, that the ServerSocket must be
* created with the no-argument constructor, then setReceiveBufferSize() must
* be called and lastly the ServerSocket is bound to an address by calling bind().
* <p>
* Failure to do this will not cause an error, and the buffer size may be set to the
* requested value but the TCP receive window in sockets accepted from
* this ServerSocket will be no larger than 64K bytes.
*
* @exception SocketException if there is an error
* in the underlying protocol, such as a TCP error.
*
* @param size the size to which to set the receive buffer
* size. This value must be greater than 0.
*
* @exception IllegalArgumentException if the
* value is 0 or is negative.
*
* @since 1.4
* @see #getReceiveBufferSize
*/
public synchronized void setReceiveBufferSize (int size) throws SocketException {
if (!(size > 0)) {
throw new IllegalArgumentException("negative receive size");
}
if (isClosed())
throw new SocketException("Socket is closed");
getImpl().setOption(SocketOptions.SO_RCVBUF, new Integer(size));
}
/**
* Gets the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option
* for this {@code ServerSocket}, that is the proposed buffer size that
* will be used for Sockets accepted from this {@code ServerSocket}.
*
* <p>Note, the value actually set in the accepted socket is determined by
* calling {@link Socket#getReceiveBufferSize()}.
* @return the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF}
* option for this {@code Socket}.
* @exception SocketException if there is an error
* in the underlying protocol, such as a TCP error.
* @see #setReceiveBufferSize(int)
* @since 1.4
*/
public synchronized int getReceiveBufferSize()
throws SocketException{
if (isClosed())
throw new SocketException("Socket is closed");
int result = 0;
Object o = getImpl().getOption(SocketOptions.SO_RCVBUF);
if (o instanceof Integer) {
result = ((Integer)o).intValue();
}
return result;
}
/**
* Sets performance preferences for this ServerSocket.
*
* <p> Sockets use the TCP/IP protocol by default. Some implementations
* may offer alternative protocols which have different performance
* characteristics than TCP/IP. This method allows the application to
* express its own preferences as to how these tradeoffs should be made
* when the implementation chooses from the available protocols.
*
* <p> Performance preferences are described by three integers
* whose values indicate the relative importance of short connection time,
* low latency, and high bandwidth. The absolute values of the integers
* are irrelevant; in order to choose a protocol the values are simply
* compared, with larger values indicating stronger preferences. If the
* application prefers short connection time over both low latency and high
* bandwidth, for example, then it could invoke this method with the values
* {@code (1, 0, 0)}. If the application prefers high bandwidth above low
* latency, and low latency above short connection time, then it could
* invoke this method with the values {@code (0, 1, 2)}.
*
* <p> Invoking this method after this socket has been bound
* will have no effect. This implies that in order to use this capability
* requires the socket to be created with the no-argument constructor.
*
* @param connectionTime
* An {@code int} expressing the relative importance of a short
* connection time
*
* @param latency
* An {@code int} expressing the relative importance of low
* latency
*
* @param bandwidth
* An {@code int} expressing the relative importance of high
* bandwidth
*
* @since 1.5
*/
public void setPerformancePreferences(int connectionTime,
int latency,
int bandwidth)
{
/* Not implemented yet */
}
}
|
googleapis/google-cloud-java | 36,412 | java-dataproc-metastore/proto-google-cloud-dataproc-metastore-v1/src/main/java/com/google/cloud/metastore/v1/KerberosConfig.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/metastore/v1/metastore.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.metastore.v1;
/**
*
*
* <pre>
* Configuration information for a Kerberos principal.
* </pre>
*
* Protobuf type {@code google.cloud.metastore.v1.KerberosConfig}
*/
public final class KerberosConfig extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.metastore.v1.KerberosConfig)
KerberosConfigOrBuilder {
private static final long serialVersionUID = 0L;
// Use KerberosConfig.newBuilder() to construct.
private KerberosConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private KerberosConfig() {
principal_ = "";
krb5ConfigGcsUri_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new KerberosConfig();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.metastore.v1.MetastoreProto
.internal_static_google_cloud_metastore_v1_KerberosConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.metastore.v1.MetastoreProto
.internal_static_google_cloud_metastore_v1_KerberosConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.metastore.v1.KerberosConfig.class,
com.google.cloud.metastore.v1.KerberosConfig.Builder.class);
}
private int bitField0_;
public static final int KEYTAB_FIELD_NUMBER = 1;
private com.google.cloud.metastore.v1.Secret keytab_;
/**
*
*
* <pre>
* A Kerberos keytab file that can be used to authenticate a service principal
* with a Kerberos Key Distribution Center (KDC).
* </pre>
*
* <code>.google.cloud.metastore.v1.Secret keytab = 1;</code>
*
* @return Whether the keytab field is set.
*/
@java.lang.Override
public boolean hasKeytab() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* A Kerberos keytab file that can be used to authenticate a service principal
* with a Kerberos Key Distribution Center (KDC).
* </pre>
*
* <code>.google.cloud.metastore.v1.Secret keytab = 1;</code>
*
* @return The keytab.
*/
@java.lang.Override
public com.google.cloud.metastore.v1.Secret getKeytab() {
return keytab_ == null ? com.google.cloud.metastore.v1.Secret.getDefaultInstance() : keytab_;
}
/**
*
*
* <pre>
* A Kerberos keytab file that can be used to authenticate a service principal
* with a Kerberos Key Distribution Center (KDC).
* </pre>
*
* <code>.google.cloud.metastore.v1.Secret keytab = 1;</code>
*/
@java.lang.Override
public com.google.cloud.metastore.v1.SecretOrBuilder getKeytabOrBuilder() {
return keytab_ == null ? com.google.cloud.metastore.v1.Secret.getDefaultInstance() : keytab_;
}
public static final int PRINCIPAL_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object principal_ = "";
/**
*
*
* <pre>
* A Kerberos principal that exists in the both the keytab the KDC
* to authenticate as. A typical principal is of the form
* `primary/instance@REALM`, but there is no exact format.
* </pre>
*
* <code>string principal = 2;</code>
*
* @return The principal.
*/
@java.lang.Override
public java.lang.String getPrincipal() {
java.lang.Object ref = principal_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
principal_ = s;
return s;
}
}
/**
*
*
* <pre>
* A Kerberos principal that exists in the both the keytab the KDC
* to authenticate as. A typical principal is of the form
* `primary/instance@REALM`, but there is no exact format.
* </pre>
*
* <code>string principal = 2;</code>
*
* @return The bytes for principal.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPrincipalBytes() {
java.lang.Object ref = principal_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
principal_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int KRB5_CONFIG_GCS_URI_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object krb5ConfigGcsUri_ = "";
/**
*
*
* <pre>
* A Cloud Storage URI that specifies the path to a
* krb5.conf file. It is of the form `gs://{bucket_name}/path/to/krb5.conf`,
* although the file does not need to be named krb5.conf explicitly.
* </pre>
*
* <code>string krb5_config_gcs_uri = 3;</code>
*
* @return The krb5ConfigGcsUri.
*/
@java.lang.Override
public java.lang.String getKrb5ConfigGcsUri() {
java.lang.Object ref = krb5ConfigGcsUri_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
krb5ConfigGcsUri_ = s;
return s;
}
}
/**
*
*
* <pre>
* A Cloud Storage URI that specifies the path to a
* krb5.conf file. It is of the form `gs://{bucket_name}/path/to/krb5.conf`,
* although the file does not need to be named krb5.conf explicitly.
* </pre>
*
* <code>string krb5_config_gcs_uri = 3;</code>
*
* @return The bytes for krb5ConfigGcsUri.
*/
@java.lang.Override
public com.google.protobuf.ByteString getKrb5ConfigGcsUriBytes() {
java.lang.Object ref = krb5ConfigGcsUri_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
krb5ConfigGcsUri_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getKeytab());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(principal_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, principal_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(krb5ConfigGcsUri_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, krb5ConfigGcsUri_);
}
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, getKeytab());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(principal_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, principal_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(krb5ConfigGcsUri_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, krb5ConfigGcsUri_);
}
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.metastore.v1.KerberosConfig)) {
return super.equals(obj);
}
com.google.cloud.metastore.v1.KerberosConfig other =
(com.google.cloud.metastore.v1.KerberosConfig) obj;
if (hasKeytab() != other.hasKeytab()) return false;
if (hasKeytab()) {
if (!getKeytab().equals(other.getKeytab())) return false;
}
if (!getPrincipal().equals(other.getPrincipal())) return false;
if (!getKrb5ConfigGcsUri().equals(other.getKrb5ConfigGcsUri())) 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 (hasKeytab()) {
hash = (37 * hash) + KEYTAB_FIELD_NUMBER;
hash = (53 * hash) + getKeytab().hashCode();
}
hash = (37 * hash) + PRINCIPAL_FIELD_NUMBER;
hash = (53 * hash) + getPrincipal().hashCode();
hash = (37 * hash) + KRB5_CONFIG_GCS_URI_FIELD_NUMBER;
hash = (53 * hash) + getKrb5ConfigGcsUri().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.metastore.v1.KerberosConfig parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.metastore.v1.KerberosConfig 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.metastore.v1.KerberosConfig parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.metastore.v1.KerberosConfig 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.metastore.v1.KerberosConfig parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.metastore.v1.KerberosConfig parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.metastore.v1.KerberosConfig parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.metastore.v1.KerberosConfig 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.metastore.v1.KerberosConfig parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.metastore.v1.KerberosConfig 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.metastore.v1.KerberosConfig parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.metastore.v1.KerberosConfig 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.metastore.v1.KerberosConfig 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 information for a Kerberos principal.
* </pre>
*
* Protobuf type {@code google.cloud.metastore.v1.KerberosConfig}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.metastore.v1.KerberosConfig)
com.google.cloud.metastore.v1.KerberosConfigOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.metastore.v1.MetastoreProto
.internal_static_google_cloud_metastore_v1_KerberosConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.metastore.v1.MetastoreProto
.internal_static_google_cloud_metastore_v1_KerberosConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.metastore.v1.KerberosConfig.class,
com.google.cloud.metastore.v1.KerberosConfig.Builder.class);
}
// Construct using com.google.cloud.metastore.v1.KerberosConfig.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getKeytabFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
keytab_ = null;
if (keytabBuilder_ != null) {
keytabBuilder_.dispose();
keytabBuilder_ = null;
}
principal_ = "";
krb5ConfigGcsUri_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.metastore.v1.MetastoreProto
.internal_static_google_cloud_metastore_v1_KerberosConfig_descriptor;
}
@java.lang.Override
public com.google.cloud.metastore.v1.KerberosConfig getDefaultInstanceForType() {
return com.google.cloud.metastore.v1.KerberosConfig.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.metastore.v1.KerberosConfig build() {
com.google.cloud.metastore.v1.KerberosConfig result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.metastore.v1.KerberosConfig buildPartial() {
com.google.cloud.metastore.v1.KerberosConfig result =
new com.google.cloud.metastore.v1.KerberosConfig(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.metastore.v1.KerberosConfig result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.keytab_ = keytabBuilder_ == null ? keytab_ : keytabBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.principal_ = principal_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.krb5ConfigGcsUri_ = krb5ConfigGcsUri_;
}
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.metastore.v1.KerberosConfig) {
return mergeFrom((com.google.cloud.metastore.v1.KerberosConfig) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.metastore.v1.KerberosConfig other) {
if (other == com.google.cloud.metastore.v1.KerberosConfig.getDefaultInstance()) return this;
if (other.hasKeytab()) {
mergeKeytab(other.getKeytab());
}
if (!other.getPrincipal().isEmpty()) {
principal_ = other.principal_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getKrb5ConfigGcsUri().isEmpty()) {
krb5ConfigGcsUri_ = other.krb5ConfigGcsUri_;
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:
{
input.readMessage(getKeytabFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
principal_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
krb5ConfigGcsUri_ = 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 com.google.cloud.metastore.v1.Secret keytab_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.metastore.v1.Secret,
com.google.cloud.metastore.v1.Secret.Builder,
com.google.cloud.metastore.v1.SecretOrBuilder>
keytabBuilder_;
/**
*
*
* <pre>
* A Kerberos keytab file that can be used to authenticate a service principal
* with a Kerberos Key Distribution Center (KDC).
* </pre>
*
* <code>.google.cloud.metastore.v1.Secret keytab = 1;</code>
*
* @return Whether the keytab field is set.
*/
public boolean hasKeytab() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* A Kerberos keytab file that can be used to authenticate a service principal
* with a Kerberos Key Distribution Center (KDC).
* </pre>
*
* <code>.google.cloud.metastore.v1.Secret keytab = 1;</code>
*
* @return The keytab.
*/
public com.google.cloud.metastore.v1.Secret getKeytab() {
if (keytabBuilder_ == null) {
return keytab_ == null
? com.google.cloud.metastore.v1.Secret.getDefaultInstance()
: keytab_;
} else {
return keytabBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* A Kerberos keytab file that can be used to authenticate a service principal
* with a Kerberos Key Distribution Center (KDC).
* </pre>
*
* <code>.google.cloud.metastore.v1.Secret keytab = 1;</code>
*/
public Builder setKeytab(com.google.cloud.metastore.v1.Secret value) {
if (keytabBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
keytab_ = value;
} else {
keytabBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* A Kerberos keytab file that can be used to authenticate a service principal
* with a Kerberos Key Distribution Center (KDC).
* </pre>
*
* <code>.google.cloud.metastore.v1.Secret keytab = 1;</code>
*/
public Builder setKeytab(com.google.cloud.metastore.v1.Secret.Builder builderForValue) {
if (keytabBuilder_ == null) {
keytab_ = builderForValue.build();
} else {
keytabBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* A Kerberos keytab file that can be used to authenticate a service principal
* with a Kerberos Key Distribution Center (KDC).
* </pre>
*
* <code>.google.cloud.metastore.v1.Secret keytab = 1;</code>
*/
public Builder mergeKeytab(com.google.cloud.metastore.v1.Secret value) {
if (keytabBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& keytab_ != null
&& keytab_ != com.google.cloud.metastore.v1.Secret.getDefaultInstance()) {
getKeytabBuilder().mergeFrom(value);
} else {
keytab_ = value;
}
} else {
keytabBuilder_.mergeFrom(value);
}
if (keytab_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* A Kerberos keytab file that can be used to authenticate a service principal
* with a Kerberos Key Distribution Center (KDC).
* </pre>
*
* <code>.google.cloud.metastore.v1.Secret keytab = 1;</code>
*/
public Builder clearKeytab() {
bitField0_ = (bitField0_ & ~0x00000001);
keytab_ = null;
if (keytabBuilder_ != null) {
keytabBuilder_.dispose();
keytabBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* A Kerberos keytab file that can be used to authenticate a service principal
* with a Kerberos Key Distribution Center (KDC).
* </pre>
*
* <code>.google.cloud.metastore.v1.Secret keytab = 1;</code>
*/
public com.google.cloud.metastore.v1.Secret.Builder getKeytabBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getKeytabFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* A Kerberos keytab file that can be used to authenticate a service principal
* with a Kerberos Key Distribution Center (KDC).
* </pre>
*
* <code>.google.cloud.metastore.v1.Secret keytab = 1;</code>
*/
public com.google.cloud.metastore.v1.SecretOrBuilder getKeytabOrBuilder() {
if (keytabBuilder_ != null) {
return keytabBuilder_.getMessageOrBuilder();
} else {
return keytab_ == null
? com.google.cloud.metastore.v1.Secret.getDefaultInstance()
: keytab_;
}
}
/**
*
*
* <pre>
* A Kerberos keytab file that can be used to authenticate a service principal
* with a Kerberos Key Distribution Center (KDC).
* </pre>
*
* <code>.google.cloud.metastore.v1.Secret keytab = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.metastore.v1.Secret,
com.google.cloud.metastore.v1.Secret.Builder,
com.google.cloud.metastore.v1.SecretOrBuilder>
getKeytabFieldBuilder() {
if (keytabBuilder_ == null) {
keytabBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.metastore.v1.Secret,
com.google.cloud.metastore.v1.Secret.Builder,
com.google.cloud.metastore.v1.SecretOrBuilder>(
getKeytab(), getParentForChildren(), isClean());
keytab_ = null;
}
return keytabBuilder_;
}
private java.lang.Object principal_ = "";
/**
*
*
* <pre>
* A Kerberos principal that exists in the both the keytab the KDC
* to authenticate as. A typical principal is of the form
* `primary/instance@REALM`, but there is no exact format.
* </pre>
*
* <code>string principal = 2;</code>
*
* @return The principal.
*/
public java.lang.String getPrincipal() {
java.lang.Object ref = principal_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
principal_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A Kerberos principal that exists in the both the keytab the KDC
* to authenticate as. A typical principal is of the form
* `primary/instance@REALM`, but there is no exact format.
* </pre>
*
* <code>string principal = 2;</code>
*
* @return The bytes for principal.
*/
public com.google.protobuf.ByteString getPrincipalBytes() {
java.lang.Object ref = principal_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
principal_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A Kerberos principal that exists in the both the keytab the KDC
* to authenticate as. A typical principal is of the form
* `primary/instance@REALM`, but there is no exact format.
* </pre>
*
* <code>string principal = 2;</code>
*
* @param value The principal to set.
* @return This builder for chaining.
*/
public Builder setPrincipal(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
principal_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A Kerberos principal that exists in the both the keytab the KDC
* to authenticate as. A typical principal is of the form
* `primary/instance@REALM`, but there is no exact format.
* </pre>
*
* <code>string principal = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPrincipal() {
principal_ = getDefaultInstance().getPrincipal();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A Kerberos principal that exists in the both the keytab the KDC
* to authenticate as. A typical principal is of the form
* `primary/instance@REALM`, but there is no exact format.
* </pre>
*
* <code>string principal = 2;</code>
*
* @param value The bytes for principal to set.
* @return This builder for chaining.
*/
public Builder setPrincipalBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
principal_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object krb5ConfigGcsUri_ = "";
/**
*
*
* <pre>
* A Cloud Storage URI that specifies the path to a
* krb5.conf file. It is of the form `gs://{bucket_name}/path/to/krb5.conf`,
* although the file does not need to be named krb5.conf explicitly.
* </pre>
*
* <code>string krb5_config_gcs_uri = 3;</code>
*
* @return The krb5ConfigGcsUri.
*/
public java.lang.String getKrb5ConfigGcsUri() {
java.lang.Object ref = krb5ConfigGcsUri_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
krb5ConfigGcsUri_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A Cloud Storage URI that specifies the path to a
* krb5.conf file. It is of the form `gs://{bucket_name}/path/to/krb5.conf`,
* although the file does not need to be named krb5.conf explicitly.
* </pre>
*
* <code>string krb5_config_gcs_uri = 3;</code>
*
* @return The bytes for krb5ConfigGcsUri.
*/
public com.google.protobuf.ByteString getKrb5ConfigGcsUriBytes() {
java.lang.Object ref = krb5ConfigGcsUri_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
krb5ConfigGcsUri_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A Cloud Storage URI that specifies the path to a
* krb5.conf file. It is of the form `gs://{bucket_name}/path/to/krb5.conf`,
* although the file does not need to be named krb5.conf explicitly.
* </pre>
*
* <code>string krb5_config_gcs_uri = 3;</code>
*
* @param value The krb5ConfigGcsUri to set.
* @return This builder for chaining.
*/
public Builder setKrb5ConfigGcsUri(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
krb5ConfigGcsUri_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* A Cloud Storage URI that specifies the path to a
* krb5.conf file. It is of the form `gs://{bucket_name}/path/to/krb5.conf`,
* although the file does not need to be named krb5.conf explicitly.
* </pre>
*
* <code>string krb5_config_gcs_uri = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearKrb5ConfigGcsUri() {
krb5ConfigGcsUri_ = getDefaultInstance().getKrb5ConfigGcsUri();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* A Cloud Storage URI that specifies the path to a
* krb5.conf file. It is of the form `gs://{bucket_name}/path/to/krb5.conf`,
* although the file does not need to be named krb5.conf explicitly.
* </pre>
*
* <code>string krb5_config_gcs_uri = 3;</code>
*
* @param value The bytes for krb5ConfigGcsUri to set.
* @return This builder for chaining.
*/
public Builder setKrb5ConfigGcsUriBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
krb5ConfigGcsUri_ = 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.metastore.v1.KerberosConfig)
}
// @@protoc_insertion_point(class_scope:google.cloud.metastore.v1.KerberosConfig)
private static final com.google.cloud.metastore.v1.KerberosConfig DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.metastore.v1.KerberosConfig();
}
public static com.google.cloud.metastore.v1.KerberosConfig getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<KerberosConfig> PARSER =
new com.google.protobuf.AbstractParser<KerberosConfig>() {
@java.lang.Override
public KerberosConfig 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<KerberosConfig> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<KerberosConfig> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.metastore.v1.KerberosConfig getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,686 | java-shopping-css/google-shopping-css/src/main/java/com/google/shopping/css/v1/AccountLabelsServiceClient.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.css.v1;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.paging.AbstractFixedSizeCollection;
import com.google.api.gax.paging.AbstractPage;
import com.google.api.gax.paging.AbstractPagedListResponse;
import com.google.api.gax.rpc.PageContext;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.protobuf.Empty;
import com.google.shopping.css.v1.stub.AccountLabelsServiceStub;
import com.google.shopping.css.v1.stub.AccountLabelsServiceStubSettings;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Service Description: Manages Merchant Center and CSS accounts labels.
*
* <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 (AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create()) {
* AccountName parent = AccountName.of("[ACCOUNT]");
* AccountLabel accountLabel = AccountLabel.newBuilder().build();
* AccountLabel response = accountLabelsServiceClient.createAccountLabel(parent, accountLabel);
* }
* }</pre>
*
* <p>Note: close() needs to be called on the AccountLabelsServiceClient 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> ListAccountLabels</td>
* <td><p> Lists the labels owned by an 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> listAccountLabels(ListAccountLabelsRequest 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> listAccountLabels(AccountName parent)
* <li><p> listAccountLabels(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> listAccountLabelsPagedCallable()
* <li><p> listAccountLabelsCallable()
* </ul>
* </td>
* </tr>
* <tr>
* <td><p> CreateAccountLabel</td>
* <td><p> Creates a new label, not assigned to any 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> createAccountLabel(CreateAccountLabelRequest 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> createAccountLabel(AccountName parent, AccountLabel accountLabel)
* <li><p> createAccountLabel(String parent, AccountLabel accountLabel)
* </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> createAccountLabelCallable()
* </ul>
* </td>
* </tr>
* <tr>
* <td><p> UpdateAccountLabel</td>
* <td><p> Updates a label.</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> updateAccountLabel(UpdateAccountLabelRequest 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> updateAccountLabel(AccountLabel accountLabel)
* </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> updateAccountLabelCallable()
* </ul>
* </td>
* </tr>
* <tr>
* <td><p> DeleteAccountLabel</td>
* <td><p> Deletes a label and removes it from all accounts to which it was assigned.</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> deleteAccountLabel(DeleteAccountLabelRequest 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> deleteAccountLabel(AccountLabelName name)
* <li><p> deleteAccountLabel(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> deleteAccountLabelCallable()
* </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 AccountLabelsServiceSettings
* 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
* AccountLabelsServiceSettings accountLabelsServiceSettings =
* AccountLabelsServiceSettings.newBuilder()
* .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
* .build();
* AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create(accountLabelsServiceSettings);
* }</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
* AccountLabelsServiceSettings accountLabelsServiceSettings =
* AccountLabelsServiceSettings.newBuilder().setEndpoint(myEndpoint).build();
* AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create(accountLabelsServiceSettings);
* }</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
* AccountLabelsServiceSettings accountLabelsServiceSettings =
* AccountLabelsServiceSettings.newHttpJsonBuilder().build();
* AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create(accountLabelsServiceSettings);
* }</pre>
*
* <p>Please refer to the GitHub repository's samples for more quickstart code snippets.
*/
@Generated("by gapic-generator-java")
public class AccountLabelsServiceClient implements BackgroundResource {
private final AccountLabelsServiceSettings settings;
private final AccountLabelsServiceStub stub;
/** Constructs an instance of AccountLabelsServiceClient with default settings. */
public static final AccountLabelsServiceClient create() throws IOException {
return create(AccountLabelsServiceSettings.newBuilder().build());
}
/**
* Constructs an instance of AccountLabelsServiceClient, 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 AccountLabelsServiceClient create(AccountLabelsServiceSettings settings)
throws IOException {
return new AccountLabelsServiceClient(settings);
}
/**
* Constructs an instance of AccountLabelsServiceClient, using the given stub for making calls.
* This is for advanced usage - prefer using create(AccountLabelsServiceSettings).
*/
public static final AccountLabelsServiceClient create(AccountLabelsServiceStub stub) {
return new AccountLabelsServiceClient(stub);
}
/**
* Constructs an instance of AccountLabelsServiceClient, 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 AccountLabelsServiceClient(AccountLabelsServiceSettings settings) throws IOException {
this.settings = settings;
this.stub = ((AccountLabelsServiceStubSettings) settings.getStubSettings()).createStub();
}
protected AccountLabelsServiceClient(AccountLabelsServiceStub stub) {
this.settings = null;
this.stub = stub;
}
public final AccountLabelsServiceSettings getSettings() {
return settings;
}
public AccountLabelsServiceStub getStub() {
return stub;
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists the labels owned by an 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 (AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create()) {
* AccountName parent = AccountName.of("[ACCOUNT]");
* for (AccountLabel element :
* accountLabelsServiceClient.listAccountLabels(parent).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
* @param parent Required. The parent account. Format: accounts/{account}
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final ListAccountLabelsPagedResponse listAccountLabels(AccountName parent) {
ListAccountLabelsRequest request =
ListAccountLabelsRequest.newBuilder()
.setParent(parent == null ? null : parent.toString())
.build();
return listAccountLabels(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists the labels owned by an 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 (AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create()) {
* String parent = AccountName.of("[ACCOUNT]").toString();
* for (AccountLabel element :
* accountLabelsServiceClient.listAccountLabels(parent).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
* @param parent Required. The parent account. Format: accounts/{account}
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final ListAccountLabelsPagedResponse listAccountLabels(String parent) {
ListAccountLabelsRequest request =
ListAccountLabelsRequest.newBuilder().setParent(parent).build();
return listAccountLabels(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists the labels owned by an 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 (AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create()) {
* ListAccountLabelsRequest request =
* ListAccountLabelsRequest.newBuilder()
* .setParent(AccountName.of("[ACCOUNT]").toString())
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .build();
* for (AccountLabel element :
* accountLabelsServiceClient.listAccountLabels(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 ListAccountLabelsPagedResponse listAccountLabels(ListAccountLabelsRequest request) {
return listAccountLabelsPagedCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists the labels owned by an 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 (AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create()) {
* ListAccountLabelsRequest request =
* ListAccountLabelsRequest.newBuilder()
* .setParent(AccountName.of("[ACCOUNT]").toString())
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .build();
* ApiFuture<AccountLabel> future =
* accountLabelsServiceClient.listAccountLabelsPagedCallable().futureCall(request);
* // Do something.
* for (AccountLabel element : future.get().iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*/
public final UnaryCallable<ListAccountLabelsRequest, ListAccountLabelsPagedResponse>
listAccountLabelsPagedCallable() {
return stub.listAccountLabelsPagedCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists the labels owned by an 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 (AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create()) {
* ListAccountLabelsRequest request =
* ListAccountLabelsRequest.newBuilder()
* .setParent(AccountName.of("[ACCOUNT]").toString())
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .build();
* while (true) {
* ListAccountLabelsResponse response =
* accountLabelsServiceClient.listAccountLabelsCallable().call(request);
* for (AccountLabel element : response.getAccountLabelsList()) {
* // doThingsWith(element);
* }
* String nextPageToken = response.getNextPageToken();
* if (!Strings.isNullOrEmpty(nextPageToken)) {
* request = request.toBuilder().setPageToken(nextPageToken).build();
* } else {
* break;
* }
* }
* }
* }</pre>
*/
public final UnaryCallable<ListAccountLabelsRequest, ListAccountLabelsResponse>
listAccountLabelsCallable() {
return stub.listAccountLabelsCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Creates a new label, not assigned to any 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 (AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create()) {
* AccountName parent = AccountName.of("[ACCOUNT]");
* AccountLabel accountLabel = AccountLabel.newBuilder().build();
* AccountLabel response = accountLabelsServiceClient.createAccountLabel(parent, accountLabel);
* }
* }</pre>
*
* @param parent Required. The parent account. Format: accounts/{account}
* @param accountLabel Required. The label to create.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final AccountLabel createAccountLabel(AccountName parent, AccountLabel accountLabel) {
CreateAccountLabelRequest request =
CreateAccountLabelRequest.newBuilder()
.setParent(parent == null ? null : parent.toString())
.setAccountLabel(accountLabel)
.build();
return createAccountLabel(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Creates a new label, not assigned to any 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 (AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create()) {
* String parent = AccountName.of("[ACCOUNT]").toString();
* AccountLabel accountLabel = AccountLabel.newBuilder().build();
* AccountLabel response = accountLabelsServiceClient.createAccountLabel(parent, accountLabel);
* }
* }</pre>
*
* @param parent Required. The parent account. Format: accounts/{account}
* @param accountLabel Required. The label to create.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final AccountLabel createAccountLabel(String parent, AccountLabel accountLabel) {
CreateAccountLabelRequest request =
CreateAccountLabelRequest.newBuilder()
.setParent(parent)
.setAccountLabel(accountLabel)
.build();
return createAccountLabel(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Creates a new label, not assigned to any 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 (AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create()) {
* CreateAccountLabelRequest request =
* CreateAccountLabelRequest.newBuilder()
* .setParent(AccountName.of("[ACCOUNT]").toString())
* .setAccountLabel(AccountLabel.newBuilder().build())
* .build();
* AccountLabel response = accountLabelsServiceClient.createAccountLabel(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 AccountLabel createAccountLabel(CreateAccountLabelRequest request) {
return createAccountLabelCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Creates a new label, not assigned to any 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 (AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create()) {
* CreateAccountLabelRequest request =
* CreateAccountLabelRequest.newBuilder()
* .setParent(AccountName.of("[ACCOUNT]").toString())
* .setAccountLabel(AccountLabel.newBuilder().build())
* .build();
* ApiFuture<AccountLabel> future =
* accountLabelsServiceClient.createAccountLabelCallable().futureCall(request);
* // Do something.
* AccountLabel response = future.get();
* }
* }</pre>
*/
public final UnaryCallable<CreateAccountLabelRequest, AccountLabel> createAccountLabelCallable() {
return stub.createAccountLabelCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Updates a label.
*
* <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 (AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create()) {
* AccountLabel accountLabel = AccountLabel.newBuilder().build();
* AccountLabel response = accountLabelsServiceClient.updateAccountLabel(accountLabel);
* }
* }</pre>
*
* @param accountLabel Required. The updated label. All fields must be provided.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final AccountLabel updateAccountLabel(AccountLabel accountLabel) {
UpdateAccountLabelRequest request =
UpdateAccountLabelRequest.newBuilder().setAccountLabel(accountLabel).build();
return updateAccountLabel(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Updates a label.
*
* <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 (AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create()) {
* UpdateAccountLabelRequest request =
* UpdateAccountLabelRequest.newBuilder()
* .setAccountLabel(AccountLabel.newBuilder().build())
* .build();
* AccountLabel response = accountLabelsServiceClient.updateAccountLabel(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 AccountLabel updateAccountLabel(UpdateAccountLabelRequest request) {
return updateAccountLabelCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Updates a label.
*
* <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 (AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create()) {
* UpdateAccountLabelRequest request =
* UpdateAccountLabelRequest.newBuilder()
* .setAccountLabel(AccountLabel.newBuilder().build())
* .build();
* ApiFuture<AccountLabel> future =
* accountLabelsServiceClient.updateAccountLabelCallable().futureCall(request);
* // Do something.
* AccountLabel response = future.get();
* }
* }</pre>
*/
public final UnaryCallable<UpdateAccountLabelRequest, AccountLabel> updateAccountLabelCallable() {
return stub.updateAccountLabelCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Deletes a label and removes it from all accounts to which it was assigned.
*
* <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 (AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create()) {
* AccountLabelName name = AccountLabelName.of("[ACCOUNT]", "[LABEL]");
* accountLabelsServiceClient.deleteAccountLabel(name);
* }
* }</pre>
*
* @param name Required. The name of the label to delete. Format:
* accounts/{account}/labels/{label}
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final void deleteAccountLabel(AccountLabelName name) {
DeleteAccountLabelRequest request =
DeleteAccountLabelRequest.newBuilder()
.setName(name == null ? null : name.toString())
.build();
deleteAccountLabel(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Deletes a label and removes it from all accounts to which it was assigned.
*
* <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 (AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create()) {
* String name = AccountLabelName.of("[ACCOUNT]", "[LABEL]").toString();
* accountLabelsServiceClient.deleteAccountLabel(name);
* }
* }</pre>
*
* @param name Required. The name of the label to delete. Format:
* accounts/{account}/labels/{label}
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final void deleteAccountLabel(String name) {
DeleteAccountLabelRequest request =
DeleteAccountLabelRequest.newBuilder().setName(name).build();
deleteAccountLabel(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Deletes a label and removes it from all accounts to which it was assigned.
*
* <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 (AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create()) {
* DeleteAccountLabelRequest request =
* DeleteAccountLabelRequest.newBuilder()
* .setName(AccountLabelName.of("[ACCOUNT]", "[LABEL]").toString())
* .build();
* accountLabelsServiceClient.deleteAccountLabel(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 void deleteAccountLabel(DeleteAccountLabelRequest request) {
deleteAccountLabelCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Deletes a label and removes it from all accounts to which it was assigned.
*
* <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 (AccountLabelsServiceClient accountLabelsServiceClient =
* AccountLabelsServiceClient.create()) {
* DeleteAccountLabelRequest request =
* DeleteAccountLabelRequest.newBuilder()
* .setName(AccountLabelName.of("[ACCOUNT]", "[LABEL]").toString())
* .build();
* ApiFuture<Empty> future =
* accountLabelsServiceClient.deleteAccountLabelCallable().futureCall(request);
* // Do something.
* future.get();
* }
* }</pre>
*/
public final UnaryCallable<DeleteAccountLabelRequest, Empty> deleteAccountLabelCallable() {
return stub.deleteAccountLabelCallable();
}
@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 ListAccountLabelsPagedResponse
extends AbstractPagedListResponse<
ListAccountLabelsRequest,
ListAccountLabelsResponse,
AccountLabel,
ListAccountLabelsPage,
ListAccountLabelsFixedSizeCollection> {
public static ApiFuture<ListAccountLabelsPagedResponse> createAsync(
PageContext<ListAccountLabelsRequest, ListAccountLabelsResponse, AccountLabel> context,
ApiFuture<ListAccountLabelsResponse> futureResponse) {
ApiFuture<ListAccountLabelsPage> futurePage =
ListAccountLabelsPage.createEmptyPage().createPageAsync(context, futureResponse);
return ApiFutures.transform(
futurePage,
input -> new ListAccountLabelsPagedResponse(input),
MoreExecutors.directExecutor());
}
private ListAccountLabelsPagedResponse(ListAccountLabelsPage page) {
super(page, ListAccountLabelsFixedSizeCollection.createEmptyCollection());
}
}
public static class ListAccountLabelsPage
extends AbstractPage<
ListAccountLabelsRequest,
ListAccountLabelsResponse,
AccountLabel,
ListAccountLabelsPage> {
private ListAccountLabelsPage(
PageContext<ListAccountLabelsRequest, ListAccountLabelsResponse, AccountLabel> context,
ListAccountLabelsResponse response) {
super(context, response);
}
private static ListAccountLabelsPage createEmptyPage() {
return new ListAccountLabelsPage(null, null);
}
@Override
protected ListAccountLabelsPage createPage(
PageContext<ListAccountLabelsRequest, ListAccountLabelsResponse, AccountLabel> context,
ListAccountLabelsResponse response) {
return new ListAccountLabelsPage(context, response);
}
@Override
public ApiFuture<ListAccountLabelsPage> createPageAsync(
PageContext<ListAccountLabelsRequest, ListAccountLabelsResponse, AccountLabel> context,
ApiFuture<ListAccountLabelsResponse> futureResponse) {
return super.createPageAsync(context, futureResponse);
}
}
public static class ListAccountLabelsFixedSizeCollection
extends AbstractFixedSizeCollection<
ListAccountLabelsRequest,
ListAccountLabelsResponse,
AccountLabel,
ListAccountLabelsPage,
ListAccountLabelsFixedSizeCollection> {
private ListAccountLabelsFixedSizeCollection(
List<ListAccountLabelsPage> pages, int collectionSize) {
super(pages, collectionSize);
}
private static ListAccountLabelsFixedSizeCollection createEmptyCollection() {
return new ListAccountLabelsFixedSizeCollection(null, 0);
}
@Override
protected ListAccountLabelsFixedSizeCollection createCollection(
List<ListAccountLabelsPage> pages, int collectionSize) {
return new ListAccountLabelsFixedSizeCollection(pages, collectionSize);
}
}
}
|
apache/hudi | 36,702 | hudi-common/src/main/java/org/apache/hudi/common/util/ConfigUtils.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.common.util;
import org.apache.hudi.common.config.ConfigProperty;
import org.apache.hudi.common.config.HoodieCommonConfig;
import org.apache.hudi.common.config.HoodieConfig;
import org.apache.hudi.common.config.HoodieMetadataConfig;
import org.apache.hudi.common.config.HoodieReaderConfig;
import org.apache.hudi.common.config.PropertiesConfig;
import org.apache.hudi.common.config.TypedProperties;
import org.apache.hudi.common.model.HoodiePayloadProps;
import org.apache.hudi.common.model.HoodieRecordPayload;
import org.apache.hudi.common.table.HoodieTableConfig;
import org.apache.hudi.exception.HoodieIOException;
import org.apache.hudi.exception.HoodieNotSupportedException;
import org.apache.hudi.exception.TableNotFoundException;
import org.apache.hudi.storage.HoodieStorage;
import org.apache.hudi.storage.StorageConfiguration;
import org.apache.hudi.storage.StoragePath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.apache.hudi.common.config.HoodieCommonConfig.DISK_MAP_BITCASK_COMPRESSION_ENABLED;
import static org.apache.hudi.common.config.HoodieCommonConfig.SPILLABLE_DISK_MAP_TYPE;
import static org.apache.hudi.common.config.HoodieMemoryConfig.MAX_MEMORY_FOR_MERGE;
import static org.apache.hudi.common.config.HoodieMemoryConfig.SPILLABLE_MAP_BASE_PATH;
import static org.apache.hudi.common.table.HoodieTableConfig.TABLE_CHECKSUM;
import static org.apache.hudi.keygen.constant.KeyGeneratorOptions.KEYGENERATOR_CONSISTENT_LOGICAL_TIMESTAMP_ENABLED;
public class ConfigUtils {
public static final String STREAMER_CONFIG_PREFIX = "hoodie.streamer.";
@Deprecated
public static final String DELTA_STREAMER_CONFIG_PREFIX = "hoodie.deltastreamer.";
public static final String SCHEMAPROVIDER_CONFIG_PREFIX = STREAMER_CONFIG_PREFIX + "schemaprovider.";
@Deprecated
public static final String OLD_SCHEMAPROVIDER_CONFIG_PREFIX = DELTA_STREAMER_CONFIG_PREFIX + "schemaprovider.";
/**
* Config stored in hive serde properties to tell query engine (spark/flink) to
* read the table as a read-optimized table when this config is true.
*/
public static final String IS_QUERY_AS_RO_TABLE = "hoodie.query.as.ro.table";
/**
* Config stored in hive serde properties to tell query engine (spark) the
* location to read.
*/
public static final String TABLE_SERDE_PATH = "path";
public static final HoodieConfig DEFAULT_HUDI_CONFIG_FOR_READER = new HoodieConfig();
private static final Logger LOG = LoggerFactory.getLogger(ConfigUtils.class);
/**
* Get ordering field.
*/
@Nullable
public static String[] getOrderingFields(Properties properties) {
String orderField = getOrderingFieldsStr(properties);
return StringUtils.isNullOrEmpty(orderField) ? null : orderField.split(",");
}
/**
* Get ordering fields as comma separated string.
*/
@Nullable
public static String getOrderingFieldsStr(Properties properties) {
String orderField = getOrderingFieldsStrDuringWrite(properties);
if (orderField == null && properties.containsKey(HoodiePayloadProps.PAYLOAD_ORDERING_FIELD_PROP_KEY)) {
orderField = properties.getProperty(HoodiePayloadProps.PAYLOAD_ORDERING_FIELD_PROP_KEY);
}
return orderField;
}
/**
* Get ordering fields as comma separated string.
*/
@Nullable
public static String getOrderingFieldsStrDuringWrite(Properties properties) {
String orderField = null;
if (containsConfigProperty(properties, HoodieTableConfig.ORDERING_FIELDS)) {
orderField = getStringWithAltKeys(properties, HoodieTableConfig.ORDERING_FIELDS);
} else if (properties.containsKey("hoodie.datasource.write.precombine.field")) {
orderField = properties.getProperty("hoodie.datasource.write.precombine.field");
}
return orderField;
}
/**
* Get ordering fields as comma separated string.
*/
@Nullable
public static String getOrderingFieldsStrDuringWrite(Map<String, String> properties) {
String orderField = null;
if (containsConfigProperty(properties, HoodieTableConfig.ORDERING_FIELDS)) {
orderField = getStringWithAltKeys(properties, HoodieTableConfig.ORDERING_FIELDS);
} else if (properties.containsKey("hoodie.datasource.write.precombine.field")) {
orderField = properties.get("hoodie.datasource.write.precombine.field");
}
return orderField;
}
/**
* Ensures that ordering field is populated for mergers and legacy payloads.
*
* <p> See also {@link #getOrderingFields(Properties)}.
*/
public static TypedProperties supplementOrderingFields(TypedProperties props, List<String> orderingFields) {
String orderingFieldsAsString = String.join(",", orderingFields);
props.putIfAbsent(HoodiePayloadProps.PAYLOAD_ORDERING_FIELD_PROP_KEY, orderingFieldsAsString);
props.putIfAbsent(HoodieTableConfig.ORDERING_FIELDS.key(), orderingFieldsAsString);
return props;
}
/**
* Ensures that the prefixed merge properties are populated for mergers.
*/
public static TypedProperties getMergeProps(TypedProperties props, HoodieTableConfig tableConfig) {
Map<String, String> mergeProps = tableConfig.getTableMergeProperties();
if (mergeProps.isEmpty()) {
return props;
}
TypedProperties copied = TypedProperties.copy(props);
mergeProps.forEach(copied::setProperty);
return copied;
}
/**
* Get payload class.
*/
public static String getPayloadClass(Properties props) {
return HoodieRecordPayload.getPayloadClassName(props);
}
/**
* Check if event time metadata should be tracked.
*/
public static boolean isTrackingEventTimeWatermark(TypedProperties props) {
return props.getBoolean("hoodie.write.track.event.time.watermark", false);
}
/**
* Check if logical timestamp should be made consistent.
*/
public static boolean shouldKeepConsistentLogicalTimestamp(TypedProperties props) {
return Boolean.parseBoolean(props.getProperty(
KEYGENERATOR_CONSISTENT_LOGICAL_TIMESTAMP_ENABLED.key(),
KEYGENERATOR_CONSISTENT_LOGICAL_TIMESTAMP_ENABLED.defaultValue()));
}
/**
* Extract event_time field name from configuration.
*/
@Nullable
public static String getEventTimeFieldName(TypedProperties props) {
return props.getProperty(HoodiePayloadProps.PAYLOAD_EVENT_TIME_FIELD_PROP_KEY);
}
public static List<String> split2List(String param) {
return StringUtils.split(param, ",").stream()
.map(String::trim).distinct().collect(Collectors.toList());
}
/**
* Convert the key-value config to a map. The format of the config
* is a key-value pair just like "k1=v1\nk2=v2\nk3=v3".
*
* @param keyValueConfig Key-value configs in properties format, i.e., multiple lines of
* `key=value`.
* @return A {@link Map} of key-value configs.
*/
public static Map<String, String> toMap(String keyValueConfig) {
return toMap(keyValueConfig, "\n");
}
/**
* Convert the key-value config to a map. The format of the config is a key-value pair
* with defined separator. For example, if the separator is a comma, the input is
* "k1=v1,k2=v2,k3=v3".
*
* @param keyValueConfig key-value configs in properties format, with defined separator.
* @param separator the separator.
* @return A {@link Map} of key-value configs.
*/
public static Map<String, String> toMap(String keyValueConfig, String separator) {
if (StringUtils.isNullOrEmpty(keyValueConfig)) {
return new HashMap<>();
}
String[] keyvalues = keyValueConfig.split(separator);
Map<String, String> tableProperties = new HashMap<>();
for (String keyValue : keyvalues) {
// Handle multiple new lines and lines that contain only spaces after splitting
if (keyValue.trim().isEmpty()) {
continue;
}
String[] keyValueArray = keyValue.split("=");
if (keyValueArray.length == 1 || keyValueArray.length == 2) {
String key = keyValueArray[0].trim();
String value = keyValueArray.length == 2 ? keyValueArray[1].trim() : "";
tableProperties.put(key, value);
} else {
throw new IllegalArgumentException("Bad key-value config: " + keyValue + ", must be the"
+ " format 'key = value'");
}
}
return tableProperties;
}
/**
* Convert map config to key-value string.The format of the config
* is a key-value pair just like "k1=v1\nk2=v2\nk3=v3".
*
* @param config A {@link Map} of key-value configs.
* @return Key-value configs in properties format, i.e., multiple lines of `key=value`.
*/
public static String configToString(Map<String, String> config) {
if (config == null) {
return null;
}
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : config.entrySet()) {
if (sb.length() > 0) {
sb.append("\n");
}
sb.append(entry.getKey()).append("=").append(entry.getValue());
}
return sb.toString();
}
/**
* Case-insensitive resolution of input enum name to the enum type
*/
public static <T extends Enum<T>> T resolveEnum(Class<T> enumType,
String name) {
T[] enumConstants = enumType.getEnumConstants();
for (T constant : enumConstants) {
if (constant.name().equalsIgnoreCase(name)) {
return constant;
}
}
throw new IllegalArgumentException("No enum constant found " + enumType.getName() + "." + name);
}
public static <T extends Enum<T>> String[] enumNames(Class<T> enumType) {
T[] enumConstants = enumType.getEnumConstants();
return Arrays.stream(enumConstants).map(Enum::name).toArray(String[]::new);
}
/**
* Strips the prefix from a config key. The prefix is defined by a {@link ConfigProperty}
* which can have alternatives. The method strips any matching prefix.
*
* @param prop The config key for stripping
* @param prefixConfig The prefix.
* @return An {@link Option} of the config key after stripping, if any prefix matches the key;
* empty {@link Option} otherwise.
*/
public static Option<String> stripPrefix(String prop, ConfigProperty<String> prefixConfig) {
if (prop.startsWith(prefixConfig.key())) {
return Option.of(String.join("", prop.split(prefixConfig.key())));
}
for (String altPrefix : prefixConfig.getAlternatives()) {
if (prop.startsWith(altPrefix)) {
return Option.of(String.join("", prop.split(altPrefix)));
}
}
return Option.empty();
}
/**
* Whether the properties contain a config. If any of the key or alternative keys of the
* {@link ConfigProperty} exists in the properties, this method returns {@code true}.
*
* @param props Configs in {@link Properties}
* @param configProperty Config to look up.
* @return {@code true} if exists; {@code false} otherwise.
*/
public static boolean containsConfigProperty(Properties props,
ConfigProperty<?> configProperty) {
if (!props.containsKey(configProperty.key())) {
for (String alternative : configProperty.getAlternatives()) {
if (props.containsKey(alternative)) {
return true;
}
}
return false;
}
return true;
}
/**
* Whether the properties contain a config. If any of the key or alternative keys of the
* {@link ConfigProperty} exists in the properties, this method returns {@code true}.
*
* @param props Configs in {@link Map}
* @param configProperty Config to look up.
* @return {@code true} if exists; {@code false} otherwise.
*/
public static boolean containsConfigProperty(Map<String, ?> props,
ConfigProperty<?> configProperty) {
return containsConfigProperty(props::containsKey, configProperty);
}
/**
* Whether the properties contain a config. If any of the key or alternative keys of the
* {@link ConfigProperty} exists, this method returns {@code true}.
*
* @param keyExistsFn Function to check if key exists
* @param configProperty Config to look up.
* @return {@code true} if exists; {@code false} otherwise.
*/
public static boolean containsConfigProperty(Function<String, Boolean> keyExistsFn,
ConfigProperty<?> configProperty) {
if (!keyExistsFn.apply(configProperty.key())) {
for (String alternative : configProperty.getAlternatives()) {
if (keyExistsFn.apply(alternative)) {
return true;
}
}
return false;
}
return true;
}
/**
* Validates that config String keys exist in the properties.
*
* @param props Configs in {@link TypedProperties} to validate.
* @param checkPropNames List of String keys that must exist.
*/
public static void checkRequiredProperties(TypedProperties props, List<String> checkPropNames) {
checkPropNames.forEach(prop -> {
if (!props.containsKey(prop)) {
throw new HoodieNotSupportedException("Required property " + prop + " is missing");
}
});
}
/**
* Validates that all {@link ConfigProperty} configs exist in the properties. For each
* {@link ConfigProperty} config, if any of the key or alternative keys of the
* {@link ConfigProperty} exists in the properties, the validation of this config passes.
*
* @param props Configs in {@link TypedProperties} to validate.
* @param configPropertyList List of {@link ConfigProperty} configs that must exist.
*/
public static void checkRequiredConfigProperties(TypedProperties props,
List<ConfigProperty<?>> configPropertyList) {
configPropertyList.forEach(configProperty -> {
if (!containsConfigProperty(props, configProperty)) {
throw new HoodieNotSupportedException("Required property " + configProperty.key() + " is missing");
}
});
}
/**
* Gets the raw value for a {@link ConfigProperty} config from properties. The key and
* alternative keys are used to fetch the config.
*
* @param props Configs in {@link Properties}.
* @param configProperty {@link ConfigProperty} config to fetch.
* @return {@link Option} of value if the config exists; empty {@link Option} otherwise.
*/
public static Option<Object> getRawValueWithAltKeys(Properties props,
ConfigProperty<?> configProperty) {
if (props.containsKey(configProperty.key())) {
return Option.ofNullable(props.get(configProperty.key()));
}
for (String alternative : configProperty.getAlternatives()) {
if (props.containsKey(alternative)) {
deprecationWarning(alternative, configProperty);
return Option.ofNullable(props.get(alternative));
}
}
return Option.empty();
}
/**
* Gets the raw value for a {@link ConfigProperty<T>} config from properties with the option
* of using default value.
*
* @param props Configs in {@link Properties}.
* @param configProperty {@link ConfigProperty} config to fetch.
* @param useDefaultValue If enabled, uses default value for configProperty.
* @return raw value of the config.
* @param <T> type of the value.
*/
public static <T> T getRawValueWithAltKeys(Properties props, ConfigProperty<T> configProperty, boolean useDefaultValue) {
Option<T> rawValue = (Option<T>) getRawValueWithAltKeys(props, configProperty);
if (rawValue.isPresent()) {
return rawValue.get();
}
if (useDefaultValue) {
return configProperty.defaultValue();
}
throw new IllegalArgumentException("Property " + configProperty.key() + " not found");
}
/**
* Gets the String value for a {@link ConfigProperty} config from properties. The key and
* alternative keys are used to fetch the config. If the config is not found, an
* {@link IllegalArgumentException} is thrown.
*
* @param props Configs in {@link Properties}.
* @param configProperty {@link ConfigProperty} config of String type to fetch.
* @return String value if the config exists.
*/
public static String getStringWithAltKeys(Properties props,
ConfigProperty<String> configProperty) {
return getStringWithAltKeys(props, configProperty, false);
}
/**
* Gets the String value for a {@link ConfigProperty} config from properties. The key and
* alternative keys are used to fetch the config. If using default value, the default value
* of {@link ConfigProperty} config, if exists, is returned if the config is not found in
* the properties. If not using default value, if the config is not found, an
* {@link IllegalArgumentException} is thrown.
*
* @param props Configs in {@link Properties}.
* @param configProperty {@link ConfigProperty} config of String type to fetch.
* @param useDefaultValue Whether to use default value from {@link ConfigProperty}.
* @return String value if the config exists; otherwise, if the config does not exist and
* {@code useDefaultValue} is true, returns default String value if there is default value
* defined in the {@link ConfigProperty} config and {@code null} otherwise.
*/
public static String getStringWithAltKeys(Properties props,
ConfigProperty<String> configProperty,
boolean useDefaultValue) {
if (useDefaultValue) {
return getStringWithAltKeys(
props, configProperty, configProperty.hasDefaultValue() ? configProperty.defaultValue() : null);
}
Option<Object> rawValue = getRawValueWithAltKeys(props, configProperty);
if (!rawValue.isPresent()) {
throw new IllegalArgumentException("Property " + configProperty.key() + " not found");
}
return rawValue.get().toString();
}
/**
* Gets the String value for a {@link ConfigProperty} config from properties. The key and
* alternative keys are used to fetch the config. The default value as the input of the method
* is returned if the config is not found in the properties.
*
* @param props Configs in {@link Properties}.
* @param configProperty {@link ConfigProperty} config of String type to fetch.
* @param defaultValue Default value.
* @return String value if the config exists; default value otherwise.
*/
public static String getStringWithAltKeys(Properties props,
ConfigProperty<?> configProperty,
String defaultValue) {
Option<Object> rawValue = getRawValueWithAltKeys(props, configProperty);
return rawValue.map(Object::toString).orElse(defaultValue);
}
/**
* Gets the String value for a {@link ConfigProperty} config from a {@link Map}. The key
* and alternative keys are used to fetch the config. The default value of {@link ConfigProperty}
* config, if exists, is returned if the config is not found in the properties.
*
* @param props Configs in {@link Map}.
* @param configProperty {@link ConfigProperty} config to fetch.
* @return String value if the config exists; default String value if the config does not exist
* and there is default value defined in the {@link ConfigProperty} config and is convertible to
* String type; {@code null} otherwise.
*/
public static <V> String getStringWithAltKeys(Map<String, V> props,
ConfigProperty<?> configProperty) {
return getStringWithAltKeys(props::get, configProperty);
}
/**
* Gets the String value for a {@link ConfigProperty} config using a key mapping function. The key
* and alternative keys are used to fetch the config. The default value of {@link ConfigProperty}
* config, if exists, is returned if the config is not found in the properties.
*
* @param keyMapper Mapper function to map the key to values.
* @param configProperty {@link ConfigProperty} config to fetch.
* @return String value if the config exists; default String value if the config does not exist
* and there is default value defined in the {@link ConfigProperty} config and is convertible to
* String type; {@code null} otherwise.
*/
public static String getStringWithAltKeys(Function<String, Object> keyMapper,
ConfigProperty<?> configProperty) {
Object value = keyMapper.apply(configProperty.key());
if (value != null) {
return value.toString();
}
for (String alternative : configProperty.getAlternatives()) {
value = keyMapper.apply(alternative);
if (value != null) {
deprecationWarning(alternative, configProperty);
return value.toString();
}
}
return configProperty.hasDefaultValue() ? configProperty.defaultValue().toString() : null;
}
private static void deprecationWarning(String alternative, ConfigProperty<?> configProperty) {
LOG.warn("The configuration key '{}' has been deprecated and may be removed in the future."
+ " Please use the new key '{}' instead.", alternative, configProperty.key());
}
/**
* Gets String value from properties with alternative keys.
*
* @param props Configs in {@link TypedProperties}.
* @param key String key.
* @param altKey Alternative String key.
* @param defaultValue Default String value.
* @return String value if the config exists; default value otherwise.
*/
public static String getStringWithAltKeys(TypedProperties props,
String key, String altKey,
String defaultValue) {
if (props.containsKey(altKey)) {
return props.getString(altKey);
}
if (props.containsKey(key)) {
return props.getString(key);
}
return defaultValue;
}
/**
* Gets the boolean value for a {@link ConfigProperty} config from properties. The key and
* alternative keys are used to fetch the config. The default value of {@link ConfigProperty}
* config, if exists, is returned if the config is not found in the properties.
*
* @param props Configs in {@link Properties}.
* @param configProperty {@link ConfigProperty} config to fetch.
* @return boolean value if the config exists; default boolean value if the config does not exist
* and there is default value defined in the {@link ConfigProperty} config; {@code false} otherwise.
*/
public static boolean getBooleanWithAltKeys(Properties props,
ConfigProperty<?> configProperty) {
Option<Object> rawValue = getRawValueWithAltKeys(props, configProperty);
boolean defaultValue = configProperty.hasDefaultValue() && Boolean.parseBoolean(configProperty.defaultValue().toString());
return rawValue.map(v -> Boolean.parseBoolean(v.toString())).orElse(defaultValue);
}
/**
* Gets the integer value for a {@link ConfigProperty} config from properties. The key and
* alternative keys are used to fetch the config. The default value of {@link ConfigProperty}
* config, if exists, is returned if the config is not found in the properties.
*
* @param props Configs in {@link Properties}.
* @param configProperty {@link ConfigProperty} config to fetch.
* @return integer value if the config exists; default integer value if the config does not exist
* and there is default value defined in the {@link ConfigProperty} config; {@code 0} otherwise.
*/
public static int getIntWithAltKeys(Properties props,
ConfigProperty<?> configProperty) {
Option<Object> rawValue = getRawValueWithAltKeys(props, configProperty);
int defaultValue = configProperty.hasDefaultValue()
? Integer.parseInt(configProperty.defaultValue().toString()) : 0;
return rawValue.map(v -> Integer.parseInt(v.toString())).orElse(defaultValue);
}
/**
* Gets the long value for a {@link ConfigProperty} config from properties. The key and
* alternative keys are used to fetch the config. The default value of {@link ConfigProperty}
* config, if exists, is returned if the config is not found in the properties.
*
* @param props Configs in {@link TypedProperties}.
* @param configProperty {@link ConfigProperty} config to fetch.
* @return long value if the config exists; default long value if the config does not exist
* and there is default value defined in the {@link ConfigProperty} config; {@code 0} otherwise.
*/
public static long getLongWithAltKeys(TypedProperties props,
ConfigProperty<Long> configProperty) {
Option<Object> rawValue = getRawValueWithAltKeys(props, configProperty);
long defaultValue = configProperty.hasDefaultValue()
? configProperty.defaultValue() : 0L;
return rawValue.map(v -> Long.parseLong(v.toString())).orElse(defaultValue);
}
/**
* Removes a {@link ConfigProperty} config from properties. This removes all possible keys
* including the alternatives from the properties.
*
* @param props Configs in {@link TypedProperties}.
* @param configProperty {@link ConfigProperty} config to remove.
*/
public static void removeConfigFromProps(TypedProperties props,
ConfigProperty<?> configProperty) {
props.remove(configProperty.key());
for (String alternative : configProperty.getAlternatives()) {
props.remove(alternative);
}
}
/**
* Returns filtered properties based on the given {@link ConfigProperty} config list to keep.
*
* @param props Configs in {@link TypedProperties}.
* @param configPropertyList List of {@link ConfigProperty} configs to keep.
* @return Filtered configs in {@link Map} with {@link ConfigProperty} configs to keep.
*/
public static Map<String, Object> filterProperties(TypedProperties props,
List<ConfigProperty<String>> configPropertyList) {
Set<String> persistedKeys = getAllConfigKeys(configPropertyList);
return props.entrySet().stream()
.filter(p -> persistedKeys.contains(String.valueOf(p.getKey())))
.collect(Collectors.toMap(e -> String.valueOf(e.getKey()), e -> String.valueOf(e.getValue())));
}
/**
* @param configPropertyList List of {@link ConfigProperty} configs to keep.
* @return all String keys of {@link ConfigProperty} configs.
*/
public static Set<String> getAllConfigKeys(List<ConfigProperty<String>> configPropertyList) {
return configPropertyList.stream().flatMap(configProperty -> {
List<String> keys = new ArrayList<>();
keys.add(configProperty.key());
keys.addAll(configProperty.getAlternatives());
return keys.stream();
}).collect(Collectors.toSet());
}
public static TypedProperties fetchConfigs(
HoodieStorage storage,
StoragePath metaPath,
String propertiesFile,
String propertiesBackupFile,
int maxReadRetries,
int maxReadRetryDelayInMs) throws IOException {
StoragePath cfgPath = new StoragePath(metaPath, propertiesFile);
StoragePath backupCfgPath = new StoragePath(metaPath, propertiesBackupFile);
int readRetryCount = 0;
boolean found = false;
TypedProperties props = new TypedProperties();
while (readRetryCount++ < maxReadRetries) {
for (StoragePath path : Arrays.asList(cfgPath, backupCfgPath)) {
// Read the properties and validate that it is a valid file
try (InputStream is = storage.open(path)) {
props.clear();
props.load(is);
found = true;
if (props.containsKey(TABLE_CHECKSUM.key())) {
ValidationUtils.checkArgument(HoodieTableConfig.validateChecksum(props));
}
return props;
} catch (IOException e) {
LOG.warn("Could not read properties from {}: {}", path, e);
} catch (IllegalArgumentException e) {
LOG.warn("Invalid properties file {}: {}", path, props);
}
}
// Failed to read all files so wait before retrying. This can happen in cases of parallel updates to the properties.
try {
Thread.sleep(maxReadRetryDelayInMs);
} catch (InterruptedException e) {
LOG.warn("Interrupted while waiting");
}
}
// If we are here then after all retries either no properties file was found or only an invalid file was found.
if (found) {
throw new IllegalArgumentException(
"hoodie.properties file seems invalid. Please check for left over `.updated` files if any, manually copy it to hoodie.properties and retry");
} else if (!storage.exists(metaPath)) {
throw new TableNotFoundException(metaPath.toString());
} else {
throw new HoodieIOException("Could not load Hoodie properties from " + cfgPath);
}
}
public static void recoverIfNeeded(HoodieStorage storage, StoragePath cfgPath,
StoragePath backupCfgPath) throws IOException {
boolean needCopy = false;
if (!storage.exists(cfgPath)) {
needCopy = true;
} else {
TypedProperties props = new TypedProperties();
try (InputStream in = storage.open(cfgPath)) {
props.load(in);
if (!props.containsKey(TABLE_CHECKSUM.key()) || !HoodieTableConfig.validateChecksum(props)) {
// the cfg file is invalid
storage.deleteFile(cfgPath);
needCopy = true;
}
}
}
if (needCopy && storage.exists(backupCfgPath)) {
byte[] bytes = FileIOUtils.readAsByteArray(storage.open(backupCfgPath));
// check whether existing backup file is valid or not
try (InputStream backupStream = new ByteArrayInputStream(bytes)) {
TypedProperties backupProps = new TypedProperties();
backupProps.load(backupStream);
if (!backupProps.containsKey(TABLE_CHECKSUM.key()) || !HoodieTableConfig.validateChecksum(backupProps)) {
// need to delete the backup as anyway reads will also fail
// subsequent writes will recover and update
storage.deleteFile(backupCfgPath);
LOG.error("Invalid properties file {}: {}", backupCfgPath, backupProps);
throw new IOException("Corrupted backup file");
}
// copy over from backup
try (OutputStream out = storage.create(cfgPath, false)) {
out.write(bytes);
}
}
}
// regardless, we don't need the backup anymore.
storage.deleteFile(backupCfgPath);
}
public static void upsertProperties(Properties current, Properties updated) {
updated.forEach((k, v) -> current.setProperty(k.toString(), v.toString()));
}
public static void deleteProperties(Properties current, Properties deleted) {
deleted.forEach((k, v) -> current.remove(k.toString()));
}
public static HoodieConfig getReaderConfigs(StorageConfiguration<?> storageConf) {
HoodieConfig config = new HoodieConfig();
config.setAll(DEFAULT_HUDI_CONFIG_FOR_READER.getProps());
return config;
}
/**
* Apply HFile cache configurations from options to a HoodieConfig.
* This method extracts HFile cache-related settings from the provided options map
* and applies them to the given HoodieConfig instance.
*
* @param options Map of options containing HFile cache configurations
* @return HoodieConfig with HFile reader configurations
*/
public static HoodieReaderConfig getHFileCacheConfigs(Map<String, String> options) {
HoodieReaderConfig config = new HoodieReaderConfig();
config.setValue(HoodieReaderConfig.HFILE_BLOCK_CACHE_ENABLED,
getStringWithAltKeys(options, HoodieReaderConfig.HFILE_BLOCK_CACHE_ENABLED));
config.setValue(HoodieReaderConfig.HFILE_BLOCK_CACHE_SIZE,
getStringWithAltKeys(options, HoodieReaderConfig.HFILE_BLOCK_CACHE_SIZE));
config.setValue(HoodieReaderConfig.HFILE_BLOCK_CACHE_TTL_MINUTES,
getStringWithAltKeys(options, HoodieReaderConfig.HFILE_BLOCK_CACHE_TTL_MINUTES));
return config;
}
public static TypedProperties loadGlobalProperties() {
return ((PropertiesConfig) ReflectionUtils.loadClass("org.apache.hudi.common.config.DFSPropertiesConfiguration")).getGlobalProperties();
}
/**
* Extract all properties whose keys start with a given prefix.
* E.g., if the prefix is "a.b.c.", and the props contain:
* "a.b.c.K1=V1", "a.b.c.K2=V2", "a.b.c.K3=V3".
* Then the output is:
* Map(K1->V1, K2->V2, K3->V3).
*/
public static Map<String, String> extractWithPrefix(TypedProperties props, String prefix) {
if (props == null || props.isEmpty()) {
return Collections.emptyMap();
}
int prefixLength = prefix.length();
Map<String, String> mergeProperties = new HashMap<>();
for (Map.Entry<Object, Object> entry : props.entrySet()) {
String key = entry.getKey().toString();
// Early exit if key is shorter than prefix or doesn't start with prefix
if (key.length() <= prefixLength || !key.startsWith(prefix)) {
continue;
}
// Extract and validate the property key
String propKey = key.substring(prefixLength).trim();
if (propKey.isEmpty()) {
continue;
}
// Extract and trim the value
Object value = entry.getValue();
String stringValue = (value != null) ? value.toString().trim() : "";
mergeProperties.put(propKey, stringValue);
}
return mergeProperties;
}
/**
* Derive necessary properties for FG reader.
*/
public static TypedProperties buildFileGroupReaderProperties(HoodieMetadataConfig metadataConfig,
boolean shouldReuse) {
HoodieCommonConfig commonConfig = HoodieCommonConfig.newBuilder()
.fromProperties(metadataConfig.getProps()).build();
TypedProperties props = new TypedProperties();
props.setProperty(
MAX_MEMORY_FOR_MERGE.key(),
Long.toString(metadataConfig.getMaxReaderMemory()));
props.setProperty(
SPILLABLE_MAP_BASE_PATH.key(),
metadataConfig.getSplliableMapDir());
props.setProperty(
SPILLABLE_DISK_MAP_TYPE.key(),
commonConfig.getSpillableDiskMapType().name());
props.setProperty(
DISK_MAP_BITCASK_COMPRESSION_ENABLED.key(),
Boolean.toString(commonConfig.isBitCaskDiskMapCompressionEnabled()));
props.setProperty(HoodieReaderConfig.HFILE_BLOCK_CACHE_ENABLED.key(),
shouldReuse ? "true" : metadataConfig.getStringOrDefault(HoodieReaderConfig.HFILE_BLOCK_CACHE_ENABLED));
props.setProperty(HoodieReaderConfig.HFILE_BLOCK_CACHE_ENABLED.key(),
metadataConfig.getStringOrDefault(HoodieReaderConfig.HFILE_BLOCK_CACHE_ENABLED));
props.setProperty(HoodieReaderConfig.HFILE_BLOCK_CACHE_SIZE.key(),
metadataConfig.getStringOrDefault(HoodieReaderConfig.HFILE_BLOCK_CACHE_SIZE));
props.setProperty(HoodieReaderConfig.HFILE_BLOCK_CACHE_TTL_MINUTES.key(),
metadataConfig.getStringOrDefault(HoodieReaderConfig.HFILE_BLOCK_CACHE_TTL_MINUTES));
return props;
}
}
|
apache/poi | 36,502 | poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java | /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.xssf.usermodel;
import static org.apache.poi.xssf.usermodel.XSSFRelation.NS_DRAWINGML;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.awt.Color;
import java.io.IOException;
import java.util.List;
import org.apache.poi.hssf.HSSFTestDataSamples;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ooxml.POIXMLDocumentPart.RelationPart;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.FontUnderline;
import org.apache.poi.ss.usermodel.ShapeTypes;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.Units;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.junit.jupiter.api.Test;
import org.openxmlformats.schemas.drawingml.x2006.main.CTGroupTransform2D;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph;
import org.openxmlformats.schemas.drawingml.x2006.main.STTextUnderlineType;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTDrawing;
class TestXSSFDrawing {
@Test
void bug54803() throws Exception {
try (XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("bug54803.xlsx")) {
XSSFSheet sheet = wb.getSheetAt(0);
sheet.createDrawingPatriarch();
try (XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb)) {
XSSFSheet sheet2 = wb2.getSheetAt(0);
assertNotNull(sheet2.getDrawingPatriarch());
}
}
}
@Test
void testRead() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx");
XSSFSheet sheet = wb.getSheetAt(0);
//the sheet has one relationship and it is XSSFDrawing
List<RelationPart> rels = sheet.getRelationParts();
assertEquals(1, rels.size());
RelationPart rp = rels.get(0);
assertTrue(rp.getDocumentPart() instanceof XSSFDrawing);
XSSFDrawing drawing = rp.getDocumentPart();
//sheet.createDrawingPatriarch() should return the same instance of XSSFDrawing
assertSame(drawing, sheet.createDrawingPatriarch());
String drawingId = rp.getRelationship().getId();
//there should be a relation to this drawing in the worksheet
assertTrue(sheet.getCTWorksheet().isSetDrawing());
assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId());
List<XSSFShape> shapes = drawing.getShapes();
assertEquals(6, shapes.size());
assertTrue(shapes.get(0) instanceof XSSFPicture);
assertTrue(shapes.get(1) instanceof XSSFPicture);
assertTrue(shapes.get(2) instanceof XSSFPicture);
assertTrue(shapes.get(3) instanceof XSSFPicture);
assertTrue(shapes.get(4) instanceof XSSFSimpleShape);
assertTrue(shapes.get(5) instanceof XSSFPicture);
for(XSSFShape sh : shapes) assertNotNull(sh.getAnchor());
checkRewrite(wb);
wb.close();
}
@Test
void testNew() throws IOException {
XSSFWorkbook wb1 = new XSSFWorkbook();
XSSFSheet sheet = wb1.createSheet();
//multiple calls of createDrawingPatriarch should return the same instance of XSSFDrawing
XSSFDrawing dr1 = sheet.createDrawingPatriarch();
XSSFDrawing dr2 = sheet.createDrawingPatriarch();
assertSame(dr1, dr2);
List<RelationPart> rels = sheet.getRelationParts();
assertEquals(1, rels.size());
RelationPart rp = rels.get(0);
assertTrue(rp.getDocumentPart() instanceof XSSFDrawing);
XSSFDrawing drawing = rp.getDocumentPart();
String drawingId = rp.getRelationship().getId();
//there should be a relation to this drawing in the worksheet
assertTrue(sheet.getCTWorksheet().isSetDrawing());
assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId());
XSSFConnector c1= drawing.createConnector(new XSSFClientAnchor(0,0,0,0,0,0,2,2));
c1.setLineWidth(2.5);
c1.setLineStyle(1);
XSSFShapeGroup c2 = drawing.createGroup(new XSSFClientAnchor(0,0,0,0,0,0,5,5));
assertNotNull(c2);
XSSFSimpleShape c3 = drawing.createSimpleShape(new XSSFClientAnchor(0,0,0,0,2,2,3,4));
c3.setText(new XSSFRichTextString("Test String"));
c3.setFillColor(128, 128, 128);
XSSFTextBox c4 = drawing.createTextbox(new XSSFClientAnchor(0,0,0,0,4,4,5,6));
XSSFRichTextString rt = new XSSFRichTextString("Test String");
rt.applyFont(0, 5, wb1.createFont());
rt.applyFont(5, 6, wb1.createFont());
c4.setText(rt);
c4.setNoFill(true);
assertEquals(4, drawing.getCTDrawing().sizeOfTwoCellAnchorArray());
List<XSSFShape> shapes = drawing.getShapes();
assertEquals(4, shapes.size());
assertTrue(shapes.get(0) instanceof XSSFConnector);
assertTrue(shapes.get(1) instanceof XSSFShapeGroup);
assertTrue(shapes.get(2) instanceof XSSFSimpleShape);
assertTrue(shapes.get(3) instanceof XSSFSimpleShape); //
// Save and re-load it
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
wb1.close();
sheet = wb2.getSheetAt(0);
// Check
dr1 = sheet.createDrawingPatriarch();
CTDrawing ctDrawing = dr1.getCTDrawing();
// Connector, shapes and text boxes are all two cell anchors
assertEquals(0, ctDrawing.sizeOfAbsoluteAnchorArray());
assertEquals(0, ctDrawing.sizeOfOneCellAnchorArray());
assertEquals(4, ctDrawing.sizeOfTwoCellAnchorArray());
shapes = dr1.getShapes();
assertEquals(4, shapes.size());
assertTrue(shapes.get(0) instanceof XSSFConnector);
assertTrue(shapes.get(1) instanceof XSSFShapeGroup);
assertTrue(shapes.get(2) instanceof XSSFSimpleShape);
assertTrue(shapes.get(3) instanceof XSSFSimpleShape); //
// Ensure it got the right namespaces
String xml = ctDrawing.toString();
assertTrue(xml.contains("xmlns:xdr=\"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing\""));
assertTrue(xml.contains("xmlns:a=\"" + NS_DRAWINGML + '\"'));
checkRewrite(wb2);
wb2.close();
}
@Test
void testMultipleDrawings() throws IOException{
XSSFWorkbook wb = new XSSFWorkbook();
for (int i = 0; i < 3; i++) {
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
assertNotNull(drawing);
}
try (OPCPackage pkg = wb.getPackage()) {
assertEquals(3, pkg.getPartsByContentType(XSSFRelation.DRAWINGS.getContentType()).size());
checkRewrite(wb);
}
wb.close();
}
@Test
void testClone() throws Exception{
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx");
XSSFSheet sheet1 = wb.getSheetAt(0);
XSSFSheet sheet2 = wb.cloneSheet(0);
//the source sheet has one relationship and it is XSSFDrawing
List<POIXMLDocumentPart> rels1 = sheet1.getRelations();
assertEquals(1, rels1.size());
assertTrue(rels1.get(0) instanceof XSSFDrawing);
List<POIXMLDocumentPart> rels2 = sheet2.getRelations();
assertEquals(1, rels2.size());
assertTrue(rels2.get(0) instanceof XSSFDrawing);
XSSFDrawing drawing1 = (XSSFDrawing)rels1.get(0);
XSSFDrawing drawing2 = (XSSFDrawing)rels2.get(0);
assertNotSame(drawing1, drawing2); // drawing2 is a clone of drawing1
List<XSSFShape> shapes1 = drawing1.getShapes();
List<XSSFShape> shapes2 = drawing2.getShapes();
assertEquals(shapes1.size(), shapes2.size());
for(int i = 0; i < shapes1.size(); i++){
XSSFShape sh1 = shapes1.get(i);
XSSFShape sh2 = shapes2.get(i);
assertSame(sh1.getClass(), sh2.getClass());
assertEquals(sh1.getShapeProperties().toString(), sh2.getShapeProperties().toString());
}
checkRewrite(wb);
wb.close();
}
/**
* ensure that rich text attributes defined in a XSSFRichTextString
* are passed to XSSFSimpleShape.
*
* See Bugzilla 52219.
*/
@Test
void testRichText() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4));
XSSFRichTextString rt = new XSSFRichTextString("Test String");
XSSFFont font = wb.createFont();
font.setColor(new XSSFColor(new Color(0, 128, 128), wb.getStylesSource().getIndexedColors()));
font.setItalic(true);
font.setBold(true);
font.setUnderline(FontUnderline.SINGLE);
rt.applyFont(font);
shape.setText(rt);
CTTextParagraph pr = shape.getCTShape().getTxBody().getPArray(0);
assertEquals(1, pr.sizeOfRArray());
CTTextCharacterProperties rPr = pr.getRArray(0).getRPr();
assertTrue(rPr.getB());
assertTrue(rPr.getI());
assertEquals(STTextUnderlineType.SNG, rPr.getU());
assertArrayEquals(
new byte[]{-1, 0, (byte)128, (byte)128} ,
rPr.getSolidFill().getSrgbClr().getVal());
checkRewrite(wb);
wb.close();
}
/**
* test that anchor is not null when reading shapes from existing drawings
*/
@Test
void testReadAnchors() throws IOException {
XSSFWorkbook wb1 = new XSSFWorkbook();
XSSFSheet sheet = wb1.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor1 = new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4);
XSSFShape shape1 = drawing.createTextbox(anchor1);
assertNotNull(shape1);
XSSFClientAnchor anchor2 = new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 5);
XSSFShape shape2 = drawing.createTextbox(anchor2);
assertNotNull(shape2);
int pictureIndex= wb1.addPicture(new byte[]{}, XSSFWorkbook.PICTURE_TYPE_PNG);
XSSFClientAnchor anchor3 = new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 6);
XSSFShape shape3 = drawing.createPicture(anchor3, pictureIndex);
assertNotNull(shape3);
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
wb1.close();
sheet = wb2.getSheetAt(0);
drawing = sheet.createDrawingPatriarch();
List<XSSFShape> shapes = drawing.getShapes();
assertEquals(shapes.get(0).getAnchor(), anchor1);
assertEquals(shapes.get(1).getAnchor(), anchor2);
assertEquals(shapes.get(2).getAnchor(), anchor3);
checkRewrite(wb2);
wb2.close();
}
/**
* ensure that font and color rich text attributes defined in a XSSFRichTextString
* are passed to XSSFSimpleShape.
*
* See Bugzilla 54969.
*/
@Test
void testRichTextFontAndColor() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4));
XSSFRichTextString rt = new XSSFRichTextString("Test String");
XSSFFont font = wb.createFont();
font.setColor(new XSSFColor(new Color(0, 128, 128), wb.getStylesSource().getIndexedColors()));
font.setFontName("Arial");
rt.applyFont(font);
shape.setText(rt);
CTTextParagraph pr = shape.getCTShape().getTxBody().getPArray(0);
assertEquals(1, pr.sizeOfRArray());
CTTextCharacterProperties rPr = pr.getRArray(0).getRPr();
assertEquals("Arial", rPr.getLatin().getTypeface());
assertArrayEquals(
new byte[]{-1, 0, (byte)128, (byte)128} ,
rPr.getSolidFill().getSrgbClr().getVal());
checkRewrite(wb);
wb.close();
}
/**
* Test setText single paragraph to ensure backwards compatibility
*/
@Test
void testSetTextSingleParagraph() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4));
XSSFRichTextString rt = new XSSFRichTextString("Test String");
XSSFFont font = wb.createFont();
font.setColor(new XSSFColor(new Color(0, 255, 255), wb.getStylesSource().getIndexedColors()));
font.setFontName("Arial");
rt.applyFont(font);
shape.setText(rt);
List<XSSFTextParagraph> paras = shape.getTextParagraphs();
assertEquals(1, paras.size());
assertEquals("Test String", paras.get(0).getText());
List<XSSFTextRun> runs = paras.get(0).getTextRuns();
assertEquals(1, runs.size());
assertEquals("Arial", runs.get(0).getFontFamily());
Color clr = runs.get(0).getFontColor();
assertArrayEquals(
new int[] { 0, 255, 255 } ,
new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() });
checkRewrite(wb);
wb.close();
}
/**
* Test addNewTextParagraph
*/
@Test
void testAddNewTextParagraph() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4));
XSSFTextParagraph para = shape.addNewTextParagraph();
para.addNewTextRun().setText("Line 1");
List<XSSFTextParagraph> paras = shape.getTextParagraphs();
assertEquals(2, paras.size()); // this should be 2 as XSSFSimpleShape creates a default paragraph (no text), and then we add a string to that.
List<XSSFTextRun> runs = para.getTextRuns();
assertEquals(1, runs.size());
assertEquals("Line 1", runs.get(0).getText());
checkRewrite(wb);
wb.close();
}
/**
* Test addNewTextParagraph using RichTextString
*/
@Test
void testAddNewTextParagraphWithRTS() throws IOException {
XSSFWorkbook wb1 = new XSSFWorkbook();
XSSFSheet sheet = wb1.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4));
XSSFRichTextString rt = new XSSFRichTextString("Test Rich Text String");
XSSFFont font = wb1.createFont();
font.setColor(new XSSFColor(new Color(0, 255, 255), wb1.getStylesSource().getIndexedColors()));
font.setFontName("Arial");
rt.applyFont(font);
XSSFFont midfont = wb1.createFont();
midfont.setColor(new XSSFColor(new Color(0, 255, 0), wb1.getStylesSource().getIndexedColors()));
rt.applyFont(5, 14, midfont); // set the text "Rich Text" to be green and the default font
XSSFTextParagraph para = shape.addNewTextParagraph(rt);
// Save and re-load it
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
wb1.close();
sheet = wb2.getSheetAt(0);
// Check
drawing = sheet.createDrawingPatriarch();
List<XSSFShape> shapes = drawing.getShapes();
assertEquals(1, shapes.size());
assertTrue(shapes.get(0) instanceof XSSFSimpleShape);
XSSFSimpleShape sshape = (XSSFSimpleShape) shapes.get(0);
List<XSSFTextParagraph> paras = sshape.getTextParagraphs();
assertEquals(2, paras.size()); // this should be 2 as XSSFSimpleShape creates a default paragraph (no text), and then we add a string to that.
List<XSSFTextRun> runs = para.getTextRuns();
assertEquals(3, runs.size());
// first run properties
assertEquals("Test ", runs.get(0).getText());
assertEquals("Arial", runs.get(0).getFontFamily());
Color clr = runs.get(0).getFontColor();
assertArrayEquals(
new int[] { 0, 255, 255 } ,
new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() });
// second run properties
assertEquals("Rich Text", runs.get(1).getText());
assertEquals(XSSFFont.DEFAULT_FONT_NAME, runs.get(1).getFontFamily());
clr = runs.get(1).getFontColor();
assertArrayEquals(
new int[] { 0, 255, 0 } ,
new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() });
// third run properties
assertEquals(" String", runs.get(2).getText());
assertEquals("Arial", runs.get(2).getFontFamily());
clr = runs.get(2).getFontColor();
assertArrayEquals(
new int[] { 0, 255, 255 } ,
new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() });
checkRewrite(wb2);
wb2.close();
}
/**
* Test add multiple paragraphs and retrieve text
*/
@Test
void testAddMultipleParagraphs() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4));
XSSFTextParagraph para = shape.addNewTextParagraph();
para.addNewTextRun().setText("Line 1");
para = shape.addNewTextParagraph();
para.addNewTextRun().setText("Line 2");
para = shape.addNewTextParagraph();
para.addNewTextRun().setText("Line 3");
List<XSSFTextParagraph> paras = shape.getTextParagraphs();
assertEquals(4, paras.size()); // this should be 4 as XSSFSimpleShape creates a default paragraph (no text), and then we added 3 paragraphs
assertEquals("Line 1\nLine 2\nLine 3", shape.getText());
checkRewrite(wb);
wb.close();
}
/**
* Test setting the text, then adding multiple paragraphs and retrieve text
*/
@Test
void testSetAddMultipleParagraphs() throws IOException {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4));
shape.setText("Line 1");
XSSFTextParagraph para = shape.addNewTextParagraph();
para.addNewTextRun().setText("Line 2");
para = shape.addNewTextParagraph();
para.addNewTextRun().setText("Line 3");
List<XSSFTextParagraph> paras = shape.getTextParagraphs();
assertEquals(3, paras.size()); // this should be 3 as we overwrote the default paragraph with setText, then added 2 new paragraphs
assertEquals("Line 1\nLine 2\nLine 3", shape.getText());
checkRewrite(wb);
wb.close();
}
/**
* Test reading text from a textbox in an existing file
*/
@Test
void testReadTextBox() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx");
XSSFSheet sheet = wb.getSheetAt(0);
//the sheet has one relationship and it is XSSFDrawing
List<RelationPart> rels = sheet.getRelationParts();
assertEquals(1, rels.size());
RelationPart rp = rels.get(0);
assertTrue(rp.getDocumentPart() instanceof XSSFDrawing);
XSSFDrawing drawing = rp.getDocumentPart();
//sheet.createDrawingPatriarch() should return the same instance of XSSFDrawing
assertSame(drawing, sheet.createDrawingPatriarch());
String drawingId = rp.getRelationship().getId();
//there should be a relation to this drawing in the worksheet
assertTrue(sheet.getCTWorksheet().isSetDrawing());
assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId());
List<XSSFShape> shapes = drawing.getShapes();
assertEquals(6, shapes.size());
assertTrue(shapes.get(4) instanceof XSSFSimpleShape);
XSSFSimpleShape textbox = (XSSFSimpleShape) shapes.get(4);
assertEquals("Sheet with various pictures\n(jpeg, png, wmf, emf and pict)", textbox.getText());
checkRewrite(wb);
wb.close();
}
/**
* Test reading multiple paragraphs from a textbox in an existing file
*/
@Test
void testReadTextBoxParagraphs() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithTextBox.xlsx");
XSSFSheet sheet = wb.getSheetAt(0);
//the sheet has one relationship and it is XSSFDrawing
List<RelationPart> rels = sheet.getRelationParts();
assertEquals(1, rels.size());
RelationPart rp = rels.get(0);
assertTrue(rp.getDocumentPart() instanceof XSSFDrawing);
XSSFDrawing drawing = rp.getDocumentPart();
//sheet.createDrawingPatriarch() should return the same instance of XSSFDrawing
assertSame(drawing, sheet.createDrawingPatriarch());
String drawingId = rp.getRelationship().getId();
//there should be a relation to this drawing in the worksheet
assertTrue(sheet.getCTWorksheet().isSetDrawing());
assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId());
List<XSSFShape> shapes = drawing.getShapes();
assertEquals(1, shapes.size());
assertTrue(shapes.get(0) instanceof XSSFSimpleShape);
XSSFSimpleShape textbox = (XSSFSimpleShape) shapes.get(0);
List<XSSFTextParagraph> paras = textbox.getTextParagraphs();
assertEquals(3, paras.size());
assertEquals("Line 2", paras.get(1).getText()); // check content of second paragraph
assertEquals("Line 1\nLine 2\nLine 3", textbox.getText()); // check content of entire textbox
// check attributes of paragraphs
assertEquals(TextAlign.LEFT, paras.get(0).getTextAlign());
assertEquals(TextAlign.CENTER, paras.get(1).getTextAlign());
assertEquals(TextAlign.RIGHT, paras.get(2).getTextAlign());
Color clr = paras.get(0).getTextRuns().get(0).getFontColor();
assertArrayEquals(
new int[] { 255, 0, 0 } ,
new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() });
clr = paras.get(1).getTextRuns().get(0).getFontColor();
assertArrayEquals(
new int[] { 0, 255, 0 } ,
new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() });
clr = paras.get(2).getTextRuns().get(0).getFontColor();
assertArrayEquals(
new int[] { 0, 0, 255 } ,
new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() });
checkRewrite(wb);
wb.close();
}
/**
* Test adding and reading back paragraphs as bullet points
*/
@Test
void testAddBulletParagraphs() throws IOException {
XSSFWorkbook wb1 = new XSSFWorkbook();
XSSFSheet sheet = wb1.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 10, 20));
String paraString1 = "A normal paragraph";
String paraString2 = "First bullet";
String paraString3 = "Second bullet (level 1)";
String paraString4 = "Third bullet";
String paraString5 = "Another normal paragraph";
String paraString6 = "First numbered bullet";
String paraString7 = "Second bullet (level 1)";
String paraString8 = "Third bullet (level 1)";
String paraString9 = "Fourth bullet (level 1)";
String paraString10 = "Fifth Bullet";
XSSFTextParagraph para = shape.addNewTextParagraph(paraString1);
assertNotNull(para);
para = shape.addNewTextParagraph(paraString2);
para.setBullet(true);
para = shape.addNewTextParagraph(paraString3);
para.setBullet(true);
para.setLevel(1);
para = shape.addNewTextParagraph(paraString4);
para.setBullet(true);
para = shape.addNewTextParagraph(paraString5);
assertNotNull(para);
para = shape.addNewTextParagraph(paraString6);
para.setBullet(ListAutoNumber.ARABIC_PERIOD);
para = shape.addNewTextParagraph(paraString7);
para.setBullet(ListAutoNumber.ARABIC_PERIOD, 3);
para.setLevel(1);
para = shape.addNewTextParagraph(paraString8);
para.setBullet(ListAutoNumber.ARABIC_PERIOD, 3);
para.setLevel(1);
para = shape.addNewTextParagraph("");
para.setBullet(ListAutoNumber.ARABIC_PERIOD, 3);
para.setLevel(1);
para = shape.addNewTextParagraph(paraString9);
para.setBullet(ListAutoNumber.ARABIC_PERIOD, 3);
para.setLevel(1);
para = shape.addNewTextParagraph(paraString10);
para.setBullet(ListAutoNumber.ARABIC_PERIOD);
// Save and re-load it
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
wb1.close();
sheet = wb2.getSheetAt(0);
// Check
drawing = sheet.createDrawingPatriarch();
List<XSSFShape> shapes = drawing.getShapes();
assertEquals(1, shapes.size());
assertTrue(shapes.get(0) instanceof XSSFSimpleShape);
XSSFSimpleShape sshape = (XSSFSimpleShape) shapes.get(0);
List<XSSFTextParagraph> paras = sshape.getTextParagraphs();
assertEquals(12, paras.size()); // this should be 12 as XSSFSimpleShape creates a default paragraph (no text), and then we added to that
String builder =
paraString1 +
"\n" +
"\u2022 " +
paraString2 +
"\n" +
"\t\u2022 " +
paraString3 +
"\n" +
"\u2022 " +
paraString4 +
"\n" +
paraString5 +
"\n" +
"1. " +
paraString6 +
"\n" +
"\t3. " +
paraString7 +
"\n" +
"\t4. " +
paraString8 +
"\n" +
"\t" + // should be empty
"\n" +
"\t5. " +
paraString9 +
"\n" +
"2. " +
paraString10;
assertEquals(builder, sshape.getText());
checkRewrite(wb2);
wb2.close();
}
/**
* Test reading bullet numbering from a textbox in an existing file
*/
@Test
void testReadTextBox2() throws IOException {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithTextBox2.xlsx");
XSSFSheet sheet = wb.getSheetAt(0);
XSSFDrawing drawing = sheet.createDrawingPatriarch();
List<XSSFShape> shapes = drawing.getShapes();
XSSFSimpleShape textbox = (XSSFSimpleShape) shapes.get(0);
String extracted = textbox.getText();
String sb =
"1. content1A\n" +
"\t1. content1B\n" +
"\t2. content2B\n" +
"\t3. content3B\n" +
"2. content2A\n" +
"\t3. content2BStartAt3\n" +
"\t\n\t\n\t" +
"4. content2BStartAt3Incremented\n" +
"\t\n\t\n\t\n\t";
assertEquals(sb, extracted);
checkRewrite(wb);
wb.close();
}
@Test
void testXSSFSimpleShapeCausesNPE56514() throws IOException {
XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("56514.xlsx");
XSSFSheet sheet = wb1.getSheetAt(0);
XSSFDrawing drawing = sheet.createDrawingPatriarch();
List<XSSFShape> shapes = drawing.getShapes();
assertEquals(4, shapes.size());
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
wb1.close();
sheet = wb2.getSheetAt(0);
drawing = sheet.createDrawingPatriarch();
shapes = drawing.getShapes();
assertEquals(4, shapes.size());
wb2.close();
}
@Test
void testXSSFSAddPicture() throws Exception {
XSSFWorkbook wb1 = new XSSFWorkbook();
XSSFSheet sheet = wb1.createSheet();
//multiple calls of createDrawingPatriarch should return the same instance of XSSFDrawing
XSSFDrawing dr1 = sheet.createDrawingPatriarch();
XSSFDrawing dr2 = sheet.createDrawingPatriarch();
assertSame(dr1, dr2);
List<RelationPart> rels = sheet.getRelationParts();
assertEquals(1, rels.size());
RelationPart rp = rels.get(0);
assertTrue(rp.getDocumentPart() instanceof XSSFDrawing);
assertEquals(0, rp.getDocumentPart().getRelations().size());
XSSFDrawing drawing = rp.getDocumentPart();
String drawingId = rp.getRelationship().getId();
//there should be a relation to this drawing in the worksheet
assertTrue(sheet.getCTWorksheet().isSetDrawing());
assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId());
byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("45829.png");
ClientAnchor anchor = wb1.getCreationHelper().createClientAnchor();
anchor.setCol1(1);
anchor.setRow1(1);
drawing.createPicture(anchor, wb1.addPicture(pictureData, Workbook.PICTURE_TYPE_JPEG));
final int pictureIndex = wb1.addPicture(pictureData, Workbook.PICTURE_TYPE_JPEG);
drawing.createPicture(anchor, pictureIndex);
drawing.createPicture(anchor, pictureIndex);
// repeated additions of same share package relationship
assertEquals(2, rp.getDocumentPart().getPackagePart().getRelationships().size());
List<XSSFShape> shapes = drawing.getShapes();
assertEquals(3, shapes.size());
assertTrue(shapes.get(0) instanceof XSSFPicture);
assertTrue(shapes.get(1) instanceof XSSFPicture);
// Save and re-load it
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
wb1.close();
sheet = wb2.getSheetAt(0);
// Check
dr1 = sheet.createDrawingPatriarch();
CTDrawing ctDrawing = dr1.getCTDrawing();
// Connector, shapes and text boxes are all two cell anchors
assertEquals(0, ctDrawing.sizeOfAbsoluteAnchorArray());
assertEquals(0, ctDrawing.sizeOfOneCellAnchorArray());
assertEquals(3, ctDrawing.sizeOfTwoCellAnchorArray());
shapes = dr1.getShapes();
assertEquals(3, shapes.size());
assertTrue(shapes.get(0) instanceof XSSFPicture);
assertTrue(shapes.get(1) instanceof XSSFPicture);
checkRewrite(wb2);
wb2.close();
}
@Test
void testBug56835CellComment() throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
XSSFSheet sheet = wb.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
// first comment works
ClientAnchor anchor = new XSSFClientAnchor(1, 1, 2, 2, 3, 3, 4, 4);
XSSFComment comment = drawing.createCellComment(anchor);
assertNotNull(comment);
// Should fail if we try to add the same comment for the same cell
assertThrows(IllegalArgumentException.class, () -> drawing.createCellComment(anchor));
}
}
@Test
void testGroupShape() throws Exception {
XSSFWorkbook wb1 = new XSSFWorkbook();
XSSFSheet sheet = wb1.createSheet();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFSimpleShape s0 = drawing.createSimpleShape(drawing.createAnchor(0, 0, Units.pixelToEMU(30), Units.pixelToEMU(30), 1, 1, 10, 10));
s0.setShapeType(ShapeTypes.RECT);
s0.setLineStyleColor(100, 0, 0);
XSSFShapeGroup g1 = drawing.createGroup(drawing.createAnchor(0, 0, 300, 300, 1, 1, 10, 10));
CTGroupTransform2D xfrmG1 = g1.getCTGroupShape().getGrpSpPr().getXfrm();
XSSFSimpleShape s1 = g1.createSimpleShape(new XSSFChildAnchor(
(int)(xfrmG1.getChExt().getCx()*0.1),
(int)(xfrmG1.getChExt().getCy()*0.1),
(int)(xfrmG1.getChExt().getCx()*0.9),
(int)(xfrmG1.getChExt().getCy()*0.9)
));
s1.setShapeType(ShapeTypes.RECT);
s1.setLineStyleColor(0, 100, 0);
XSSFShapeGroup g2 = g1.createGroup(new XSSFChildAnchor(
(int)(xfrmG1.getChExt().getCx()*0.2),
(int)(xfrmG1.getChExt().getCy()*0.2),
(int)(xfrmG1.getChExt().getCx()*0.8),
(int)(xfrmG1.getChExt().getCy()*0.8)
));
CTGroupTransform2D xfrmG2 = g2.getCTGroupShape().getGrpSpPr().getXfrm();
XSSFSimpleShape s2 = g2.createSimpleShape(new XSSFChildAnchor(
(int)(xfrmG2.getChExt().getCx()*0.1),
(int)(xfrmG2.getChExt().getCy()*0.1),
(int)(xfrmG2.getChExt().getCx()*0.9),
(int)(xfrmG2.getChExt().getCy()*0.9)
));
s2.setShapeType(ShapeTypes.RECT);
s2.setLineStyleColor(0, 0, 100);
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1);
wb1.close();
XSSFDrawing draw = wb2.getSheetAt(0).getDrawingPatriarch();
List<XSSFShape> shapes = draw.getShapes();
assertEquals(2, shapes.size());
assertTrue(shapes.get(0) instanceof XSSFSimpleShape);
assertTrue(shapes.get(1) instanceof XSSFShapeGroup);
shapes = draw.getShapes((XSSFShapeGroup)shapes.get(1));
assertEquals(2, shapes.size());
assertTrue(shapes.get(0) instanceof XSSFSimpleShape);
assertTrue(shapes.get(1) instanceof XSSFShapeGroup);
shapes = draw.getShapes((XSSFShapeGroup)shapes.get(1));
assertEquals(1, shapes.size());
assertTrue(shapes.get(0) instanceof XSSFSimpleShape);
wb2.close();
}
@Test
void testBug63901() throws IOException {
try (XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("chartTitle_withTitle.xlsx")) {
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFDrawing drawing = sheet.getDrawingPatriarch();
assertEquals(1, drawing.getCharts().size());
XSSFWorkbook workbook2 = new XSSFWorkbook();
XSSFSheet sheet2 = workbook2.createSheet();
XSSFDrawing drawing2 = sheet2.createDrawingPatriarch();
drawing.getCharts().forEach(drawing2::importChart);
assertEquals(1, drawing2.getCharts().size());
}
}
private static void checkRewrite(XSSFWorkbook wb) throws IOException {
XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb);
assertNotNull(wb2);
wb2.close();
}
}
|
googleads/google-ads-java | 36,609 | google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/services/ListInsightsEligibleDatesResponse.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v19/services/audience_insights_service.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v19.services;
/**
* <pre>
* Response message for
* [AudienceInsightsService.ListInsightsEligibleDates][google.ads.googleads.v19.services.AudienceInsightsService.ListInsightsEligibleDates].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse}
*/
public final class ListInsightsEligibleDatesResponse extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse)
ListInsightsEligibleDatesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListInsightsEligibleDatesResponse.newBuilder() to construct.
private ListInsightsEligibleDatesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListInsightsEligibleDatesResponse() {
dataMonths_ =
com.google.protobuf.LazyStringArrayList.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new ListInsightsEligibleDatesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v19_services_ListInsightsEligibleDatesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v19_services_ListInsightsEligibleDatesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse.class, com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse.Builder.class);
}
private int bitField0_;
public static final int DATA_MONTHS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private com.google.protobuf.LazyStringArrayList dataMonths_ =
com.google.protobuf.LazyStringArrayList.emptyList();
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @return A list containing the dataMonths.
*/
public com.google.protobuf.ProtocolStringList
getDataMonthsList() {
return dataMonths_;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @return The count of dataMonths.
*/
public int getDataMonthsCount() {
return dataMonths_.size();
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param index The index of the element to return.
* @return The dataMonths at the given index.
*/
public java.lang.String getDataMonths(int index) {
return dataMonths_.get(index);
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param index The index of the value to return.
* @return The bytes of the dataMonths at the given index.
*/
public com.google.protobuf.ByteString
getDataMonthsBytes(int index) {
return dataMonths_.getByteString(index);
}
public static final int LAST_THIRTY_DAYS_FIELD_NUMBER = 2;
private com.google.ads.googleads.v19.common.DateRange lastThirtyDays_;
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v19.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v19.common.DateRange last_thirty_days = 2;</code>
* @return Whether the lastThirtyDays field is set.
*/
@java.lang.Override
public boolean hasLastThirtyDays() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v19.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v19.common.DateRange last_thirty_days = 2;</code>
* @return The lastThirtyDays.
*/
@java.lang.Override
public com.google.ads.googleads.v19.common.DateRange getLastThirtyDays() {
return lastThirtyDays_ == null ? com.google.ads.googleads.v19.common.DateRange.getDefaultInstance() : lastThirtyDays_;
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v19.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v19.common.DateRange last_thirty_days = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v19.common.DateRangeOrBuilder getLastThirtyDaysOrBuilder() {
return lastThirtyDays_ == null ? com.google.ads.googleads.v19.common.DateRange.getDefaultInstance() : lastThirtyDays_;
}
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 < dataMonths_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, dataMonths_.getRaw(i));
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getLastThirtyDays());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
{
int dataSize = 0;
for (int i = 0; i < dataMonths_.size(); i++) {
dataSize += computeStringSizeNoTag(dataMonths_.getRaw(i));
}
size += dataSize;
size += 1 * getDataMonthsList().size();
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, getLastThirtyDays());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse)) {
return super.equals(obj);
}
com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse other = (com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse) obj;
if (!getDataMonthsList()
.equals(other.getDataMonthsList())) return false;
if (hasLastThirtyDays() != other.hasLastThirtyDays()) return false;
if (hasLastThirtyDays()) {
if (!getLastThirtyDays()
.equals(other.getLastThirtyDays())) 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 (getDataMonthsCount() > 0) {
hash = (37 * hash) + DATA_MONTHS_FIELD_NUMBER;
hash = (53 * hash) + getDataMonthsList().hashCode();
}
if (hasLastThirtyDays()) {
hash = (37 * hash) + LAST_THIRTY_DAYS_FIELD_NUMBER;
hash = (53 * hash) + getLastThirtyDays().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Response message for
* [AudienceInsightsService.ListInsightsEligibleDates][google.ads.googleads.v19.services.AudienceInsightsService.ListInsightsEligibleDates].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse)
com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v19_services_ListInsightsEligibleDatesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v19_services_ListInsightsEligibleDatesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse.class, com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse.Builder.class);
}
// Construct using com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getLastThirtyDaysFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
dataMonths_ =
com.google.protobuf.LazyStringArrayList.emptyList();
lastThirtyDays_ = null;
if (lastThirtyDaysBuilder_ != null) {
lastThirtyDaysBuilder_.dispose();
lastThirtyDaysBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v19.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v19_services_ListInsightsEligibleDatesResponse_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse getDefaultInstanceForType() {
return com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse build() {
com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse buildPartial() {
com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse result = new com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
dataMonths_.makeImmutable();
result.dataMonths_ = dataMonths_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.lastThirtyDays_ = lastThirtyDaysBuilder_ == null
? lastThirtyDays_
: lastThirtyDaysBuilder_.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.ads.googleads.v19.services.ListInsightsEligibleDatesResponse) {
return mergeFrom((com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse other) {
if (other == com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse.getDefaultInstance()) return this;
if (!other.dataMonths_.isEmpty()) {
if (dataMonths_.isEmpty()) {
dataMonths_ = other.dataMonths_;
bitField0_ |= 0x00000001;
} else {
ensureDataMonthsIsMutable();
dataMonths_.addAll(other.dataMonths_);
}
onChanged();
}
if (other.hasLastThirtyDays()) {
mergeLastThirtyDays(other.getLastThirtyDays());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
java.lang.String s = input.readStringRequireUtf8();
ensureDataMonthsIsMutable();
dataMonths_.add(s);
break;
} // case 10
case 18: {
input.readMessage(
getLastThirtyDaysFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.protobuf.LazyStringArrayList dataMonths_ =
com.google.protobuf.LazyStringArrayList.emptyList();
private void ensureDataMonthsIsMutable() {
if (!dataMonths_.isModifiable()) {
dataMonths_ = new com.google.protobuf.LazyStringArrayList(dataMonths_);
}
bitField0_ |= 0x00000001;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @return A list containing the dataMonths.
*/
public com.google.protobuf.ProtocolStringList
getDataMonthsList() {
dataMonths_.makeImmutable();
return dataMonths_;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @return The count of dataMonths.
*/
public int getDataMonthsCount() {
return dataMonths_.size();
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param index The index of the element to return.
* @return The dataMonths at the given index.
*/
public java.lang.String getDataMonths(int index) {
return dataMonths_.get(index);
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param index The index of the value to return.
* @return The bytes of the dataMonths at the given index.
*/
public com.google.protobuf.ByteString
getDataMonthsBytes(int index) {
return dataMonths_.getByteString(index);
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param index The index to set the value at.
* @param value The dataMonths to set.
* @return This builder for chaining.
*/
public Builder setDataMonths(
int index, java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
ensureDataMonthsIsMutable();
dataMonths_.set(index, value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param value The dataMonths to add.
* @return This builder for chaining.
*/
public Builder addDataMonths(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
ensureDataMonthsIsMutable();
dataMonths_.add(value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param values The dataMonths to add.
* @return This builder for chaining.
*/
public Builder addAllDataMonths(
java.lang.Iterable<java.lang.String> values) {
ensureDataMonthsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, dataMonths_);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @return This builder for chaining.
*/
public Builder clearDataMonths() {
dataMonths_ =
com.google.protobuf.LazyStringArrayList.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);;
onChanged();
return this;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param value The bytes of the dataMonths to add.
* @return This builder for chaining.
*/
public Builder addDataMonthsBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
ensureDataMonthsIsMutable();
dataMonths_.add(value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.ads.googleads.v19.common.DateRange lastThirtyDays_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.common.DateRange, com.google.ads.googleads.v19.common.DateRange.Builder, com.google.ads.googleads.v19.common.DateRangeOrBuilder> lastThirtyDaysBuilder_;
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v19.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v19.common.DateRange last_thirty_days = 2;</code>
* @return Whether the lastThirtyDays field is set.
*/
public boolean hasLastThirtyDays() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v19.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v19.common.DateRange last_thirty_days = 2;</code>
* @return The lastThirtyDays.
*/
public com.google.ads.googleads.v19.common.DateRange getLastThirtyDays() {
if (lastThirtyDaysBuilder_ == null) {
return lastThirtyDays_ == null ? com.google.ads.googleads.v19.common.DateRange.getDefaultInstance() : lastThirtyDays_;
} else {
return lastThirtyDaysBuilder_.getMessage();
}
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v19.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v19.common.DateRange last_thirty_days = 2;</code>
*/
public Builder setLastThirtyDays(com.google.ads.googleads.v19.common.DateRange value) {
if (lastThirtyDaysBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
lastThirtyDays_ = value;
} else {
lastThirtyDaysBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v19.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v19.common.DateRange last_thirty_days = 2;</code>
*/
public Builder setLastThirtyDays(
com.google.ads.googleads.v19.common.DateRange.Builder builderForValue) {
if (lastThirtyDaysBuilder_ == null) {
lastThirtyDays_ = builderForValue.build();
} else {
lastThirtyDaysBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v19.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v19.common.DateRange last_thirty_days = 2;</code>
*/
public Builder mergeLastThirtyDays(com.google.ads.googleads.v19.common.DateRange value) {
if (lastThirtyDaysBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0) &&
lastThirtyDays_ != null &&
lastThirtyDays_ != com.google.ads.googleads.v19.common.DateRange.getDefaultInstance()) {
getLastThirtyDaysBuilder().mergeFrom(value);
} else {
lastThirtyDays_ = value;
}
} else {
lastThirtyDaysBuilder_.mergeFrom(value);
}
if (lastThirtyDays_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v19.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v19.common.DateRange last_thirty_days = 2;</code>
*/
public Builder clearLastThirtyDays() {
bitField0_ = (bitField0_ & ~0x00000002);
lastThirtyDays_ = null;
if (lastThirtyDaysBuilder_ != null) {
lastThirtyDaysBuilder_.dispose();
lastThirtyDaysBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v19.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v19.common.DateRange last_thirty_days = 2;</code>
*/
public com.google.ads.googleads.v19.common.DateRange.Builder getLastThirtyDaysBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getLastThirtyDaysFieldBuilder().getBuilder();
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v19.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v19.common.DateRange last_thirty_days = 2;</code>
*/
public com.google.ads.googleads.v19.common.DateRangeOrBuilder getLastThirtyDaysOrBuilder() {
if (lastThirtyDaysBuilder_ != null) {
return lastThirtyDaysBuilder_.getMessageOrBuilder();
} else {
return lastThirtyDays_ == null ?
com.google.ads.googleads.v19.common.DateRange.getDefaultInstance() : lastThirtyDays_;
}
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v19.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v19.common.DateRange last_thirty_days = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.common.DateRange, com.google.ads.googleads.v19.common.DateRange.Builder, com.google.ads.googleads.v19.common.DateRangeOrBuilder>
getLastThirtyDaysFieldBuilder() {
if (lastThirtyDaysBuilder_ == null) {
lastThirtyDaysBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.common.DateRange, com.google.ads.googleads.v19.common.DateRange.Builder, com.google.ads.googleads.v19.common.DateRangeOrBuilder>(
getLastThirtyDays(),
getParentForChildren(),
isClean());
lastThirtyDays_ = null;
}
return lastThirtyDaysBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse)
private static final com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse();
}
public static com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListInsightsEligibleDatesResponse>
PARSER = new com.google.protobuf.AbstractParser<ListInsightsEligibleDatesResponse>() {
@java.lang.Override
public ListInsightsEligibleDatesResponse 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<ListInsightsEligibleDatesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListInsightsEligibleDatesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v19.services.ListInsightsEligibleDatesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 36,609 | google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/services/ListInsightsEligibleDatesResponse.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v20/services/audience_insights_service.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v20.services;
/**
* <pre>
* Response message for
* [AudienceInsightsService.ListInsightsEligibleDates][google.ads.googleads.v20.services.AudienceInsightsService.ListInsightsEligibleDates].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse}
*/
public final class ListInsightsEligibleDatesResponse extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse)
ListInsightsEligibleDatesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListInsightsEligibleDatesResponse.newBuilder() to construct.
private ListInsightsEligibleDatesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListInsightsEligibleDatesResponse() {
dataMonths_ =
com.google.protobuf.LazyStringArrayList.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new ListInsightsEligibleDatesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v20_services_ListInsightsEligibleDatesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v20_services_ListInsightsEligibleDatesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse.class, com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse.Builder.class);
}
private int bitField0_;
public static final int DATA_MONTHS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private com.google.protobuf.LazyStringArrayList dataMonths_ =
com.google.protobuf.LazyStringArrayList.emptyList();
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @return A list containing the dataMonths.
*/
public com.google.protobuf.ProtocolStringList
getDataMonthsList() {
return dataMonths_;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @return The count of dataMonths.
*/
public int getDataMonthsCount() {
return dataMonths_.size();
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param index The index of the element to return.
* @return The dataMonths at the given index.
*/
public java.lang.String getDataMonths(int index) {
return dataMonths_.get(index);
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param index The index of the value to return.
* @return The bytes of the dataMonths at the given index.
*/
public com.google.protobuf.ByteString
getDataMonthsBytes(int index) {
return dataMonths_.getByteString(index);
}
public static final int LAST_THIRTY_DAYS_FIELD_NUMBER = 2;
private com.google.ads.googleads.v20.common.DateRange lastThirtyDays_;
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v20.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v20.common.DateRange last_thirty_days = 2;</code>
* @return Whether the lastThirtyDays field is set.
*/
@java.lang.Override
public boolean hasLastThirtyDays() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v20.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v20.common.DateRange last_thirty_days = 2;</code>
* @return The lastThirtyDays.
*/
@java.lang.Override
public com.google.ads.googleads.v20.common.DateRange getLastThirtyDays() {
return lastThirtyDays_ == null ? com.google.ads.googleads.v20.common.DateRange.getDefaultInstance() : lastThirtyDays_;
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v20.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v20.common.DateRange last_thirty_days = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v20.common.DateRangeOrBuilder getLastThirtyDaysOrBuilder() {
return lastThirtyDays_ == null ? com.google.ads.googleads.v20.common.DateRange.getDefaultInstance() : lastThirtyDays_;
}
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 < dataMonths_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, dataMonths_.getRaw(i));
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getLastThirtyDays());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
{
int dataSize = 0;
for (int i = 0; i < dataMonths_.size(); i++) {
dataSize += computeStringSizeNoTag(dataMonths_.getRaw(i));
}
size += dataSize;
size += 1 * getDataMonthsList().size();
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, getLastThirtyDays());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse)) {
return super.equals(obj);
}
com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse other = (com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse) obj;
if (!getDataMonthsList()
.equals(other.getDataMonthsList())) return false;
if (hasLastThirtyDays() != other.hasLastThirtyDays()) return false;
if (hasLastThirtyDays()) {
if (!getLastThirtyDays()
.equals(other.getLastThirtyDays())) 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 (getDataMonthsCount() > 0) {
hash = (37 * hash) + DATA_MONTHS_FIELD_NUMBER;
hash = (53 * hash) + getDataMonthsList().hashCode();
}
if (hasLastThirtyDays()) {
hash = (37 * hash) + LAST_THIRTY_DAYS_FIELD_NUMBER;
hash = (53 * hash) + getLastThirtyDays().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Response message for
* [AudienceInsightsService.ListInsightsEligibleDates][google.ads.googleads.v20.services.AudienceInsightsService.ListInsightsEligibleDates].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse)
com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v20_services_ListInsightsEligibleDatesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v20_services_ListInsightsEligibleDatesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse.class, com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse.Builder.class);
}
// Construct using com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getLastThirtyDaysFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
dataMonths_ =
com.google.protobuf.LazyStringArrayList.emptyList();
lastThirtyDays_ = null;
if (lastThirtyDaysBuilder_ != null) {
lastThirtyDaysBuilder_.dispose();
lastThirtyDaysBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v20.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v20_services_ListInsightsEligibleDatesResponse_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse getDefaultInstanceForType() {
return com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse build() {
com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse buildPartial() {
com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse result = new com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
dataMonths_.makeImmutable();
result.dataMonths_ = dataMonths_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.lastThirtyDays_ = lastThirtyDaysBuilder_ == null
? lastThirtyDays_
: lastThirtyDaysBuilder_.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.ads.googleads.v20.services.ListInsightsEligibleDatesResponse) {
return mergeFrom((com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse other) {
if (other == com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse.getDefaultInstance()) return this;
if (!other.dataMonths_.isEmpty()) {
if (dataMonths_.isEmpty()) {
dataMonths_ = other.dataMonths_;
bitField0_ |= 0x00000001;
} else {
ensureDataMonthsIsMutable();
dataMonths_.addAll(other.dataMonths_);
}
onChanged();
}
if (other.hasLastThirtyDays()) {
mergeLastThirtyDays(other.getLastThirtyDays());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
java.lang.String s = input.readStringRequireUtf8();
ensureDataMonthsIsMutable();
dataMonths_.add(s);
break;
} // case 10
case 18: {
input.readMessage(
getLastThirtyDaysFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.protobuf.LazyStringArrayList dataMonths_ =
com.google.protobuf.LazyStringArrayList.emptyList();
private void ensureDataMonthsIsMutable() {
if (!dataMonths_.isModifiable()) {
dataMonths_ = new com.google.protobuf.LazyStringArrayList(dataMonths_);
}
bitField0_ |= 0x00000001;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @return A list containing the dataMonths.
*/
public com.google.protobuf.ProtocolStringList
getDataMonthsList() {
dataMonths_.makeImmutable();
return dataMonths_;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @return The count of dataMonths.
*/
public int getDataMonthsCount() {
return dataMonths_.size();
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param index The index of the element to return.
* @return The dataMonths at the given index.
*/
public java.lang.String getDataMonths(int index) {
return dataMonths_.get(index);
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param index The index of the value to return.
* @return The bytes of the dataMonths at the given index.
*/
public com.google.protobuf.ByteString
getDataMonthsBytes(int index) {
return dataMonths_.getByteString(index);
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param index The index to set the value at.
* @param value The dataMonths to set.
* @return This builder for chaining.
*/
public Builder setDataMonths(
int index, java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
ensureDataMonthsIsMutable();
dataMonths_.set(index, value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param value The dataMonths to add.
* @return This builder for chaining.
*/
public Builder addDataMonths(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
ensureDataMonthsIsMutable();
dataMonths_.add(value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param values The dataMonths to add.
* @return This builder for chaining.
*/
public Builder addAllDataMonths(
java.lang.Iterable<java.lang.String> values) {
ensureDataMonthsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, dataMonths_);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @return This builder for chaining.
*/
public Builder clearDataMonths() {
dataMonths_ =
com.google.protobuf.LazyStringArrayList.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);;
onChanged();
return this;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param value The bytes of the dataMonths to add.
* @return This builder for chaining.
*/
public Builder addDataMonthsBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
ensureDataMonthsIsMutable();
dataMonths_.add(value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.ads.googleads.v20.common.DateRange lastThirtyDays_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.common.DateRange, com.google.ads.googleads.v20.common.DateRange.Builder, com.google.ads.googleads.v20.common.DateRangeOrBuilder> lastThirtyDaysBuilder_;
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v20.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v20.common.DateRange last_thirty_days = 2;</code>
* @return Whether the lastThirtyDays field is set.
*/
public boolean hasLastThirtyDays() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v20.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v20.common.DateRange last_thirty_days = 2;</code>
* @return The lastThirtyDays.
*/
public com.google.ads.googleads.v20.common.DateRange getLastThirtyDays() {
if (lastThirtyDaysBuilder_ == null) {
return lastThirtyDays_ == null ? com.google.ads.googleads.v20.common.DateRange.getDefaultInstance() : lastThirtyDays_;
} else {
return lastThirtyDaysBuilder_.getMessage();
}
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v20.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v20.common.DateRange last_thirty_days = 2;</code>
*/
public Builder setLastThirtyDays(com.google.ads.googleads.v20.common.DateRange value) {
if (lastThirtyDaysBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
lastThirtyDays_ = value;
} else {
lastThirtyDaysBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v20.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v20.common.DateRange last_thirty_days = 2;</code>
*/
public Builder setLastThirtyDays(
com.google.ads.googleads.v20.common.DateRange.Builder builderForValue) {
if (lastThirtyDaysBuilder_ == null) {
lastThirtyDays_ = builderForValue.build();
} else {
lastThirtyDaysBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v20.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v20.common.DateRange last_thirty_days = 2;</code>
*/
public Builder mergeLastThirtyDays(com.google.ads.googleads.v20.common.DateRange value) {
if (lastThirtyDaysBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0) &&
lastThirtyDays_ != null &&
lastThirtyDays_ != com.google.ads.googleads.v20.common.DateRange.getDefaultInstance()) {
getLastThirtyDaysBuilder().mergeFrom(value);
} else {
lastThirtyDays_ = value;
}
} else {
lastThirtyDaysBuilder_.mergeFrom(value);
}
if (lastThirtyDays_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v20.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v20.common.DateRange last_thirty_days = 2;</code>
*/
public Builder clearLastThirtyDays() {
bitField0_ = (bitField0_ & ~0x00000002);
lastThirtyDays_ = null;
if (lastThirtyDaysBuilder_ != null) {
lastThirtyDaysBuilder_.dispose();
lastThirtyDaysBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v20.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v20.common.DateRange last_thirty_days = 2;</code>
*/
public com.google.ads.googleads.v20.common.DateRange.Builder getLastThirtyDaysBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getLastThirtyDaysFieldBuilder().getBuilder();
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v20.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v20.common.DateRange last_thirty_days = 2;</code>
*/
public com.google.ads.googleads.v20.common.DateRangeOrBuilder getLastThirtyDaysOrBuilder() {
if (lastThirtyDaysBuilder_ != null) {
return lastThirtyDaysBuilder_.getMessageOrBuilder();
} else {
return lastThirtyDays_ == null ?
com.google.ads.googleads.v20.common.DateRange.getDefaultInstance() : lastThirtyDays_;
}
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v20.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v20.common.DateRange last_thirty_days = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.common.DateRange, com.google.ads.googleads.v20.common.DateRange.Builder, com.google.ads.googleads.v20.common.DateRangeOrBuilder>
getLastThirtyDaysFieldBuilder() {
if (lastThirtyDaysBuilder_ == null) {
lastThirtyDaysBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.common.DateRange, com.google.ads.googleads.v20.common.DateRange.Builder, com.google.ads.googleads.v20.common.DateRangeOrBuilder>(
getLastThirtyDays(),
getParentForChildren(),
isClean());
lastThirtyDays_ = null;
}
return lastThirtyDaysBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse)
private static final com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse();
}
public static com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListInsightsEligibleDatesResponse>
PARSER = new com.google.protobuf.AbstractParser<ListInsightsEligibleDatesResponse>() {
@java.lang.Override
public ListInsightsEligibleDatesResponse 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<ListInsightsEligibleDatesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListInsightsEligibleDatesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v20.services.ListInsightsEligibleDatesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 36,609 | google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/services/ListInsightsEligibleDatesResponse.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v21/services/audience_insights_service.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v21.services;
/**
* <pre>
* Response message for
* [AudienceInsightsService.ListInsightsEligibleDates][google.ads.googleads.v21.services.AudienceInsightsService.ListInsightsEligibleDates].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse}
*/
public final class ListInsightsEligibleDatesResponse extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse)
ListInsightsEligibleDatesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListInsightsEligibleDatesResponse.newBuilder() to construct.
private ListInsightsEligibleDatesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListInsightsEligibleDatesResponse() {
dataMonths_ =
com.google.protobuf.LazyStringArrayList.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new ListInsightsEligibleDatesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v21_services_ListInsightsEligibleDatesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v21_services_ListInsightsEligibleDatesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse.class, com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse.Builder.class);
}
private int bitField0_;
public static final int DATA_MONTHS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private com.google.protobuf.LazyStringArrayList dataMonths_ =
com.google.protobuf.LazyStringArrayList.emptyList();
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @return A list containing the dataMonths.
*/
public com.google.protobuf.ProtocolStringList
getDataMonthsList() {
return dataMonths_;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @return The count of dataMonths.
*/
public int getDataMonthsCount() {
return dataMonths_.size();
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param index The index of the element to return.
* @return The dataMonths at the given index.
*/
public java.lang.String getDataMonths(int index) {
return dataMonths_.get(index);
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param index The index of the value to return.
* @return The bytes of the dataMonths at the given index.
*/
public com.google.protobuf.ByteString
getDataMonthsBytes(int index) {
return dataMonths_.getByteString(index);
}
public static final int LAST_THIRTY_DAYS_FIELD_NUMBER = 2;
private com.google.ads.googleads.v21.common.DateRange lastThirtyDays_;
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v21.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v21.common.DateRange last_thirty_days = 2;</code>
* @return Whether the lastThirtyDays field is set.
*/
@java.lang.Override
public boolean hasLastThirtyDays() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v21.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v21.common.DateRange last_thirty_days = 2;</code>
* @return The lastThirtyDays.
*/
@java.lang.Override
public com.google.ads.googleads.v21.common.DateRange getLastThirtyDays() {
return lastThirtyDays_ == null ? com.google.ads.googleads.v21.common.DateRange.getDefaultInstance() : lastThirtyDays_;
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v21.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v21.common.DateRange last_thirty_days = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v21.common.DateRangeOrBuilder getLastThirtyDaysOrBuilder() {
return lastThirtyDays_ == null ? com.google.ads.googleads.v21.common.DateRange.getDefaultInstance() : lastThirtyDays_;
}
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 < dataMonths_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, dataMonths_.getRaw(i));
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getLastThirtyDays());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
{
int dataSize = 0;
for (int i = 0; i < dataMonths_.size(); i++) {
dataSize += computeStringSizeNoTag(dataMonths_.getRaw(i));
}
size += dataSize;
size += 1 * getDataMonthsList().size();
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, getLastThirtyDays());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse)) {
return super.equals(obj);
}
com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse other = (com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse) obj;
if (!getDataMonthsList()
.equals(other.getDataMonthsList())) return false;
if (hasLastThirtyDays() != other.hasLastThirtyDays()) return false;
if (hasLastThirtyDays()) {
if (!getLastThirtyDays()
.equals(other.getLastThirtyDays())) 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 (getDataMonthsCount() > 0) {
hash = (37 * hash) + DATA_MONTHS_FIELD_NUMBER;
hash = (53 * hash) + getDataMonthsList().hashCode();
}
if (hasLastThirtyDays()) {
hash = (37 * hash) + LAST_THIRTY_DAYS_FIELD_NUMBER;
hash = (53 * hash) + getLastThirtyDays().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Response message for
* [AudienceInsightsService.ListInsightsEligibleDates][google.ads.googleads.v21.services.AudienceInsightsService.ListInsightsEligibleDates].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse)
com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v21_services_ListInsightsEligibleDatesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v21_services_ListInsightsEligibleDatesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse.class, com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse.Builder.class);
}
// Construct using com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getLastThirtyDaysFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
dataMonths_ =
com.google.protobuf.LazyStringArrayList.emptyList();
lastThirtyDays_ = null;
if (lastThirtyDaysBuilder_ != null) {
lastThirtyDaysBuilder_.dispose();
lastThirtyDaysBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v21.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v21_services_ListInsightsEligibleDatesResponse_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse getDefaultInstanceForType() {
return com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse build() {
com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse buildPartial() {
com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse result = new com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
dataMonths_.makeImmutable();
result.dataMonths_ = dataMonths_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.lastThirtyDays_ = lastThirtyDaysBuilder_ == null
? lastThirtyDays_
: lastThirtyDaysBuilder_.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.ads.googleads.v21.services.ListInsightsEligibleDatesResponse) {
return mergeFrom((com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse other) {
if (other == com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse.getDefaultInstance()) return this;
if (!other.dataMonths_.isEmpty()) {
if (dataMonths_.isEmpty()) {
dataMonths_ = other.dataMonths_;
bitField0_ |= 0x00000001;
} else {
ensureDataMonthsIsMutable();
dataMonths_.addAll(other.dataMonths_);
}
onChanged();
}
if (other.hasLastThirtyDays()) {
mergeLastThirtyDays(other.getLastThirtyDays());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
java.lang.String s = input.readStringRequireUtf8();
ensureDataMonthsIsMutable();
dataMonths_.add(s);
break;
} // case 10
case 18: {
input.readMessage(
getLastThirtyDaysFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.protobuf.LazyStringArrayList dataMonths_ =
com.google.protobuf.LazyStringArrayList.emptyList();
private void ensureDataMonthsIsMutable() {
if (!dataMonths_.isModifiable()) {
dataMonths_ = new com.google.protobuf.LazyStringArrayList(dataMonths_);
}
bitField0_ |= 0x00000001;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @return A list containing the dataMonths.
*/
public com.google.protobuf.ProtocolStringList
getDataMonthsList() {
dataMonths_.makeImmutable();
return dataMonths_;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @return The count of dataMonths.
*/
public int getDataMonthsCount() {
return dataMonths_.size();
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param index The index of the element to return.
* @return The dataMonths at the given index.
*/
public java.lang.String getDataMonths(int index) {
return dataMonths_.get(index);
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param index The index of the value to return.
* @return The bytes of the dataMonths at the given index.
*/
public com.google.protobuf.ByteString
getDataMonthsBytes(int index) {
return dataMonths_.getByteString(index);
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param index The index to set the value at.
* @param value The dataMonths to set.
* @return This builder for chaining.
*/
public Builder setDataMonths(
int index, java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
ensureDataMonthsIsMutable();
dataMonths_.set(index, value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param value The dataMonths to add.
* @return This builder for chaining.
*/
public Builder addDataMonths(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
ensureDataMonthsIsMutable();
dataMonths_.add(value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param values The dataMonths to add.
* @return This builder for chaining.
*/
public Builder addAllDataMonths(
java.lang.Iterable<java.lang.String> values) {
ensureDataMonthsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, dataMonths_);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @return This builder for chaining.
*/
public Builder clearDataMonths() {
dataMonths_ =
com.google.protobuf.LazyStringArrayList.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);;
onChanged();
return this;
}
/**
* <pre>
* The months for which AudienceInsights data is currently
* available, each represented as a string in the form "YYYY-MM".
* </pre>
*
* <code>repeated string data_months = 1;</code>
* @param value The bytes of the dataMonths to add.
* @return This builder for chaining.
*/
public Builder addDataMonthsBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
ensureDataMonthsIsMutable();
dataMonths_.add(value);
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.ads.googleads.v21.common.DateRange lastThirtyDays_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.common.DateRange, com.google.ads.googleads.v21.common.DateRange.Builder, com.google.ads.googleads.v21.common.DateRangeOrBuilder> lastThirtyDaysBuilder_;
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v21.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v21.common.DateRange last_thirty_days = 2;</code>
* @return Whether the lastThirtyDays field is set.
*/
public boolean hasLastThirtyDays() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v21.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v21.common.DateRange last_thirty_days = 2;</code>
* @return The lastThirtyDays.
*/
public com.google.ads.googleads.v21.common.DateRange getLastThirtyDays() {
if (lastThirtyDaysBuilder_ == null) {
return lastThirtyDays_ == null ? com.google.ads.googleads.v21.common.DateRange.getDefaultInstance() : lastThirtyDays_;
} else {
return lastThirtyDaysBuilder_.getMessage();
}
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v21.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v21.common.DateRange last_thirty_days = 2;</code>
*/
public Builder setLastThirtyDays(com.google.ads.googleads.v21.common.DateRange value) {
if (lastThirtyDaysBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
lastThirtyDays_ = value;
} else {
lastThirtyDaysBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v21.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v21.common.DateRange last_thirty_days = 2;</code>
*/
public Builder setLastThirtyDays(
com.google.ads.googleads.v21.common.DateRange.Builder builderForValue) {
if (lastThirtyDaysBuilder_ == null) {
lastThirtyDays_ = builderForValue.build();
} else {
lastThirtyDaysBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v21.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v21.common.DateRange last_thirty_days = 2;</code>
*/
public Builder mergeLastThirtyDays(com.google.ads.googleads.v21.common.DateRange value) {
if (lastThirtyDaysBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0) &&
lastThirtyDays_ != null &&
lastThirtyDays_ != com.google.ads.googleads.v21.common.DateRange.getDefaultInstance()) {
getLastThirtyDaysBuilder().mergeFrom(value);
} else {
lastThirtyDays_ = value;
}
} else {
lastThirtyDaysBuilder_.mergeFrom(value);
}
if (lastThirtyDays_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v21.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v21.common.DateRange last_thirty_days = 2;</code>
*/
public Builder clearLastThirtyDays() {
bitField0_ = (bitField0_ & ~0x00000002);
lastThirtyDays_ = null;
if (lastThirtyDaysBuilder_ != null) {
lastThirtyDaysBuilder_.dispose();
lastThirtyDaysBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v21.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v21.common.DateRange last_thirty_days = 2;</code>
*/
public com.google.ads.googleads.v21.common.DateRange.Builder getLastThirtyDaysBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getLastThirtyDaysFieldBuilder().getBuilder();
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v21.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v21.common.DateRange last_thirty_days = 2;</code>
*/
public com.google.ads.googleads.v21.common.DateRangeOrBuilder getLastThirtyDaysOrBuilder() {
if (lastThirtyDaysBuilder_ != null) {
return lastThirtyDaysBuilder_.getMessageOrBuilder();
} else {
return lastThirtyDays_ == null ?
com.google.ads.googleads.v21.common.DateRange.getDefaultInstance() : lastThirtyDays_;
}
}
/**
* <pre>
* The actual dates covered by the "last 30 days" date range that will be used
* implicitly for
* [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v21.services.AudienceInsightsService.GenerateAudienceCompositionInsights]
* requests that have no data_month set.
* </pre>
*
* <code>.google.ads.googleads.v21.common.DateRange last_thirty_days = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.common.DateRange, com.google.ads.googleads.v21.common.DateRange.Builder, com.google.ads.googleads.v21.common.DateRangeOrBuilder>
getLastThirtyDaysFieldBuilder() {
if (lastThirtyDaysBuilder_ == null) {
lastThirtyDaysBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.common.DateRange, com.google.ads.googleads.v21.common.DateRange.Builder, com.google.ads.googleads.v21.common.DateRangeOrBuilder>(
getLastThirtyDays(),
getParentForChildren(),
isClean());
lastThirtyDays_ = null;
}
return lastThirtyDaysBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse)
private static final com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse();
}
public static com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListInsightsEligibleDatesResponse>
PARSER = new com.google.protobuf.AbstractParser<ListInsightsEligibleDatesResponse>() {
@java.lang.Override
public ListInsightsEligibleDatesResponse 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<ListInsightsEligibleDatesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListInsightsEligibleDatesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v21.services.ListInsightsEligibleDatesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,392 | java-shopping-merchant-reports/proto-google-shopping-merchant-reports-v1/src/main/java/com/google/shopping/merchant/reports/v1/SearchResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/shopping/merchant/reports/v1/reports.proto
// Protobuf Java Version: 3.25.8
package com.google.shopping.merchant.reports.v1;
/**
*
*
* <pre>
* Response message for the `ReportService.Search` method.
* </pre>
*
* Protobuf type {@code google.shopping.merchant.reports.v1.SearchResponse}
*/
public final class SearchResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.shopping.merchant.reports.v1.SearchResponse)
SearchResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use SearchResponse.newBuilder() to construct.
private SearchResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SearchResponse() {
results_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new SearchResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.shopping.merchant.reports.v1.ReportsProto
.internal_static_google_shopping_merchant_reports_v1_SearchResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.shopping.merchant.reports.v1.ReportsProto
.internal_static_google_shopping_merchant_reports_v1_SearchResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.shopping.merchant.reports.v1.SearchResponse.class,
com.google.shopping.merchant.reports.v1.SearchResponse.Builder.class);
}
public static final int RESULTS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.shopping.merchant.reports.v1.ReportRow> results_;
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.shopping.merchant.reports.v1.ReportRow> getResultsList() {
return results_;
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.shopping.merchant.reports.v1.ReportRowOrBuilder>
getResultsOrBuilderList() {
return results_;
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
@java.lang.Override
public int getResultsCount() {
return results_.size();
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
@java.lang.Override
public com.google.shopping.merchant.reports.v1.ReportRow getResults(int index) {
return results_.get(index);
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
@java.lang.Override
public com.google.shopping.merchant.reports.v1.ReportRowOrBuilder getResultsOrBuilder(int index) {
return results_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token which can be sent as `page_token` to retrieve the next page. If
* 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>
* Token which can be sent as `page_token` to retrieve the next page. If
* 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 < results_.size(); i++) {
output.writeMessage(1, results_.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 < results_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, results_.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.reports.v1.SearchResponse)) {
return super.equals(obj);
}
com.google.shopping.merchant.reports.v1.SearchResponse other =
(com.google.shopping.merchant.reports.v1.SearchResponse) obj;
if (!getResultsList().equals(other.getResultsList())) 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 (getResultsCount() > 0) {
hash = (37 * hash) + RESULTS_FIELD_NUMBER;
hash = (53 * hash) + getResultsList().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.reports.v1.SearchResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.reports.v1.SearchResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.shopping.merchant.reports.v1.SearchResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.reports.v1.SearchResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.shopping.merchant.reports.v1.SearchResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.reports.v1.SearchResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.shopping.merchant.reports.v1.SearchResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.reports.v1.SearchResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.shopping.merchant.reports.v1.SearchResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.reports.v1.SearchResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.shopping.merchant.reports.v1.SearchResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.reports.v1.SearchResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.shopping.merchant.reports.v1.SearchResponse 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 `ReportService.Search` method.
* </pre>
*
* Protobuf type {@code google.shopping.merchant.reports.v1.SearchResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.shopping.merchant.reports.v1.SearchResponse)
com.google.shopping.merchant.reports.v1.SearchResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.shopping.merchant.reports.v1.ReportsProto
.internal_static_google_shopping_merchant_reports_v1_SearchResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.shopping.merchant.reports.v1.ReportsProto
.internal_static_google_shopping_merchant_reports_v1_SearchResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.shopping.merchant.reports.v1.SearchResponse.class,
com.google.shopping.merchant.reports.v1.SearchResponse.Builder.class);
}
// Construct using com.google.shopping.merchant.reports.v1.SearchResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (resultsBuilder_ == null) {
results_ = java.util.Collections.emptyList();
} else {
results_ = null;
resultsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.shopping.merchant.reports.v1.ReportsProto
.internal_static_google_shopping_merchant_reports_v1_SearchResponse_descriptor;
}
@java.lang.Override
public com.google.shopping.merchant.reports.v1.SearchResponse getDefaultInstanceForType() {
return com.google.shopping.merchant.reports.v1.SearchResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.shopping.merchant.reports.v1.SearchResponse build() {
com.google.shopping.merchant.reports.v1.SearchResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.shopping.merchant.reports.v1.SearchResponse buildPartial() {
com.google.shopping.merchant.reports.v1.SearchResponse result =
new com.google.shopping.merchant.reports.v1.SearchResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.shopping.merchant.reports.v1.SearchResponse result) {
if (resultsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
results_ = java.util.Collections.unmodifiableList(results_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.results_ = results_;
} else {
result.results_ = resultsBuilder_.build();
}
}
private void buildPartial0(com.google.shopping.merchant.reports.v1.SearchResponse 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.reports.v1.SearchResponse) {
return mergeFrom((com.google.shopping.merchant.reports.v1.SearchResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.shopping.merchant.reports.v1.SearchResponse other) {
if (other == com.google.shopping.merchant.reports.v1.SearchResponse.getDefaultInstance())
return this;
if (resultsBuilder_ == null) {
if (!other.results_.isEmpty()) {
if (results_.isEmpty()) {
results_ = other.results_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureResultsIsMutable();
results_.addAll(other.results_);
}
onChanged();
}
} else {
if (!other.results_.isEmpty()) {
if (resultsBuilder_.isEmpty()) {
resultsBuilder_.dispose();
resultsBuilder_ = null;
results_ = other.results_;
bitField0_ = (bitField0_ & ~0x00000001);
resultsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getResultsFieldBuilder()
: null;
} else {
resultsBuilder_.addAllMessages(other.results_);
}
}
}
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.reports.v1.ReportRow m =
input.readMessage(
com.google.shopping.merchant.reports.v1.ReportRow.parser(),
extensionRegistry);
if (resultsBuilder_ == null) {
ensureResultsIsMutable();
results_.add(m);
} else {
resultsBuilder_.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.reports.v1.ReportRow> results_ =
java.util.Collections.emptyList();
private void ensureResultsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
results_ =
new java.util.ArrayList<com.google.shopping.merchant.reports.v1.ReportRow>(results_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.shopping.merchant.reports.v1.ReportRow,
com.google.shopping.merchant.reports.v1.ReportRow.Builder,
com.google.shopping.merchant.reports.v1.ReportRowOrBuilder>
resultsBuilder_;
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public java.util.List<com.google.shopping.merchant.reports.v1.ReportRow> getResultsList() {
if (resultsBuilder_ == null) {
return java.util.Collections.unmodifiableList(results_);
} else {
return resultsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public int getResultsCount() {
if (resultsBuilder_ == null) {
return results_.size();
} else {
return resultsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public com.google.shopping.merchant.reports.v1.ReportRow getResults(int index) {
if (resultsBuilder_ == null) {
return results_.get(index);
} else {
return resultsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public Builder setResults(int index, com.google.shopping.merchant.reports.v1.ReportRow value) {
if (resultsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureResultsIsMutable();
results_.set(index, value);
onChanged();
} else {
resultsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public Builder setResults(
int index, com.google.shopping.merchant.reports.v1.ReportRow.Builder builderForValue) {
if (resultsBuilder_ == null) {
ensureResultsIsMutable();
results_.set(index, builderForValue.build());
onChanged();
} else {
resultsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public Builder addResults(com.google.shopping.merchant.reports.v1.ReportRow value) {
if (resultsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureResultsIsMutable();
results_.add(value);
onChanged();
} else {
resultsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public Builder addResults(int index, com.google.shopping.merchant.reports.v1.ReportRow value) {
if (resultsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureResultsIsMutable();
results_.add(index, value);
onChanged();
} else {
resultsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public Builder addResults(
com.google.shopping.merchant.reports.v1.ReportRow.Builder builderForValue) {
if (resultsBuilder_ == null) {
ensureResultsIsMutable();
results_.add(builderForValue.build());
onChanged();
} else {
resultsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public Builder addResults(
int index, com.google.shopping.merchant.reports.v1.ReportRow.Builder builderForValue) {
if (resultsBuilder_ == null) {
ensureResultsIsMutable();
results_.add(index, builderForValue.build());
onChanged();
} else {
resultsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public Builder addAllResults(
java.lang.Iterable<? extends com.google.shopping.merchant.reports.v1.ReportRow> values) {
if (resultsBuilder_ == null) {
ensureResultsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, results_);
onChanged();
} else {
resultsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public Builder clearResults() {
if (resultsBuilder_ == null) {
results_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
resultsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public Builder removeResults(int index) {
if (resultsBuilder_ == null) {
ensureResultsIsMutable();
results_.remove(index);
onChanged();
} else {
resultsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public com.google.shopping.merchant.reports.v1.ReportRow.Builder getResultsBuilder(int index) {
return getResultsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public com.google.shopping.merchant.reports.v1.ReportRowOrBuilder getResultsOrBuilder(
int index) {
if (resultsBuilder_ == null) {
return results_.get(index);
} else {
return resultsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public java.util.List<? extends com.google.shopping.merchant.reports.v1.ReportRowOrBuilder>
getResultsOrBuilderList() {
if (resultsBuilder_ != null) {
return resultsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(results_);
}
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public com.google.shopping.merchant.reports.v1.ReportRow.Builder addResultsBuilder() {
return getResultsFieldBuilder()
.addBuilder(com.google.shopping.merchant.reports.v1.ReportRow.getDefaultInstance());
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public com.google.shopping.merchant.reports.v1.ReportRow.Builder addResultsBuilder(int index) {
return getResultsFieldBuilder()
.addBuilder(
index, com.google.shopping.merchant.reports.v1.ReportRow.getDefaultInstance());
}
/**
*
*
* <pre>
* Rows that matched the search query.
* </pre>
*
* <code>repeated .google.shopping.merchant.reports.v1.ReportRow results = 1;</code>
*/
public java.util.List<com.google.shopping.merchant.reports.v1.ReportRow.Builder>
getResultsBuilderList() {
return getResultsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.shopping.merchant.reports.v1.ReportRow,
com.google.shopping.merchant.reports.v1.ReportRow.Builder,
com.google.shopping.merchant.reports.v1.ReportRowOrBuilder>
getResultsFieldBuilder() {
if (resultsBuilder_ == null) {
resultsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.shopping.merchant.reports.v1.ReportRow,
com.google.shopping.merchant.reports.v1.ReportRow.Builder,
com.google.shopping.merchant.reports.v1.ReportRowOrBuilder>(
results_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
results_ = null;
}
return resultsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token which can be sent as `page_token` to retrieve the next page. If
* 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>
* Token which can be sent as `page_token` to retrieve the next page. If
* 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>
* Token which can be sent as `page_token` to retrieve the next page. If
* 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>
* Token which can be sent as `page_token` to retrieve the next page. If
* 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>
* Token which can be sent as `page_token` to retrieve the next page. If
* 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.reports.v1.SearchResponse)
}
// @@protoc_insertion_point(class_scope:google.shopping.merchant.reports.v1.SearchResponse)
private static final com.google.shopping.merchant.reports.v1.SearchResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.shopping.merchant.reports.v1.SearchResponse();
}
public static com.google.shopping.merchant.reports.v1.SearchResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SearchResponse> PARSER =
new com.google.protobuf.AbstractParser<SearchResponse>() {
@java.lang.Override
public SearchResponse 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<SearchResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SearchResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.shopping.merchant.reports.v1.SearchResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,482 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/QuestionAnsweringQualityInput.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 quality metric.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput}
*/
public final class QuestionAnsweringQualityInput extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput)
QuestionAnsweringQualityInputOrBuilder {
private static final long serialVersionUID = 0L;
// Use QuestionAnsweringQualityInput.newBuilder() to construct.
private QuestionAnsweringQualityInput(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private QuestionAnsweringQualityInput() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new QuestionAnsweringQualityInput();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_QuestionAnsweringQualityInput_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_QuestionAnsweringQualityInput_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput.class,
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput.Builder.class);
}
private int bitField0_;
public static final int METRIC_SPEC_FIELD_NUMBER = 1;
private com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec metricSpec_;
/**
*
*
* <pre>
* Required. Spec for question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec 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 quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The metricSpec.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec getMetricSpec() {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec.getDefaultInstance()
: metricSpec_;
}
/**
*
*
* <pre>
* Required. Spec for question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpecOrBuilder
getMetricSpecOrBuilder() {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec.getDefaultInstance()
: metricSpec_;
}
public static final int INSTANCE_FIELD_NUMBER = 2;
private com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance instance_;
/**
*
*
* <pre>
* Required. Question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance 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 quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance getInstance() {
return instance_ == null
? com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance.getDefaultInstance()
: instance_;
}
/**
*
*
* <pre>
* Required. Question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstanceOrBuilder
getInstanceOrBuilder() {
return instance_ == null
? com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance.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.QuestionAnsweringQualityInput)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput other =
(com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput) 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.QuestionAnsweringQualityInput parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput 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.QuestionAnsweringQualityInput parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput 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.QuestionAnsweringQualityInput parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput 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.QuestionAnsweringQualityInput parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput 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.QuestionAnsweringQualityInput
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput
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.QuestionAnsweringQualityInput 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.QuestionAnsweringQualityInput 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.QuestionAnsweringQualityInput 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 quality metric.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput)
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInputOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_QuestionAnsweringQualityInput_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_QuestionAnsweringQualityInput_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput.class,
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput.Builder.class);
}
// Construct using
// com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput.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_QuestionAnsweringQualityInput_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput build() {
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput buildPartial() {
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput result =
new com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput 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.QuestionAnsweringQualityInput) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput other) {
if (other
== com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput.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.QuestionAnsweringQualitySpec metricSpec_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec,
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec.Builder,
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpecOrBuilder>
metricSpecBuilder_;
/**
*
*
* <pre>
* Required. Spec for question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec 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 quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The metricSpec.
*/
public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec getMetricSpec() {
if (metricSpecBuilder_ == null) {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec.getDefaultInstance()
: metricSpec_;
} else {
return metricSpecBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Spec for question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setMetricSpec(
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec 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 quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setMetricSpec(
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec.Builder builderForValue) {
if (metricSpecBuilder_ == null) {
metricSpec_ = builderForValue.build();
} else {
metricSpecBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Spec for question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeMetricSpec(
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec value) {
if (metricSpecBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& metricSpec_ != null
&& metricSpec_
!= com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec
.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 quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec 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 quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec.Builder
getMetricSpecBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getMetricSpecFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Spec for question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpecOrBuilder
getMetricSpecOrBuilder() {
if (metricSpecBuilder_ != null) {
return metricSpecBuilder_.getMessageOrBuilder();
} else {
return metricSpec_ == null
? com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec.getDefaultInstance()
: metricSpec_;
}
}
/**
*
*
* <pre>
* Required. Spec for question answering quality score metric.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec metric_spec = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec,
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec.Builder,
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpecOrBuilder>
getMetricSpecFieldBuilder() {
if (metricSpecBuilder_ == null) {
metricSpecBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec,
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpec.Builder,
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualitySpecOrBuilder>(
getMetricSpec(), getParentForChildren(), isClean());
metricSpec_ = null;
}
return metricSpecBuilder_;
}
private com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance instance_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance,
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance.Builder,
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstanceOrBuilder>
instanceBuilder_;
/**
*
*
* <pre>
* Required. Question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance 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 quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance getInstance() {
if (instanceBuilder_ == null) {
return instance_ == null
? com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance
.getDefaultInstance()
: instance_;
} else {
return instanceBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance 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 quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance.Builder
builderForValue) {
if (instanceBuilder_ == null) {
instance_ = builderForValue.build();
} else {
instanceBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeInstance(
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance value) {
if (instanceBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& instance_ != null
&& instance_
!= com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance
.getDefaultInstance()) {
getInstanceBuilder().mergeFrom(value);
} else {
instance_ = value;
}
} else {
instanceBuilder_.mergeFrom(value);
}
if (instance_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance 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 quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance.Builder
getInstanceBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getInstanceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstanceOrBuilder
getInstanceOrBuilder() {
if (instanceBuilder_ != null) {
return instanceBuilder_.getMessageOrBuilder();
} else {
return instance_ == null
? com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance
.getDefaultInstance()
: instance_;
}
}
/**
*
*
* <pre>
* Required. Question answering quality instance.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance instance = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance,
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance.Builder,
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstanceOrBuilder>
getInstanceFieldBuilder() {
if (instanceBuilder_ == null) {
instanceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance,
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstance.Builder,
com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInstanceOrBuilder>(
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.QuestionAnsweringQualityInput)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput)
private static final com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput();
}
public static com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<QuestionAnsweringQualityInput> PARSER =
new com.google.protobuf.AbstractParser<QuestionAnsweringQualityInput>() {
@java.lang.Override
public QuestionAnsweringQualityInput 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<QuestionAnsweringQualityInput> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<QuestionAnsweringQualityInput> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.QuestionAnsweringQualityInput
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
oracle/graal | 36,326 | sulong/projects/com.oracle.truffle.llvm.runtime/src/com/oracle/truffle/llvm/runtime/nodes/op/LLVMArithmeticNode.java | /*
* Copyright (c) 2016, 2023, Oracle and/or its affiliates.
*
* All rights reserved.
*
* 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 com.oracle.truffle.llvm.runtime.nodes.op;
import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.CreateCast;
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.interop.UnsupportedMessageException;
import com.oracle.truffle.api.nodes.UnexpectedResultException;
import com.oracle.truffle.api.profiles.ValueProfile;
import com.oracle.truffle.llvm.runtime.ArithmeticOperation;
import com.oracle.truffle.llvm.runtime.LLVMIVarBit;
import com.oracle.truffle.llvm.runtime.floating.LLVM128BitFloat;
import com.oracle.truffle.llvm.runtime.floating.LLVM80BitFloat;
import com.oracle.truffle.llvm.runtime.floating.LLVMLongDoubleFloatingPoint;
import com.oracle.truffle.llvm.runtime.floating.LLVMLongDoubleNode;
import com.oracle.truffle.llvm.runtime.floating.LLVMLongDoubleNode.LongDoubleKinds;
import com.oracle.truffle.llvm.runtime.interop.LLVMNegatedForeignObject;
import com.oracle.truffle.llvm.runtime.nodes.api.LLVMExpressionNode;
import com.oracle.truffle.llvm.runtime.nodes.api.LLVMNode;
import com.oracle.truffle.llvm.runtime.nodes.api.LLVMTypesGen;
import com.oracle.truffle.llvm.runtime.nodes.memory.LLVMNativePointerSupport;
import com.oracle.truffle.llvm.runtime.nodes.op.LLVMArithmeticNodeFactory.LLVMI64ArithmeticNodeGen;
import com.oracle.truffle.llvm.runtime.nodes.op.LLVMArithmeticNodeFactory.LLVMI64SubNodeGen;
import com.oracle.truffle.llvm.runtime.nodes.op.LLVMArithmeticNodeFactory.ManagedAndNodeGen;
import com.oracle.truffle.llvm.runtime.nodes.op.LLVMArithmeticNodeFactory.ManagedMulNodeGen;
import com.oracle.truffle.llvm.runtime.nodes.op.LLVMArithmeticNodeFactory.ManagedSubNodeGen;
import com.oracle.truffle.llvm.runtime.nodes.op.LLVMArithmeticNodeFactory.ManagedXorNodeGen;
import com.oracle.truffle.llvm.runtime.nodes.op.LLVMArithmeticNodeFactory.PointerToI64NodeGen;
import com.oracle.truffle.llvm.runtime.nodes.util.LLVMSameObjectNode;
import com.oracle.truffle.llvm.runtime.pointer.LLVMManagedPointer;
import com.oracle.truffle.llvm.runtime.pointer.LLVMPointer;
@NodeChild("leftNode")
@NodeChild("rightNode")
public abstract class LLVMArithmeticNode extends LLVMExpressionNode {
public abstract Object executeWithTarget(Object left, Object right);
private abstract static class LLVMArithmeticOp {
boolean doBoolean(boolean left, boolean right) {
int ret = doInt(left ? 1 : 0, right ? 1 : 0);
return (ret & 1) == 1;
}
abstract byte doByte(byte left, byte right);
abstract short doShort(short left, short right);
abstract int doInt(int left, int right);
abstract long doLong(long left, long right);
abstract LLVMIVarBit doVarBit(LLVMIVarBit left, LLVMIVarBit right);
boolean canDoManaged(@SuppressWarnings("unused") long operand) {
return false;
}
ManagedArithmeticNode createManagedNode() {
return null;
}
}
private abstract static class LLVMFPArithmeticOp extends LLVMArithmeticOp {
abstract float doFloat(float left, float right);
abstract double doDouble(double left, double right);
abstract LLVMLongDoubleNode createFP80Node();
abstract LLVMLongDoubleNode createFP128Node();
}
abstract static class ManagedArithmeticNode extends LLVMNode {
abstract Object execute(LLVMManagedPointer left, long right);
abstract Object execute(long left, LLVMManagedPointer right);
long executeLong(LLVMManagedPointer left, long right) throws UnexpectedResultException {
return LLVMTypesGen.expectLong(execute(left, right));
}
long executeLong(long left, LLVMManagedPointer right) throws UnexpectedResultException {
return LLVMTypesGen.expectLong(execute(left, right));
}
}
abstract static class ManagedCommutativeArithmeticNode extends ManagedArithmeticNode {
@Override
final Object execute(long left, LLVMManagedPointer right) {
return execute(right, left);
}
@Override
final long executeLong(long left, LLVMManagedPointer right) throws UnexpectedResultException {
return executeLong(right, left);
}
}
final LLVMArithmeticOp op;
protected boolean canDoManaged(long operand) {
return op.canDoManaged(operand);
}
protected LLVMArithmeticNode(ArithmeticOperation op) {
switch (op) {
case ADD:
this.op = ADD;
break;
case SUB:
this.op = SUB;
break;
case MUL:
this.op = MUL;
break;
case DIV:
this.op = DIV;
break;
case UDIV:
this.op = UDIV;
break;
case REM:
this.op = REM;
break;
case UREM:
this.op = UREM;
break;
case AND:
this.op = AND;
break;
case OR:
this.op = OR;
break;
case XOR:
this.op = XOR;
break;
case SHL:
this.op = SHL;
break;
case LSHR:
this.op = LSHR;
break;
case ASHR:
this.op = ASHR;
break;
default:
throw new AssertionError(op.name());
}
}
public abstract static class LLVMI1ArithmeticNode extends LLVMArithmeticNode {
LLVMI1ArithmeticNode(ArithmeticOperation op) {
super(op);
}
@Specialization
boolean doBoolean(boolean left, boolean right) {
return op.doBoolean(left, right);
}
}
public abstract static class LLVMI8ArithmeticNode extends LLVMArithmeticNode {
LLVMI8ArithmeticNode(ArithmeticOperation op) {
super(op);
}
@Specialization
byte doByte(byte left, byte right) {
return op.doByte(left, right);
}
}
public abstract static class LLVMI16ArithmeticNode extends LLVMArithmeticNode {
LLVMI16ArithmeticNode(ArithmeticOperation op) {
super(op);
}
@Specialization
short doShort(short left, short right) {
return op.doShort(left, right);
}
}
public abstract static class LLVMI32ArithmeticNode extends LLVMArithmeticNode {
LLVMI32ArithmeticNode(ArithmeticOperation op) {
super(op);
}
@Specialization
int doInt(int left, int right) {
return op.doInt(left, right);
}
}
@NodeChild
public abstract static class PointerToI64Node extends LLVMExpressionNode {
@Specialization
long doLong(long l) {
return l;
}
@Specialization(guards = "isPointer.execute(ptr)", rewriteOn = UnsupportedMessageException.class)
long doPointer(Object ptr,
@SuppressWarnings("unused") @Cached LLVMNativePointerSupport.IsPointerNode isPointer,
@Cached LLVMNativePointerSupport.AsPointerNode asPointer) throws UnsupportedMessageException {
return asPointer.execute(ptr);
}
@Specialization(guards = "!isPointer.execute(ptr)")
Object doManaged(Object ptr,
@SuppressWarnings("unused") @Cached LLVMNativePointerSupport.IsPointerNode isPointer) {
return ptr;
}
@Specialization(replaces = {"doLong", "doPointer", "doManaged"})
Object doGeneric(Object ptr,
@SuppressWarnings("unused") @Cached LLVMNativePointerSupport.IsPointerNode isPointer,
@Cached LLVMNativePointerSupport.AsPointerNode asPointer) {
if (isPointer.execute(ptr)) {
try {
return asPointer.execute(ptr);
} catch (UnsupportedMessageException ex) {
// ignore
}
}
return ptr;
}
}
/**
* We try to preserve pointers as good as possible because pointers to foreign objects can
* usually not be converted to i64. Even if the foreign object implements the pointer messages,
* the conversion is usually one-way.
*/
public abstract static class LLVMAbstractI64ArithmeticNode extends LLVMArithmeticNode {
public abstract long executeLongWithTarget(long left, long right);
public static LLVMAbstractI64ArithmeticNode create(ArithmeticOperation op, LLVMExpressionNode left, LLVMExpressionNode right) {
if (op == ArithmeticOperation.SUB) {
return LLVMI64SubNodeGen.create(left, right);
} else {
return LLVMI64ArithmeticNodeGen.create(op, left, right);
}
}
protected LLVMAbstractI64ArithmeticNode(ArithmeticOperation op) {
super(op);
}
@CreateCast({"leftNode", "rightNode"})
PointerToI64Node createCast(LLVMExpressionNode child) {
return PointerToI64NodeGen.create(child);
}
@Specialization
protected long doLong(long left, long right) {
return op.doLong(left, right);
}
ManagedArithmeticNode createManagedNode() {
return op.createManagedNode();
}
@Specialization(guards = "canDoManaged(right)", rewriteOn = UnexpectedResultException.class)
long doManagedLeftLong(LLVMManagedPointer left, long right,
@Cached("createManagedNode()") ManagedArithmeticNode node) throws UnexpectedResultException {
return node.executeLong(left, right);
}
@Specialization(guards = "canDoManaged(right)", replaces = "doManagedLeftLong")
Object doManagedLeft(LLVMManagedPointer left, long right,
@Cached("createManagedNode()") ManagedArithmeticNode node) {
return node.execute(left, right);
}
@Specialization(guards = "canDoManaged(left)", rewriteOn = UnexpectedResultException.class)
long doManagedRightLong(long left, LLVMManagedPointer right,
@Cached("createManagedNode()") ManagedArithmeticNode node) throws UnexpectedResultException {
return node.executeLong(left, right);
}
@Specialization(guards = "canDoManaged(left)", replaces = "doManagedRightLong")
Object doManagedRight(long left, LLVMManagedPointer right,
@Cached("createManagedNode()") ManagedArithmeticNode node) {
return node.execute(left, right);
}
@Specialization(guards = "!canDoManaged(left)")
long doPointerRight(long left, LLVMPointer right,
@Cached LLVMNativePointerSupport.ToNativePointerNode toNativePointerRight) {
return op.doLong(left, toNativePointerRight.execute(right).asNative());
}
@Specialization(guards = "!canDoManaged(right)")
long doPointerLeft(LLVMPointer left, long right,
@Cached LLVMNativePointerSupport.ToNativePointerNode toNativePointerLeft) {
return op.doLong(toNativePointerLeft.execute(left).asNative(), right);
}
}
abstract static class LLVMI64ArithmeticNode extends LLVMAbstractI64ArithmeticNode {
protected LLVMI64ArithmeticNode(ArithmeticOperation op) {
super(op);
}
@Specialization
long doPointer(LLVMPointer left, LLVMPointer right,
@Cached LLVMNativePointerSupport.ToNativePointerNode toNativePointerLeft,
@Cached LLVMNativePointerSupport.ToNativePointerNode toNativePointerRight) {
return op.doLong(toNativePointerLeft.execute(left).asNative(), toNativePointerRight.execute(right).asNative());
}
}
abstract static class LLVMI64SubNode extends LLVMAbstractI64ArithmeticNode {
protected LLVMI64SubNode() {
super(ArithmeticOperation.SUB);
}
@Specialization(guards = "sameObject.execute(left.getObject(), right.getObject())")
long doSameObjectLong(LLVMManagedPointer left, LLVMManagedPointer right,
@SuppressWarnings("unused") @Cached LLVMSameObjectNode sameObject) {
return left.getOffset() - right.getOffset();
}
@Specialization(guards = "!sameObject.execute(left.getObject(), right.getObject())")
long doNotSameObject(LLVMManagedPointer left, LLVMManagedPointer right,
@SuppressWarnings("unused") @Cached LLVMSameObjectNode sameObject,
@Cached LLVMNativePointerSupport.ToNativePointerNode toNativePointerLeft,
@Cached LLVMNativePointerSupport.ToNativePointerNode toNativePointerRight) {
return toNativePointerLeft.execute(left).asNative() - toNativePointerRight.execute(right).asNative();
}
}
public abstract static class LLVMIVarBitArithmeticNode extends LLVMArithmeticNode {
LLVMIVarBitArithmeticNode(ArithmeticOperation op) {
super(op);
}
@Specialization
LLVMIVarBit doVarBit(LLVMIVarBit left, LLVMIVarBit right) {
return op.doVarBit(left, right);
}
}
public abstract static class LLVMFloatingArithmeticNode extends LLVMArithmeticNode {
LLVMFloatingArithmeticNode(ArithmeticOperation op) {
super(op);
assert this.op instanceof LLVMFPArithmeticOp;
}
LLVMFPArithmeticOp fpOp() {
return (LLVMFPArithmeticOp) op;
}
}
public abstract static class LLVMFloatArithmeticNode extends LLVMFloatingArithmeticNode {
LLVMFloatArithmeticNode(ArithmeticOperation op) {
super(op);
}
@Specialization
float doFloat(float left, float right) {
return fpOp().doFloat(left, right);
}
}
public abstract static class LLVMDoubleArithmeticNode extends LLVMFloatingArithmeticNode {
LLVMDoubleArithmeticNode(ArithmeticOperation op) {
super(op);
}
@Specialization
double doDouble(double left, double right) {
return fpOp().doDouble(left, right);
}
}
public abstract static class LLVMFP80ArithmeticNode extends LLVMFloatingArithmeticNode {
LLVMFP80ArithmeticNode(ArithmeticOperation op) {
super(op);
}
LLVMLongDoubleNode createFP80Node() {
return fpOp().createFP80Node();
}
@Specialization
LLVMLongDoubleFloatingPoint do80BitFloat(LLVM80BitFloat left, LLVM80BitFloat right,
@Cached("createFP80Node()") LLVMLongDoubleNode node) {
return node.execute(left, right);
}
}
public abstract static class LLVMFP128ArithmeticNode extends LLVMFloatingArithmeticNode {
LLVMFP128ArithmeticNode(ArithmeticOperation op) {
super(op);
}
LLVMLongDoubleNode createFP128Node() {
return fpOp().createFP128Node();
}
@Specialization
LLVMLongDoubleFloatingPoint do128BitFloat(LLVM128BitFloat left, LLVM128BitFloat right,
@Cached("createFP128Node()") LLVMLongDoubleNode node) {
return node.execute(left, right);
}
}
static final class ManagedAddNode extends ManagedCommutativeArithmeticNode {
@Override
Object execute(LLVMManagedPointer left, long right) {
return left.increment(right);
}
}
private static final LLVMFPArithmeticOp ADD = new LLVMFPArithmeticOp() {
@Override
boolean doBoolean(boolean left, boolean right) {
return left ^ right;
}
@Override
byte doByte(byte left, byte right) {
return (byte) (left + right);
}
@Override
short doShort(short left, short right) {
return (short) (left + right);
}
@Override
int doInt(int left, int right) {
return left + right;
}
@Override
long doLong(long left, long right) {
return left + right;
}
@Override
boolean canDoManaged(long op) {
return true;
}
@Override
ManagedArithmeticNode createManagedNode() {
return new ManagedAddNode();
}
@Override
LLVMIVarBit doVarBit(LLVMIVarBit left, LLVMIVarBit right) {
return left.add(right);
}
@Override
float doFloat(float left, float right) {
return left + right;
}
@Override
double doDouble(double left, double right) {
return left + right;
}
@Override
LLVMLongDoubleNode createFP80Node() {
return LLVMLongDoubleNode.createAddNode(LongDoubleKinds.FP80);
}
@Override
LLVMLongDoubleNode createFP128Node() {
return LLVMLongDoubleNode.createAddNode(LongDoubleKinds.FP128);
}
@Override
public String toString() {
return "ADD";
}
};
abstract static class ManagedMulNode extends ManagedCommutativeArithmeticNode {
@Specialization(guards = "right == 1")
LLVMManagedPointer doIdentity(LLVMManagedPointer left, @SuppressWarnings("unused") long right) {
return left;
}
/**
* @param left
* @param right
* @see #execute(LLVMManagedPointer, long)
*/
@Specialization(guards = "right == 0")
long doZero(LLVMManagedPointer left, long right) {
return 0;
}
static boolean isMinusOne(long v) {
return v == -1L;
}
@Specialization(guards = "isMinusOne(right)")
LLVMManagedPointer doNegate(LLVMManagedPointer left, @SuppressWarnings("unused") long right) {
Object negated = LLVMNegatedForeignObject.negate(left.getObject());
return LLVMManagedPointer.create(negated, -left.getOffset());
}
}
private static final LLVMFPArithmeticOp MUL = new LLVMFPArithmeticOp() {
@Override
boolean doBoolean(boolean left, boolean right) {
return left & right;
}
@Override
byte doByte(byte left, byte right) {
return (byte) (left * right);
}
@Override
short doShort(short left, short right) {
return (short) (left * right);
}
@Override
int doInt(int left, int right) {
return left * right;
}
@Override
long doLong(long left, long right) {
return left * right;
}
@Override
boolean canDoManaged(long op) {
return op == 1 || op == -1 || op == 0;
}
@Override
ManagedArithmeticNode createManagedNode() {
return ManagedMulNodeGen.create();
}
@Override
LLVMIVarBit doVarBit(LLVMIVarBit left, LLVMIVarBit right) {
return left.mul(right);
}
@Override
float doFloat(float left, float right) {
return left * right;
}
@Override
double doDouble(double left, double right) {
return left * right;
}
@Override
LLVMLongDoubleNode createFP80Node() {
return LLVMLongDoubleNode.createMulNode(LongDoubleKinds.FP80);
}
@Override
LLVMLongDoubleNode createFP128Node() {
return LLVMLongDoubleNode.createMulNode(LongDoubleKinds.FP128);
}
@Override
public String toString() {
return "MUL";
}
};
abstract static class ManagedSubNode extends ManagedArithmeticNode {
@Specialization
LLVMManagedPointer doLeft(LLVMManagedPointer left, long right) {
return left.increment(-right);
}
@Specialization
LLVMManagedPointer doRight(long left, LLVMManagedPointer right,
@Cached("createClassProfile()") ValueProfile type) {
// type profile to be able to do fast-path negate-negate
Object foreign = type.profile(right.getObject());
Object negated = LLVMNegatedForeignObject.negate(foreign);
return LLVMManagedPointer.create(negated, left - right.getOffset());
}
}
private static final LLVMFPArithmeticOp SUB = new LLVMFPArithmeticOp() {
@Override
boolean doBoolean(boolean left, boolean right) {
return left ^ right;
}
@Override
byte doByte(byte left, byte right) {
return (byte) (left - right);
}
@Override
short doShort(short left, short right) {
return (short) (left - right);
}
@Override
int doInt(int left, int right) {
return left - right;
}
@Override
long doLong(long left, long right) {
return left - right;
}
@Override
boolean canDoManaged(long op) {
return true;
}
@Override
ManagedArithmeticNode createManagedNode() {
return ManagedSubNodeGen.create();
}
@Override
LLVMIVarBit doVarBit(LLVMIVarBit left, LLVMIVarBit right) {
return left.sub(right);
}
@Override
float doFloat(float left, float right) {
return left - right;
}
@Override
double doDouble(double left, double right) {
return left - right;
}
@Override
LLVMLongDoubleNode createFP80Node() {
return LLVMLongDoubleNode.createSubNode(LongDoubleKinds.FP80);
}
@Override
LLVMLongDoubleNode createFP128Node() {
return LLVMLongDoubleNode.createSubNode(LongDoubleKinds.FP128);
}
@Override
public String toString() {
return "SUB";
}
};
private static final LLVMFPArithmeticOp DIV = new LLVMFPArithmeticOp() {
@Override
byte doByte(byte left, byte right) {
return (byte) (left / right);
}
@Override
short doShort(short left, short right) {
return (short) (left / right);
}
@Override
int doInt(int left, int right) {
return left / right;
}
@Override
long doLong(long left, long right) {
return left / right;
}
@Override
LLVMIVarBit doVarBit(LLVMIVarBit left, LLVMIVarBit right) {
return left.div(right);
}
@Override
float doFloat(float left, float right) {
return left / right;
}
@Override
double doDouble(double left, double right) {
return left / right;
}
@Override
LLVMLongDoubleNode createFP80Node() {
return LLVMLongDoubleNode.createDivNode(LongDoubleKinds.FP80);
}
@Override
LLVMLongDoubleNode createFP128Node() {
return LLVMLongDoubleNode.createDivNode(LongDoubleKinds.FP128);
}
@Override
public String toString() {
return "DIV";
}
};
private static final LLVMArithmeticOp UDIV = new LLVMArithmeticOp() {
@Override
byte doByte(byte left, byte right) {
return (byte) (Byte.toUnsignedInt(left) / Byte.toUnsignedInt(right));
}
@Override
short doShort(short left, short right) {
return (short) (Short.toUnsignedInt(left) / Short.toUnsignedInt(right));
}
@Override
int doInt(int left, int right) {
return Integer.divideUnsigned(left, right);
}
@Override
long doLong(long left, long right) {
return Long.divideUnsigned(left, right);
}
@Override
LLVMIVarBit doVarBit(LLVMIVarBit left, LLVMIVarBit right) {
return left.unsignedDiv(right);
}
@Override
public String toString() {
return "UDIV";
}
};
private static final LLVMFPArithmeticOp REM = new LLVMFPArithmeticOp() {
@Override
byte doByte(byte left, byte right) {
return (byte) (left % right);
}
@Override
short doShort(short left, short right) {
return (short) (left % right);
}
@Override
int doInt(int left, int right) {
return left % right;
}
@Override
long doLong(long left, long right) {
return left % right;
}
@Override
LLVMIVarBit doVarBit(LLVMIVarBit left, LLVMIVarBit right) {
return left.rem(right);
}
@Override
float doFloat(float left, float right) {
return left % right;
}
@Override
double doDouble(double left, double right) {
return left % right;
}
@Override
LLVMLongDoubleNode createFP80Node() {
return LLVMLongDoubleNode.createRemNode(LongDoubleKinds.FP80);
}
@Override
LLVMLongDoubleNode createFP128Node() {
return LLVMLongDoubleNode.createRemNode(LongDoubleKinds.FP128);
}
@Override
public String toString() {
return "REM";
}
};
private static final LLVMArithmeticOp UREM = new LLVMArithmeticOp() {
@Override
byte doByte(byte left, byte right) {
return (byte) (Byte.toUnsignedInt(left) % Byte.toUnsignedInt(right));
}
@Override
short doShort(short left, short right) {
return (short) (Short.toUnsignedInt(left) % Short.toUnsignedInt(right));
}
@Override
int doInt(int left, int right) {
return Integer.remainderUnsigned(left, right);
}
@Override
long doLong(long left, long right) {
return Long.remainderUnsigned(left, right);
}
@Override
LLVMIVarBit doVarBit(LLVMIVarBit left, LLVMIVarBit right) {
return left.unsignedRem(right);
}
@Override
public String toString() {
return "UREM";
}
};
abstract static class ManagedAndNode extends ManagedCommutativeArithmeticNode {
/*
* For doing certain pointer arithmetics on managed pointers, we assume that a pointer
* consists of n offset and m pointer identity bits. As long as the pointer offset bits are
* manipulated, the pointer still points to the same managed object. If the pointer identity
* bits are changed, we assume that the pointer will point to a different object, i.e., that
* the pointer is destroyed.
*/
private static final int POINTER_OFFSET_BITS = 32;
static boolean highBitsSet(long op) {
// if the high bits are all set, this AND is used for alignment
long highBits = op >> POINTER_OFFSET_BITS;
return highBits == -1L;
}
@Specialization(guards = "highBitsSet(right)")
LLVMManagedPointer doAlign(LLVMManagedPointer left, long right) {
return LLVMManagedPointer.create(left.getObject(), left.getOffset() & right);
}
static boolean highBitsClear(long op) {
// if the high bits are all clear, this AND drops the base of the pointer
long highBits = op >> POINTER_OFFSET_BITS;
return highBits == 0L;
}
@Specialization(guards = "highBitsClear(right)")
long doMask(LLVMManagedPointer left, long right) {
return left.getOffset() & right;
}
}
private static final LLVMArithmeticOp AND = new LLVMArithmeticOp() {
@Override
boolean doBoolean(boolean left, boolean right) {
return left && right;
}
@Override
byte doByte(byte left, byte right) {
return (byte) (left & right);
}
@Override
short doShort(short left, short right) {
return (short) (left & right);
}
@Override
int doInt(int left, int right) {
return left & right;
}
@Override
long doLong(long left, long right) {
return left & right;
}
@Override
boolean canDoManaged(long op) {
return ManagedAndNode.highBitsSet(op) || ManagedAndNode.highBitsClear(op);
}
@Override
ManagedArithmeticNode createManagedNode() {
return ManagedAndNodeGen.create();
}
@Override
LLVMIVarBit doVarBit(LLVMIVarBit left, LLVMIVarBit right) {
return left.and(right);
}
@Override
public String toString() {
return "ADD";
}
};
private static final LLVMArithmeticOp OR = new LLVMArithmeticOp() {
@Override
boolean doBoolean(boolean left, boolean right) {
return left || right;
}
@Override
byte doByte(byte left, byte right) {
return (byte) (left | right);
}
@Override
short doShort(short left, short right) {
return (short) (left | right);
}
@Override
int doInt(int left, int right) {
return left | right;
}
@Override
long doLong(long left, long right) {
return left | right;
}
@Override
LLVMIVarBit doVarBit(LLVMIVarBit left, LLVMIVarBit right) {
return left.or(right);
}
@Override
public String toString() {
return "OR";
}
};
abstract static class ManagedXorNode extends ManagedCommutativeArithmeticNode {
@Specialization
LLVMManagedPointer doXor(LLVMManagedPointer left, long right,
@Cached("createClassProfile()") ValueProfile type) {
// type profile to be able to do fast-path negate-negate
Object foreign = type.profile(left.getObject());
assert right == -1L;
// -a is the two's complement, i.e. -a == (a ^ -1) + 1
// therefore, (a ^ -1) == -a - 1
Object negated = LLVMNegatedForeignObject.negate(foreign);
return LLVMManagedPointer.create(negated, -left.getOffset() - 1);
}
}
private static final LLVMArithmeticOp XOR = new LLVMArithmeticOp() {
@Override
boolean doBoolean(boolean left, boolean right) {
return left ^ right;
}
@Override
byte doByte(byte left, byte right) {
return (byte) (left ^ right);
}
@Override
short doShort(short left, short right) {
return (short) (left ^ right);
}
@Override
int doInt(int left, int right) {
return left ^ right;
}
@Override
long doLong(long left, long right) {
return left ^ right;
}
@Override
boolean canDoManaged(long op) {
return op == -1L;
}
@Override
ManagedArithmeticNode createManagedNode() {
return ManagedXorNodeGen.create();
}
@Override
LLVMIVarBit doVarBit(LLVMIVarBit left, LLVMIVarBit right) {
return left.xor(right);
}
@Override
public String toString() {
return "XOR";
}
};
private static final LLVMArithmeticOp SHL = new LLVMArithmeticOp() {
@Override
boolean doBoolean(boolean left, boolean right) {
return right ? false : left;
}
@Override
byte doByte(byte left, byte right) {
return (byte) (left << right);
}
@Override
short doShort(short left, short right) {
return (short) (left << right);
}
@Override
int doInt(int left, int right) {
return left << right;
}
@Override
long doLong(long left, long right) {
return left << right;
}
@Override
LLVMIVarBit doVarBit(LLVMIVarBit left, LLVMIVarBit right) {
return left.leftShift(right);
}
@Override
public String toString() {
return "SHL";
}
};
private static final LLVMArithmeticOp LSHR = new LLVMArithmeticOp() {
@Override
boolean doBoolean(boolean left, boolean right) {
return right ? false : left;
}
@Override
byte doByte(byte left, byte right) {
return (byte) ((left & LLVMExpressionNode.I8_MASK) >>> right);
}
@Override
short doShort(short left, short right) {
return (short) ((left & LLVMExpressionNode.I16_MASK) >>> right);
}
@Override
int doInt(int left, int right) {
return left >>> right;
}
@Override
long doLong(long left, long right) {
return left >>> right;
}
@Override
LLVMIVarBit doVarBit(LLVMIVarBit left, LLVMIVarBit right) {
return left.logicalRightShift(right);
}
@Override
public String toString() {
return "LSHL";
}
};
private static final LLVMArithmeticOp ASHR = new LLVMArithmeticOp() {
@Override
boolean doBoolean(boolean left, boolean right) {
return left;
}
@Override
byte doByte(byte left, byte right) {
return (byte) (left >> right);
}
@Override
short doShort(short left, short right) {
return (short) (left >> right);
}
@Override
int doInt(int left, int right) {
return left >> right;
}
@Override
long doLong(long left, long right) {
return left >> right;
}
@Override
LLVMIVarBit doVarBit(LLVMIVarBit left, LLVMIVarBit right) {
return left.arithmeticRightShift(right);
}
@Override
public String toString() {
return "ASHR";
}
};
}
|
apache/tinkerpop | 36,810 | gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/io/graphson/GraphSONSerializersV3.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.tinkerpop.gremlin.structure.io.graphson;
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.MutablePath;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.apache.tinkerpop.gremlin.process.traversal.util.DefaultTraversalMetrics;
import org.apache.tinkerpop.gremlin.process.traversal.util.ImmutableExplanation;
import org.apache.tinkerpop.gremlin.process.traversal.util.Metrics;
import org.apache.tinkerpop.gremlin.process.traversal.util.MutableMetrics;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalExplanation;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalMetrics;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.apache.tinkerpop.gremlin.structure.util.Comparators;
import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedEdge;
import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedFactory;
import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedProperty;
import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex;
import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertexProperty;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import org.apache.tinkerpop.shaded.jackson.core.JsonGenerationException;
import org.apache.tinkerpop.shaded.jackson.core.JsonGenerator;
import org.apache.tinkerpop.shaded.jackson.core.JsonParser;
import org.apache.tinkerpop.shaded.jackson.core.JsonProcessingException;
import org.apache.tinkerpop.shaded.jackson.core.JsonToken;
import org.apache.tinkerpop.shaded.jackson.databind.DeserializationContext;
import org.apache.tinkerpop.shaded.jackson.databind.JavaType;
import org.apache.tinkerpop.shaded.jackson.databind.SerializerProvider;
import org.apache.tinkerpop.shaded.jackson.databind.deser.std.StdDeserializer;
import org.apache.tinkerpop.shaded.jackson.databind.jsontype.TypeSerializer;
import org.apache.tinkerpop.shaded.jackson.databind.ser.std.StdKeySerializer;
import org.apache.tinkerpop.shaded.jackson.databind.ser.std.StdScalarSerializer;
import org.apache.tinkerpop.shaded.jackson.databind.type.TypeFactory;
import org.javatuples.Pair;
import org.javatuples.Triplet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONUtil.safeWriteObjectField;
/**
* GraphSON serializers for graph-based objects such as vertices, edges, properties, and paths. These serializers
* present a generalized way to serialize the implementations of core interfaces.
*
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
class GraphSONSerializersV3 {
private GraphSONSerializersV3() {
}
////////////////////////////// SERIALIZERS /////////////////////////////////
final static class VertexJacksonSerializer extends StdScalarSerializer<Vertex> {
private final boolean normalize;
private final TypeInfo typeInfo;
public VertexJacksonSerializer(final boolean normalize, final TypeInfo typeInfo) {
super(Vertex.class);
this.normalize = normalize;
this.typeInfo = typeInfo;
}
@Override
public void serialize(final Vertex vertex, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider)
throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField(GraphSONTokens.ID, vertex.id());
jsonGenerator.writeStringField(GraphSONTokens.LABEL, vertex.label());
writeTypeForGraphObjectIfUntyped(jsonGenerator, typeInfo, GraphSONTokens.VERTEX);
writeProperties(vertex, jsonGenerator, serializerProvider);
jsonGenerator.writeEndObject();
}
private void writeProperties(final Vertex vertex, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) throws IOException {
if (vertex.keys().size() == 0)
return;
jsonGenerator.writeFieldName(GraphSONTokens.PROPERTIES);
jsonGenerator.writeStartObject();
final List<String> keys = normalize ?
IteratorUtils.list(vertex.keys().iterator(), Comparator.naturalOrder()) : new ArrayList<>(vertex.keys());
for (String key : keys) {
final Iterator<VertexProperty<Object>> vertexProperties = normalize ?
IteratorUtils.list(vertex.properties(key), Comparators.PROPERTY_COMPARATOR).iterator() : vertex.properties(key);
if (vertexProperties.hasNext()) {
jsonGenerator.writeFieldName(key);
jsonGenerator.writeStartArray();
while (vertexProperties.hasNext()) {
// if you writeObject the property directly it treats it as a standalone VertexProperty which
// will write the label duplicating it. we really only want that for embedded types
if (typeInfo == TypeInfo.NO_TYPES) {
VertexPropertyJacksonSerializer.writeVertexProperty(vertexProperties.next(), jsonGenerator,
serializerProvider, normalize, false);
} else {
jsonGenerator.writeObject(vertexProperties.next());
}
}
jsonGenerator.writeEndArray();
}
}
jsonGenerator.writeEndObject();
}
}
final static class EdgeJacksonSerializer extends StdScalarSerializer<Edge> {
private final boolean normalize;
private final TypeInfo typeInfo;
public EdgeJacksonSerializer(final boolean normalize, final TypeInfo typeInfo) {
super(Edge.class);
this.normalize = normalize;
this.typeInfo = typeInfo;
}
@Override
public void serialize(final Edge edge, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider)
throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField(GraphSONTokens.ID, edge.id());
jsonGenerator.writeStringField(GraphSONTokens.LABEL, edge.label());
writeTypeForGraphObjectIfUntyped(jsonGenerator, typeInfo, GraphSONTokens.EDGE);
jsonGenerator.writeStringField(GraphSONTokens.IN_LABEL, edge.inVertex().label());
jsonGenerator.writeStringField(GraphSONTokens.OUT_LABEL, edge.outVertex().label());
jsonGenerator.writeObjectField(GraphSONTokens.IN, edge.inVertex().id());
jsonGenerator.writeObjectField(GraphSONTokens.OUT, edge.outVertex().id());
writeProperties(edge, jsonGenerator);
jsonGenerator.writeEndObject();
}
private void writeProperties(final Edge edge, final JsonGenerator jsonGenerator) throws IOException {
final Iterator<Property<Object>> elementProperties = normalize ?
IteratorUtils.list(edge.properties(), Comparators.PROPERTY_COMPARATOR).iterator() : edge.properties();
if (elementProperties.hasNext()) {
jsonGenerator.writeFieldName(GraphSONTokens.PROPERTIES);
jsonGenerator.writeStartObject();
if (typeInfo == TypeInfo.NO_TYPES)
elementProperties.forEachRemaining(prop -> safeWriteObjectField(jsonGenerator, prop.key(), prop.value()));
else
elementProperties.forEachRemaining(prop -> safeWriteObjectField(jsonGenerator, prop.key(), prop));
jsonGenerator.writeEndObject();
}
}
}
final static class PropertyJacksonSerializer extends StdScalarSerializer<Property> {
public PropertyJacksonSerializer() {
super(Property.class);
}
@Override
public void serialize(final Property property, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider)
throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField(GraphSONTokens.KEY, property.key());
jsonGenerator.writeObjectField(GraphSONTokens.VALUE, property.value());
jsonGenerator.writeEndObject();
}
}
final static class VertexPropertyJacksonSerializer extends StdScalarSerializer<VertexProperty> {
private final boolean normalize;
private final boolean includeLabel;
public VertexPropertyJacksonSerializer(final boolean normalize, final boolean includeLabel) {
super(VertexProperty.class);
this.normalize = normalize;
this.includeLabel = includeLabel;
}
@Override
public void serialize(final VertexProperty property, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider)
throws IOException {
writeVertexProperty(property, jsonGenerator, serializerProvider, normalize, includeLabel);
}
private static void writeVertexProperty(final VertexProperty property, final JsonGenerator jsonGenerator,
final SerializerProvider serializerProvider, final boolean normalize,
final boolean includeLabel)
throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField(GraphSONTokens.ID, property.id());
jsonGenerator.writeObjectField(GraphSONTokens.VALUE, property.value());
if (includeLabel)
jsonGenerator.writeStringField(GraphSONTokens.LABEL, property.label());
tryWriteMetaProperties(property, jsonGenerator, normalize);
jsonGenerator.writeEndObject();
}
private static void tryWriteMetaProperties(final VertexProperty property, final JsonGenerator jsonGenerator,
final boolean normalize) throws IOException {
// when "detached" you can't check features of the graph it detached from so it has to be
// treated differently from a regular VertexProperty implementation.
if (property instanceof DetachedVertexProperty) {
// only write meta properties key if they exist
if (property.properties().hasNext()) {
writeMetaProperties(property, jsonGenerator, normalize);
}
} else {
// still attached - so we can check the features to see if it's worth even trying to write the
// meta properties key
if (property.graph().features().vertex().supportsMetaProperties() && property.properties().hasNext()) {
writeMetaProperties(property, jsonGenerator, normalize);
}
}
}
private static void writeMetaProperties(final VertexProperty property, final JsonGenerator jsonGenerator,
final boolean normalize) throws IOException {
jsonGenerator.writeFieldName(GraphSONTokens.PROPERTIES);
jsonGenerator.writeStartObject();
final Iterator<Property<Object>> metaProperties = normalize ?
IteratorUtils.list((Iterator<Property<Object>>) property.properties(), Comparators.PROPERTY_COMPARATOR).iterator() : property.properties();
while (metaProperties.hasNext()) {
final Property<Object> metaProperty = metaProperties.next();
jsonGenerator.writeObjectField(metaProperty.key(), metaProperty.value());
}
jsonGenerator.writeEndObject();
}
}
final static class PathJacksonSerializer extends StdScalarSerializer<Path> {
public PathJacksonSerializer() {
super(Path.class);
}
@Override
public void serialize(final Path path, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider)
throws IOException, JsonGenerationException {
jsonGenerator.writeStartObject();
// prior to 3.7.5, the code was such that:
// paths shouldn't serialize with properties if the path contains graph elements
//
// however, there was the idea that v3 untyped should essentially match v1 which does include the
// properties. as of 3.7.5, we remove detachment to references and allow users to control the inclusion
// or exclusion of properties with the materializeProperties option.
jsonGenerator.writeObjectField(GraphSONTokens.LABELS, path.labels());
jsonGenerator.writeObjectField(GraphSONTokens.OBJECTS, path.objects());
jsonGenerator.writeEndObject();
}
}
final static class TreeJacksonSerializer extends StdScalarSerializer<Tree> {
public TreeJacksonSerializer() {
super(Tree.class);
}
@Override
public void serialize(final Tree tree, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) throws IOException, JsonGenerationException {
jsonGenerator.writeStartArray();
final Set<Map.Entry<Element, Tree>> set = tree.entrySet();
for (Map.Entry<Element, Tree> entry : set) {
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField(GraphSONTokens.KEY, entry.getKey());
jsonGenerator.writeObjectField(GraphSONTokens.VALUE, entry.getValue());
jsonGenerator.writeEndObject();
}
jsonGenerator.writeEndArray();
}
}
final static class TraversalExplanationJacksonSerializer extends StdScalarSerializer<TraversalExplanation> {
public TraversalExplanationJacksonSerializer() {
super(TraversalExplanation.class);
}
@Override
public void serialize(final TraversalExplanation traversalExplanation, final JsonGenerator jsonGenerator,
final SerializerProvider serializerProvider) throws IOException {
final Map<String, Object> m = new LinkedHashMap<>();
m.put(GraphSONTokens.ORIGINAL, getStepsAsList(traversalExplanation.getOriginalTraversal()));
final List<Pair<TraversalStrategy, Traversal.Admin<?, ?>>> strategyTraversals = traversalExplanation.getStrategyTraversals();
final List<Map<String, Object>> intermediates = new ArrayList<>();
for (final Pair<TraversalStrategy, Traversal.Admin<?, ?>> pair : strategyTraversals) {
final Map<String, Object> intermediate = new LinkedHashMap<>();
intermediate.put(GraphSONTokens.STRATEGY, pair.getValue0().toString());
intermediate.put(GraphSONTokens.CATEGORY, pair.getValue0().getTraversalCategory().getSimpleName());
intermediate.put(GraphSONTokens.TRAVERSAL, getStepsAsList(pair.getValue1()));
intermediates.add(intermediate);
}
m.put(GraphSONTokens.INTERMEDIATE, intermediates);
if (strategyTraversals.isEmpty())
m.put(GraphSONTokens.FINAL, getStepsAsList(traversalExplanation.getOriginalTraversal()));
else
m.put(GraphSONTokens.FINAL, getStepsAsList(strategyTraversals.get(strategyTraversals.size() - 1).getValue1()));
jsonGenerator.writeObject(m);
}
private List<String> getStepsAsList(final Traversal.Admin<?, ?> t) {
final List<String> steps = new ArrayList<>();
t.getSteps().iterator().forEachRemaining(s -> steps.add(s.toString()));
return steps;
}
}
final static class IntegerGraphSONSerializer extends StdScalarSerializer<Integer> {
public IntegerGraphSONSerializer() {
super(Integer.class);
}
@Override
public void serialize(final Integer integer, final JsonGenerator jsonGenerator,
final SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeNumber(((Integer) integer).intValue());
}
}
final static class DoubleGraphSONSerializer extends StdScalarSerializer<Double> {
public DoubleGraphSONSerializer() {
super(Double.class);
}
@Override
public void serialize(final Double doubleValue, final JsonGenerator jsonGenerator,
final SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeNumber(doubleValue);
}
}
final static class TraversalMetricsJacksonSerializer extends StdScalarSerializer<TraversalMetrics> {
public TraversalMetricsJacksonSerializer() {
super(TraversalMetrics.class);
}
@Override
public void serialize(final TraversalMetrics traversalMetrics, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider)
throws IOException {
// creation of the map enables all the fields to be properly written with their type if required
final Map<String, Object> m = new HashMap<>();
m.put(GraphSONTokens.DURATION, traversalMetrics.getDuration(TimeUnit.NANOSECONDS) / 1000000d);
final List<Metrics> metrics = new ArrayList<>();
metrics.addAll(traversalMetrics.getMetrics());
m.put(GraphSONTokens.METRICS, metrics);
jsonGenerator.writeObject(m);
}
}
final static class MetricsJacksonSerializer extends StdScalarSerializer<Metrics> {
public MetricsJacksonSerializer() {
super(Metrics.class);
}
@Override
public void serialize(final Metrics metrics, final JsonGenerator jsonGenerator,
final SerializerProvider serializerProvider) throws IOException {
final Map<String, Object> m = new HashMap<>();
m.put(GraphSONTokens.ID, metrics.getId());
m.put(GraphSONTokens.NAME, metrics.getName());
m.put(GraphSONTokens.COUNTS, metrics.getCounts());
m.put(GraphSONTokens.DURATION, metrics.getDuration(TimeUnit.NANOSECONDS) / 1000000d);
if (!metrics.getAnnotations().isEmpty()) {
m.put(GraphSONTokens.ANNOTATIONS, metrics.getAnnotations());
}
if (!metrics.getNested().isEmpty()) {
final List<Metrics> nested = new ArrayList<>();
metrics.getNested().forEach(it -> nested.add(it));
m.put(GraphSONTokens.METRICS, nested);
}
jsonGenerator.writeObject(m);
}
}
/**
* Maps in the JVM can have {@link Object} as a key, but in JSON they must be a {@link String}.
*/
final static class GraphSONKeySerializer extends StdKeySerializer {
@Override
public void serialize(final Object o, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) throws IOException {
ser(o, jsonGenerator, serializerProvider);
}
@Override
public void serializeWithType(final Object o, final JsonGenerator jsonGenerator,
final SerializerProvider serializerProvider, final TypeSerializer typeSerializer) throws IOException {
ser(o, jsonGenerator, serializerProvider);
}
private void ser(final Object o, final JsonGenerator jsonGenerator,
final SerializerProvider serializerProvider) throws IOException {
if (Element.class.isAssignableFrom(o.getClass()))
jsonGenerator.writeFieldName((((Element) o).id()).toString());
else
super.serialize(o, jsonGenerator, serializerProvider);
}
}
//////////////////////////// DESERIALIZERS ///////////////////////////
static class VertexJacksonDeserializer extends StdDeserializer<Vertex> {
public VertexJacksonDeserializer() {
super(Vertex.class);
}
public Vertex deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
final DetachedVertex.Builder v = DetachedVertex.build();
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
if (jsonParser.getCurrentName().equals(GraphSONTokens.ID)) {
jsonParser.nextToken();
v.setId(deserializationContext.readValue(jsonParser, Object.class));
} else if (jsonParser.getCurrentName().equals(GraphSONTokens.LABEL)) {
jsonParser.nextToken();
v.setLabel(jsonParser.getText());
} else if (jsonParser.getCurrentName().equals(GraphSONTokens.PROPERTIES)) {
jsonParser.nextToken();
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
jsonParser.nextToken();
while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
v.addProperty((DetachedVertexProperty) deserializationContext.readValue(jsonParser, VertexProperty.class));
}
}
}
}
return v.create();
}
@Override
public boolean isCachable() {
return true;
}
}
static class EdgeJacksonDeserializer extends StdDeserializer<Edge> {
public EdgeJacksonDeserializer() {
super(Edge.class);
}
@Override
public Edge deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
final DetachedEdge.Builder e = DetachedEdge.build();
final DetachedVertex.Builder inV = DetachedVertex.build();
final DetachedVertex.Builder outV = DetachedVertex.build();
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
if (jsonParser.getCurrentName().equals(GraphSONTokens.ID)) {
jsonParser.nextToken();
e.setId(deserializationContext.readValue(jsonParser, Object.class));
} else if (jsonParser.getCurrentName().equals(GraphSONTokens.LABEL)) {
jsonParser.nextToken();
e.setLabel(jsonParser.getText());
} else if (jsonParser.getCurrentName().equals(GraphSONTokens.OUT)) {
jsonParser.nextToken();
outV.setId(deserializationContext.readValue(jsonParser, Object.class));
} else if (jsonParser.getCurrentName().equals(GraphSONTokens.OUT_LABEL)) {
jsonParser.nextToken();
outV.setLabel(jsonParser.getText());
} else if (jsonParser.getCurrentName().equals(GraphSONTokens.IN)) {
jsonParser.nextToken();
inV.setId(deserializationContext.readValue(jsonParser, Object.class));
} else if (jsonParser.getCurrentName().equals(GraphSONTokens.IN_LABEL)) {
jsonParser.nextToken();
inV.setLabel(jsonParser.getText());
} else if (jsonParser.getCurrentName().equals(GraphSONTokens.PROPERTIES)) {
jsonParser.nextToken();
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
jsonParser.nextToken();
e.addProperty(deserializationContext.readValue(jsonParser, Property.class));
}
}
}
e.setInV(inV.create());
e.setOutV(outV.create());
return e.create();
}
@Override
public boolean isCachable() {
return true;
}
}
static class PropertyJacksonDeserializer extends StdDeserializer<Property> {
public PropertyJacksonDeserializer() {
super(Property.class);
}
@Override
public Property deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
String key = null;
Object value = null;
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
if (jsonParser.getCurrentName().equals(GraphSONTokens.KEY)) {
jsonParser.nextToken();
key = jsonParser.getText();
} else if (jsonParser.getCurrentName().equals(GraphSONTokens.VALUE)) {
jsonParser.nextToken();
value = deserializationContext.readValue(jsonParser, Object.class);
}
}
return new DetachedProperty<>(key, value);
}
@Override
public boolean isCachable() {
return true;
}
}
static class PathJacksonDeserializer extends StdDeserializer<Path> {
private static final JavaType setType = TypeFactory.defaultInstance().constructCollectionType(HashSet.class, String.class);
public PathJacksonDeserializer() {
super(Path.class);
}
@Override
public Path deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
final Path p = MutablePath.make();
List<Object> labels = new ArrayList<>();
List<Object> objects = new ArrayList<>();
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
if (jsonParser.getCurrentName().equals(GraphSONTokens.LABELS)) {
jsonParser.nextToken();
labels = deserializationContext.readValue(jsonParser, List.class);
} else if (jsonParser.getCurrentName().equals(GraphSONTokens.OBJECTS)) {
jsonParser.nextToken();
objects = deserializationContext.readValue(jsonParser, List.class);
}
}
for (int i = 0; i < objects.size(); i++) {
p.extend(objects.get(i), (Set<String>) labels.get(i));
}
return p;
}
@Override
public boolean isCachable() {
return true;
}
}
static class VertexPropertyJacksonDeserializer extends StdDeserializer<VertexProperty> {
private static final JavaType propertiesType = TypeFactory.defaultInstance().constructMapType(HashMap.class, String.class, Object.class);
protected VertexPropertyJacksonDeserializer() {
super(VertexProperty.class);
}
@Override
public VertexProperty deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
final DetachedVertexProperty.Builder vp = DetachedVertexProperty.build();
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
if (jsonParser.getCurrentName().equals(GraphSONTokens.ID)) {
jsonParser.nextToken();
vp.setId(deserializationContext.readValue(jsonParser, Object.class));
} else if (jsonParser.getCurrentName().equals(GraphSONTokens.LABEL)) {
jsonParser.nextToken();
vp.setLabel(jsonParser.getText());
} else if (jsonParser.getCurrentName().equals(GraphSONTokens.VALUE)) {
jsonParser.nextToken();
vp.setValue(deserializationContext.readValue(jsonParser, Object.class));
} else if (jsonParser.getCurrentName().equals(GraphSONTokens.PROPERTIES)) {
jsonParser.nextToken();
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
final String key = jsonParser.getCurrentName();
jsonParser.nextToken();
final Object val = deserializationContext.readValue(jsonParser, Object.class);
vp.addProperty(new DetachedProperty(key, val));
}
}
}
return vp.create();
}
@Override
public boolean isCachable() {
return true;
}
}
static class TraversalExplanationJacksonDeserializer extends StdDeserializer<TraversalExplanation> {
public TraversalExplanationJacksonDeserializer() {
super(TraversalExplanation.class);
}
@Override
public TraversalExplanation deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
final Map<String, Object> explainData = deserializationContext.readValue(jsonParser, Map.class);
final String originalTraversal = explainData.get(GraphSONTokens.ORIGINAL).toString();
final List<Triplet<String, String, String>> intermediates = new ArrayList<>();
final List<Map<String,Object>> listMap = (List<Map<String,Object>>) explainData.get(GraphSONTokens.INTERMEDIATE);
for (Map<String,Object> m : listMap) {
intermediates.add(Triplet.with(m.get(GraphSONTokens.STRATEGY).toString(),
m.get(GraphSONTokens.CATEGORY).toString(),
m.get(GraphSONTokens.TRAVERSAL).toString()));
}
return new ImmutableExplanation(originalTraversal, intermediates);
}
@Override
public boolean isCachable() {
return true;
}
}
static class MetricsJacksonDeserializer extends StdDeserializer<Metrics> {
public MetricsJacksonDeserializer() {
super(Metrics.class);
}
@Override
public Metrics deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
final Map<String, Object> metricsData = deserializationContext.readValue(jsonParser, Map.class);
final MutableMetrics m = new MutableMetrics((String)metricsData.get(GraphSONTokens.ID), (String)metricsData.get(GraphSONTokens.NAME));
m.setDuration(Math.round((Double) metricsData.get(GraphSONTokens.DURATION) * 1000000), TimeUnit.NANOSECONDS);
for (Map.Entry<String, Long> count : ((Map<String, Long>)metricsData.getOrDefault(GraphSONTokens.COUNTS, new LinkedHashMap<>(0))).entrySet()) {
m.setCount(count.getKey(), count.getValue());
}
for (Map.Entry<String, Long> count : ((Map<String, Long>) metricsData.getOrDefault(GraphSONTokens.ANNOTATIONS, new LinkedHashMap<>(0))).entrySet()) {
m.setAnnotation(count.getKey(), count.getValue());
}
for (MutableMetrics nested : (List<MutableMetrics>)metricsData.getOrDefault(GraphSONTokens.METRICS, new ArrayList<>(0))) {
m.addNested(nested);
}
return m;
}
@Override
public boolean isCachable() {
return true;
}
}
static class TraversalMetricsJacksonDeserializer extends StdDeserializer<TraversalMetrics> {
public TraversalMetricsJacksonDeserializer() {
super(TraversalMetrics.class);
}
@Override
public TraversalMetrics deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
final Map<String, Object> traversalMetricsData = deserializationContext.readValue(jsonParser, Map.class);
return new DefaultTraversalMetrics(
Math.round((Double) traversalMetricsData.get(GraphSONTokens.DURATION) * 1000000),
(List<MutableMetrics>) traversalMetricsData.get(GraphSONTokens.METRICS)
);
}
@Override
public boolean isCachable() {
return true;
}
}
static class TreeJacksonDeserializer extends StdDeserializer<Tree> {
public TreeJacksonDeserializer() {
super(Tree.class);
}
@Override
public Tree deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
final List<Map> data = deserializationContext.readValue(jsonParser, List.class);
final Tree t = new Tree();
for (Map<String, Object> entry : data) {
t.put(entry.get(GraphSONTokens.KEY), entry.get(GraphSONTokens.VALUE));
}
return t;
}
@Override
public boolean isCachable() {
return true;
}
}
static class IntegerJackonsDeserializer extends StdDeserializer<Integer> {
protected IntegerJackonsDeserializer() {
super(Integer.class);
}
@Override
public Integer deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
return jsonParser.getIntValue();
}
@Override
public boolean isCachable() {
return true;
}
}
static class DoubleJacksonDeserializer extends StdDeserializer<Double> {
protected DoubleJacksonDeserializer() {
super(Double.class);
}
@Override
public Double deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
if (jsonParser.getCurrentToken().isNumeric())
return jsonParser.getDoubleValue();
else {
final String numberText = jsonParser.getValueAsString();
if ("NaN".equalsIgnoreCase(numberText))
return Double.NaN;
else if ("-Infinity".equals(numberText) || "-INF".equalsIgnoreCase(numberText))
return Double.NEGATIVE_INFINITY;
else if ("Infinity".equals(numberText) || "INF".equals(numberText))
return Double.POSITIVE_INFINITY;
else
throw new IllegalStateException("Double value unexpected: " + numberText);
}
}
@Override
public boolean isCachable() {
return true;
}
}
/**
* When doing untyped serialization graph objects get a special "type" field appended.
*/
private static void writeTypeForGraphObjectIfUntyped(final JsonGenerator jsonGenerator, final TypeInfo typeInfo,
final String type) throws IOException {
if (typeInfo == TypeInfo.NO_TYPES) {
jsonGenerator.writeStringField(GraphSONTokens.TYPE, type);
}
}
} |
googleapis/google-cloud-java | 36,374 | java-apigee-registry/proto-google-cloud-apigee-registry-v1/src/main/java/com/google/cloud/apigeeregistry/v1/ListArtifactsRequest.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/apigeeregistry/v1/registry_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.apigeeregistry.v1;
/**
*
*
* <pre>
* Request message for ListArtifacts.
* </pre>
*
* Protobuf type {@code google.cloud.apigeeregistry.v1.ListArtifactsRequest}
*/
public final class ListArtifactsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.apigeeregistry.v1.ListArtifactsRequest)
ListArtifactsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListArtifactsRequest.newBuilder() to construct.
private ListArtifactsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListArtifactsRequest() {
parent_ = "";
pageToken_ = "";
filter_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListArtifactsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.apigeeregistry.v1.RegistryServiceProto
.internal_static_google_cloud_apigeeregistry_v1_ListArtifactsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.apigeeregistry.v1.RegistryServiceProto
.internal_static_google_cloud_apigeeregistry_v1_ListArtifactsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.apigeeregistry.v1.ListArtifactsRequest.class,
com.google.cloud.apigeeregistry.v1.ListArtifactsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent, which owns this collection of artifacts.
* Format: `{parent}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The parent, which owns this collection of artifacts.
* Format: `{parent}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* The maximum number of artifacts to return.
* The service may return fewer than this value.
* If unspecified, at most 50 values will be returned.
* The maximum is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A page token, received from a previous `ListArtifacts` call.
* Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to `ListArtifacts` must
* match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A page token, received from a previous `ListArtifacts` call.
* Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to `ListArtifacts` must
* match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* An expression that can be used to filter the list. Filters use the Common
* Expression Language and can refer to all message fields except contents.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* An expression that can be used to filter the list. Filters use the Common
* Expression Language and can refer to all message fields except contents.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.apigeeregistry.v1.ListArtifactsRequest)) {
return super.equals(obj);
}
com.google.cloud.apigeeregistry.v1.ListArtifactsRequest other =
(com.google.cloud.apigeeregistry.v1.ListArtifactsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.apigeeregistry.v1.ListArtifactsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apigeeregistry.v1.ListArtifactsRequest 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.apigeeregistry.v1.ListArtifactsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apigeeregistry.v1.ListArtifactsRequest 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.apigeeregistry.v1.ListArtifactsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.apigeeregistry.v1.ListArtifactsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.apigeeregistry.v1.ListArtifactsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.apigeeregistry.v1.ListArtifactsRequest 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.apigeeregistry.v1.ListArtifactsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.apigeeregistry.v1.ListArtifactsRequest 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.apigeeregistry.v1.ListArtifactsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.apigeeregistry.v1.ListArtifactsRequest 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.apigeeregistry.v1.ListArtifactsRequest 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 ListArtifacts.
* </pre>
*
* Protobuf type {@code google.cloud.apigeeregistry.v1.ListArtifactsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.apigeeregistry.v1.ListArtifactsRequest)
com.google.cloud.apigeeregistry.v1.ListArtifactsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.apigeeregistry.v1.RegistryServiceProto
.internal_static_google_cloud_apigeeregistry_v1_ListArtifactsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.apigeeregistry.v1.RegistryServiceProto
.internal_static_google_cloud_apigeeregistry_v1_ListArtifactsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.apigeeregistry.v1.ListArtifactsRequest.class,
com.google.cloud.apigeeregistry.v1.ListArtifactsRequest.Builder.class);
}
// Construct using com.google.cloud.apigeeregistry.v1.ListArtifactsRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
filter_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.apigeeregistry.v1.RegistryServiceProto
.internal_static_google_cloud_apigeeregistry_v1_ListArtifactsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.apigeeregistry.v1.ListArtifactsRequest getDefaultInstanceForType() {
return com.google.cloud.apigeeregistry.v1.ListArtifactsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.apigeeregistry.v1.ListArtifactsRequest build() {
com.google.cloud.apigeeregistry.v1.ListArtifactsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.apigeeregistry.v1.ListArtifactsRequest buildPartial() {
com.google.cloud.apigeeregistry.v1.ListArtifactsRequest result =
new com.google.cloud.apigeeregistry.v1.ListArtifactsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.apigeeregistry.v1.ListArtifactsRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.filter_ = filter_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.apigeeregistry.v1.ListArtifactsRequest) {
return mergeFrom((com.google.cloud.apigeeregistry.v1.ListArtifactsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.apigeeregistry.v1.ListArtifactsRequest other) {
if (other == com.google.cloud.apigeeregistry.v1.ListArtifactsRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000008;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent, which owns this collection of artifacts.
* Format: `{parent}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The parent, which owns this collection of artifacts.
* Format: `{parent}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The parent, which owns this collection of artifacts.
* Format: `{parent}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The parent, which owns this collection of artifacts.
* Format: `{parent}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The parent, which owns this collection of artifacts.
* Format: `{parent}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* The maximum number of artifacts to return.
* The service may return fewer than this value.
* If unspecified, at most 50 values will be returned.
* The maximum is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* The maximum number of artifacts to return.
* The service may return fewer than this value.
* If unspecified, at most 50 values will be returned.
* The maximum is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The maximum number of artifacts to return.
* The service may return fewer than this value.
* If unspecified, at most 50 values will be returned.
* The maximum is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A page token, received from a previous `ListArtifacts` call.
* Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to `ListArtifacts` must
* match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A page token, received from a previous `ListArtifacts` call.
* Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to `ListArtifacts` must
* match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A page token, received from a previous `ListArtifacts` call.
* Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to `ListArtifacts` must
* match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* A page token, received from a previous `ListArtifacts` call.
* Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to `ListArtifacts` must
* match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* A page token, received from a previous `ListArtifacts` call.
* Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to `ListArtifacts` must
* match the call that provided the page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* An expression that can be used to filter the list. Filters use the Common
* Expression Language and can refer to all message fields except contents.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* An expression that can be used to filter the list. Filters use the Common
* Expression Language and can refer to all message fields except contents.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* An expression that can be used to filter the list. Filters use the Common
* Expression Language and can refer to all message fields except contents.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* An expression that can be used to filter the list. Filters use the Common
* Expression Language and can refer to all message fields except contents.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* An expression that can be used to filter the list. Filters use the Common
* Expression Language and can refer to all message fields except contents.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.apigeeregistry.v1.ListArtifactsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.apigeeregistry.v1.ListArtifactsRequest)
private static final com.google.cloud.apigeeregistry.v1.ListArtifactsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.apigeeregistry.v1.ListArtifactsRequest();
}
public static com.google.cloud.apigeeregistry.v1.ListArtifactsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListArtifactsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListArtifactsRequest>() {
@java.lang.Override
public ListArtifactsRequest 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<ListArtifactsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListArtifactsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.apigeeregistry.v1.ListArtifactsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
google/graphicsfuzz | 35,088 | ast/src/test/java/com/graphicsfuzz/common/tool/PrettyPrinterVisitorTest.java | /*
* Copyright 2018 The GraphicsFuzz Project 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
*
* 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.graphicsfuzz.common.tool;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.graphicsfuzz.common.ast.CompareAstsDuplicate;
import com.graphicsfuzz.common.ast.TranslationUnit;
import com.graphicsfuzz.common.glslversion.ShadingLanguageVersion;
import com.graphicsfuzz.common.util.GlslParserException;
import com.graphicsfuzz.common.util.ParseHelper;
import com.graphicsfuzz.common.util.ParseTimeoutException;
import com.graphicsfuzz.common.util.ShaderKind;
import com.graphicsfuzz.util.Constants;
import com.graphicsfuzz.util.ExecHelper;
import com.graphicsfuzz.util.ToolHelper;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class PrettyPrinterVisitorTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void testArraySizeExpression() throws Exception {
final String program = ""
+ "void main()\n"
+ "{\n"
+ " int a[3 + 4];\n"
+ "}\n";
assertEquals(program, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testLiteralUniformDefines() throws Exception {
final String shaderWithBindings = ""
+ "layout(set = 0, binding = 0) uniform buf0 { int _GLF_uniform_int_values[2]; };"
+ "layout(set = 0, binding = 1) uniform buf1 { uint _GLF_uniform_uint_values[1]; };"
+ "layout(set = 0, binding = 2) uniform buf2 { float _GLF_uniform_float_values[3]; };"
+ "layout(set = 0, binding = 3) uniform sampler2D tex;"
+ "void main() { "
+ "int a = _GLF_uniform_int_values[0];"
+ "int b = _GLF_uniform_int_values[1];"
+ "uint c = _GLF_uniform_uint_values[0];"
+ "float d = _GLF_uniform_float_values[0];"
+ "float e = _GLF_uniform_float_values[1];"
+ "float f = _GLF_uniform_float_values[2];"
+ "}";
final String shaderPrettyPrinted = ""
+ "#define _int_0 _GLF_uniform_int_values[0]\n"
+ "#define _int_2 _GLF_uniform_int_values[1]\n"
+ "#define _uint_72 _GLF_uniform_uint_values[0]\n"
+ "#define _float_0_0 _GLF_uniform_float_values[0]\n"
+ "#define _float_22_4 _GLF_uniform_float_values[1]\n"
+ "#define _float_11_3 _GLF_uniform_float_values[2]\n"
+ "\n"
+ "// Contents of _GLF_uniform_int_values: [0, 2]\n"
+ "layout(set = 0, binding = 0) uniform buf0 {\n"
+ " int _GLF_uniform_int_values[2];\n"
+ "};\n"
+ "// Contents of _GLF_uniform_uint_values: 72\n"
+ "layout(set = 0, binding = 1) uniform buf1 {\n"
+ " uint _GLF_uniform_uint_values[1];\n"
+ "};\n"
+ "// Contents of _GLF_uniform_float_values: [0.0, 22.4, 11.3]\n"
+ "layout(set = 0, binding = 2) uniform buf2 {\n"
+ " float _GLF_uniform_float_values[3];\n"
+ "};\n"
+ "layout(set = 0, binding = 3) uniform sampler2D tex;\n\n"
+ "void main()\n"
+ "{\n"
+ " int a = _int_0;\n"
+ " int b = _int_2;\n"
+ " uint c = _uint_72;\n"
+ " float d = _float_0_0;\n"
+ " float e = _float_22_4;\n"
+ " float f = _float_11_3;\n"
+ "}\n";
UniformValueSupplier uniformValues = name -> {
if (name.equals("_GLF_uniform_int_values")) {
return Optional.of(Arrays.asList("0", "2"));
} else if (name.equals("_GLF_uniform_float_values")) {
return Optional.of(Arrays.asList("0.0", "22.4", "11.3"));
} else if (name.equals("_GLF_uniform_uint_values")) {
return Optional.of(Arrays.asList("72"));
} else if (name.equals("tex")) {
throw new RuntimeException("The value of a sampler uniform should not be requested.");
}
return Optional.empty();
};
assertEquals(shaderPrettyPrinted,
PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(shaderWithBindings),
uniformValues));
}
@Test
public void testUniformBlockContentsInComments() throws Exception {
final String shaderWithBindings = ""
+ "layout(set = 0, binding = 0) uniform buf0 { int _GLF_uniform_int_values[2]; };"
+ "layout(set = 0, binding = 1) uniform buf1 { float _GLF_uniform_float_values[1]; };"
+ "void main() { }";
final String shaderPrettyPrinted = ""
+ "#define _int_0 _GLF_uniform_int_values[0]\n"
+ "#define _int_1 _GLF_uniform_int_values[1]\n"
+ "#define _float_3_0 _GLF_uniform_float_values[0]\n"
+ "\n"
+ "// Contents of _GLF_uniform_int_values: [0, 1]\n"
+ "layout(set = 0, binding = 0) uniform buf0 {\n"
+ " int _GLF_uniform_int_values[2];\n"
+ "};\n"
+ "// Contents of _GLF_uniform_float_values: 3.0\n"
+ "layout(set = 0, binding = 1) uniform buf1 {\n"
+ " float _GLF_uniform_float_values[1];\n"
+ "};\n"
+ "void main()\n"
+ "{\n"
+ "}\n";
UniformValueSupplier uniformValues = name -> {
if (name.equals("_GLF_uniform_int_values")) {
return Optional.of(Arrays.asList("0", "1"));
} else if (name.equals("_GLF_uniform_float_values")) {
return Optional.of(Collections.singletonList("3.0"));
}
return Optional.empty();
};
assertEquals(shaderPrettyPrinted,
PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(shaderWithBindings),
uniformValues));
}
@Test
public void testUniformArrayContentsInComments() throws Exception {
final String shader = ""
+ "uniform int a[3], b[2], X[1], Y[22], Z[1];"
+ "uniform float _GLF_uniform_float_values[3], D;"
+ "uniform uint _GLF_uniform_uint_values[2], E[33];"
+ "uniform int test[5], test2[1], A;"
+ "void main()"
+ "{"
+ " float a = _GLF_uniform_float_values[0];"
+ " float b = _GLF_uniform_float_values[1];"
+ " int c = _GLF_uniform_int_values[0];"
+ " int d = _GLF_uniform_int_values[1];"
+ " int e = _GLF_uniform_int_values[2];"
+ " int f = _GLF_uniform_uint_values[0];"
+ " int g = _GLF_uniform_uint_values[1];"
+ "}";
final String shaderPrettyPrinted = ""
+ "#define _uint_2 _GLF_uniform_uint_values[0]\n"
+ "#define _uint_11 _GLF_uniform_uint_values[1]\n"
+ "#define _uint_22 _GLF_uniform_uint_values[2]\n"
+ "#define _float_0_0 _GLF_uniform_float_values[0]\n"
+ "#define _float_1_4 _GLF_uniform_float_values[1]\n"
+ "#define _float_22_2 _GLF_uniform_float_values[2]\n"
+ "\n"
+ "// Contents of a: [0, 1, 2]\n"
+ "// Contents of b: [3, 4, 5]\n"
+ "// Contents of Z: 77\n"
+ "uniform int a[3], b[2], X[1], Y[22], Z[1];\n"
+ "\n"
+ "// Contents of _GLF_uniform_float_values: [0.0, 1.4, 22.2]\n"
+ "uniform float _GLF_uniform_float_values[3], D;\n"
+ "\n"
+ "// Contents of _GLF_uniform_uint_values: [2, 11, 22]\n"
+ "uniform uint _GLF_uniform_uint_values[2], E[33];\n"
+ "\n"
+ "// Contents of test2: 66\n"
+ "uniform int test[5], test2[1], A;\n"
+ "\n"
+ "void main()\n"
+ "{\n"
+ " float a = _float_0_0;\n"
+ " float b = _float_1_4;\n"
+ " int c = _GLF_uniform_int_values[0];\n"
+ " int d = _GLF_uniform_int_values[1];\n"
+ " int e = _GLF_uniform_int_values[2];\n"
+ " int f = _uint_2;\n"
+ " int g = _uint_11;\n"
+ "}\n";
final List<TranslationUnit> shaders = new ArrayList<>();
shaders.add(ParseHelper.parse(shader, ShaderKind.FRAGMENT));
UniformValueSupplier uniformValues = name -> {
if (name.equals("a")) {
return Optional.of(Arrays.asList("0", "1", "2"));
} else if (name.equals("b")) {
return Optional.of(Arrays.asList("3", "4", "5"));
} else if (name.equals("_GLF_uniform_uint_values")) {
return Optional.of(Arrays.asList("2", "11", "22"));
} else if (name.equals("_GLF_uniform_float_values")) {
return Optional.of(Arrays.asList("0.0", "1.4", "22.2"));
} else if (name.equals("test2")) {
return Optional.of(Arrays.asList("66"));
} else if (name.equals("Z")) {
return Optional.of(Arrays.asList("77"));
}
return Optional.empty();
};
assertEquals(shaderPrettyPrinted,
PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(shader), uniformValues));
}
@Test
public void testArraySizeExpressionInParameter() throws Exception {
final String program = ""
+ "void foo(int A[3 + 4])\n"
+ "{\n"
+ "}\n"
+ "void main()\n"
+ "{\n"
+ " int a[7];\n"
+ " foo(a);\n"
+ "}\n";
assertEquals(program, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrint() throws Exception {
final String program = ""
+ "struct A {\n"
+ PrettyPrinterVisitor.defaultIndent(1) + "int x;\n"
+ "} ;\n\n"
+ "struct B {\n"
+ PrettyPrinterVisitor.defaultIndent(1) + "int y;\n"
+ "} ;\n\n"
+ "void main()\n"
+ "{\n"
+ "}\n";
assertEquals(program, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintSwitch() throws Exception {
final String program = ""
+ "void main()\n"
+ "{\n"
+ PrettyPrinterVisitor.defaultIndent(1) + "int x = 3;\n"
+ PrettyPrinterVisitor.defaultIndent(1) + "switch(x)\n"
+ PrettyPrinterVisitor.defaultIndent(2) + "{\n"
+ PrettyPrinterVisitor.defaultIndent(3) + "case 0:\n"
+ PrettyPrinterVisitor.defaultIndent(3) + "x ++;\n"
+ PrettyPrinterVisitor.defaultIndent(3) + "case 1:\n"
+ PrettyPrinterVisitor.defaultIndent(3) + "case 3:\n"
+ PrettyPrinterVisitor.defaultIndent(3) + "x ++;\n"
+ PrettyPrinterVisitor.defaultIndent(3) + "break;\n"
+ PrettyPrinterVisitor.defaultIndent(3) + "case 4:\n"
+ PrettyPrinterVisitor.defaultIndent(3) + "break;\n"
+ PrettyPrinterVisitor.defaultIndent(3) + "default:\n"
+ PrettyPrinterVisitor.defaultIndent(3) + "break;\n"
+ PrettyPrinterVisitor.defaultIndent(2) + "}\n"
+ "}\n";
TranslationUnit tu = ParseHelper.parse(program);
CompareAstsDuplicate.assertEqualAsts(tu, tu.clone());
}
@Test
public void testStruct() throws Exception {
final String program = "struct foo {\n"
+ PrettyPrinterVisitor.defaultIndent(1) + "int data[10];\n"
+ "} ;\n\n";
assertEquals(program, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test(expected = RuntimeException.class)
public void testStruct2() throws Exception {
// As we are not yet supporting 2D arrays, we expect a RuntimeException to be thrown.
// When we do support 2D arrays this test should pass without exception.
final String program = "struct foo {\n"
+ PrettyPrinterVisitor.defaultIndent(1) + "int data[10][20];\n"
+ "};\n";
assertEquals(program, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintQualifiers() throws Exception {
// const volatile is not useful here, but this is just to test that qualifier order is
// preserved.
final String program = ""
+ "const volatile float x;\n\n";
assertEquals(program, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintLayout() throws Exception {
// This test deliberately exposes that we presently do not dig into the inside of layout
// qualifiers. When we do, we will ditch this test and replace it with some tests that
// check we are handling the internals properly.
final String program = ""
+ "layout(location = 0) out vec4 color;\n\n"
+ "layout(anything=3, we, like=4, aswearenotyethandlingtheinternals) out vec2 blah;\n\n"
+ "void main()\n"
+ "{\n"
+ "}\n";
assertEquals(program, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintComputeShader() throws Exception {
final String program = ""
+ "layout(std430, binding = 2) buffer abuf {\n"
+ " int data[];\n"
+ "};\n"
+ "layout(local_size_x = 128, local_size_y = 1) in;\n"
+ "void main()\n"
+ "{\n"
+ " for(uint d = gl_WorkGroupSize.x / 2u; d > 0u; d >>= 1u)\n"
+ " {\n"
+ " if(gl_LocalInvocationID.x < d)\n"
+ " {\n"
+ " data[gl_LocalInvocationID.x] += data[d + gl_LocalInvocationID.x];\n"
+ " }\n"
+ " barrier();\n"
+ " }\n"
+ "}\n";
assertEquals(program, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintStructs() throws Exception {
// This checks exact layout, so will require maintenance if things change.
// This is expected and deliberate: do the maintenance :)
final String program = ""
+ "struct S {\n"
+ " int a;\n"
+ " int b;\n"
+ "} ;\n"
+ "\n"
+ "struct T {\n"
+ " S myS1;\n"
+ " S myS2;\n"
+ "} ;\n"
+ "\n"
+ "void main()\n"
+ "{\n"
+ " T myT = T(S(1, 2), S(3, 4));\n"
+ "}\n";
assertEquals(program, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintArrayParameter() throws Exception {
final String program = "void foo(int A[2])\n"
+ "{\n"
+ "}\n";
assertEquals(program, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintArrayVariable() throws Exception {
final String program = "void main()\n"
+ "{\n"
+ " int A[2] = int[2](1, 2);\n"
+ "}\n";
assertEquals(program, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintStructs2() throws Exception {
// This checks exact layout, so will require maintenance if things change.
// This is expected and deliberate: do the maintenance :)
final String program = ""
+ "struct S {\n"
+ " int a;\n"
+ " int b;\n"
+ "} ;\n"
+ "\n"
+ "S someS = S(8, 9);\n"
+ "\n"
+ "struct T {\n"
+ " S myS1;\n"
+ " S myS2;\n"
+ "} ;\n"
+ "\n"
+ "void main()\n"
+ "{\n"
+ " T myT = T(S(1, 2), S(3, 4));\n"
+ "}\n";
assertEquals(program, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintStructs3() throws Exception {
// This checks exact layout, so will require maintenance if things change.
// This is expected and deliberate: do the maintenance :)
final String program = ""
+ "struct S {\n"
+ " int a;\n"
+ " int b;\n"
+ "} someS = S(8, 9);\n"
+ "\n"
+ "struct T {\n"
+ " S myS1;\n"
+ " S myS2;\n"
+ "} ;\n"
+ "\n"
+ "void main()\n"
+ "{\n"
+ " T myT = T(S(1, 2), S(someS.a, 4));\n"
+ "}\n";
assertEquals(program, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintStructs4() throws Exception {
// This checks exact layout, so will require maintenance if things change.
// This is expected and deliberate: do the maintenance :)
final String program = ""
+ "struct {\n"
+ " int a;\n"
+ " int b;\n"
+ "} X, Y, Z;\n"
+ "\n"
+ "void main()\n"
+ "{\n"
+ " X.a = 3;\n"
+ " Y.b = X.a;\n"
+ "}\n";
assertEquals(program, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintVersion() throws Exception {
final String program = "#\tversion 100\nvoid main() { }\n";
final String expected = "#version 100\nvoid main()\n{\n}\n";
assertEquals(expected, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintVersionEs() throws Exception {
final String program = "#\tversion 320 es\nvoid main() { }\n";
final String expected = "#version 320 es\nvoid main()\n{\n}\n";
assertEquals(expected, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintExtension() throws Exception {
final String program = ""
+ "#\textension GL_EXT_gpu_shader5 : enable\nvoid main() { }";
final String expected = ""
+ "#extension GL_EXT_gpu_shader5 : enable\nvoid main()\n{\n}\n";
assertEquals(expected, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintPragmaOptimizeOn() throws Exception {
final String program = "#\tpragma optimize ( on )\nvoid main() { }\n";
final String expected = "#pragma optimize(on)\nvoid main()\n{\n}\n";
assertEquals(expected, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintPragmaOptimizeOff() throws Exception {
final String program = "#pragma optimize ( off )\nvoid main() { }\n";
final String expected = "#pragma optimize(off)\nvoid main()\n{\n}\n";
assertEquals(expected, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintPragmaDebugOn() throws Exception {
final String program = "#\tpragma debug ( on )\nvoid main() { }\n";
final String expected = "#pragma debug(on)\nvoid main()\n{\n}\n";
assertEquals(expected, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintPragmaDebugOff() throws Exception {
final String program = "#\tpragma debug ( off )\nvoid main() { }\n";
final String expected = "#pragma debug(off)\nvoid main()\n{\n}\n";
assertEquals(expected, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintPragmaInvariantAll() throws Exception {
final String program = "#\tpragma invariant ( all )\nvoid main() { }\n";
final String expected = "#pragma invariant(all)\nvoid main()\n{\n}\n";
assertEquals(expected, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testSamplers() throws Exception {
final String program =
"uniform sampler1D s1;\n\n"
+ "uniform sampler2D s2;\n\n"
+ "uniform sampler2DRect s3;\n\n"
+ "uniform sampler3D s4;\n\n"
+ "uniform samplerCube s5;\n\n"
+ "uniform sampler1DShadow s7;\n\n"
+ "uniform sampler2DShadow s8;\n\n"
+ "uniform sampler2DRectShadow s9;\n\n"
+ "uniform samplerCubeShadow s10;\n\n"
+ "uniform sampler1DArray s11;\n\n"
+ "uniform sampler2DArray s12;\n\n"
+ "uniform sampler1DArrayShadow s13;\n\n"
+ "uniform sampler2DArrayShadow s14;\n\n"
+ "uniform samplerBuffer s15;\n\n"
+ "uniform samplerCubeArray s16;\n\n"
+ "uniform samplerCubeArrayShadow s17;\n\n"
+ "uniform isampler1D s18;\n\n"
+ "uniform isampler2D s19;\n\n"
+ "uniform isampler2DRect s20;\n\n"
+ "uniform isampler3D s21;\n\n"
+ "uniform isamplerCube s22;\n\n"
+ "uniform isampler1DArray s23;\n\n"
+ "uniform isampler2DArray s24;\n\n"
+ "uniform isamplerBuffer s25;\n\n"
+ "uniform isamplerCubeArray s26;\n\n"
+ "uniform usampler1D s27;\n\n"
+ "uniform usampler2D s28;\n\n"
+ "uniform usampler2DRect s29;\n\n"
+ "uniform usampler3D s30;\n\n"
+ "uniform usamplerCube s31;\n\n"
+ "uniform usampler1DArray s32;\n\n"
+ "uniform usampler2DArray s33;\n\n"
+ "uniform usamplerBuffer s34;\n\n"
+ "uniform usamplerCubeArray s35;\n\n"
+ "uniform sampler2DMS s36;\n\n"
+ "uniform isampler2DMS s37;\n\n"
+ "uniform usampler2DMS s38;\n\n"
+ "uniform sampler2DMSArray s39;\n\n"
+ "uniform isampler2DMSArray s40;\n\n"
+ "uniform usampler2DMSArray s41;\n\n";
final File shaderFile = temporaryFolder.newFile("shader.frag");
FileUtils.writeStringToFile(shaderFile, "#version 410\n\n" + program, StandardCharsets.UTF_8);
assertEquals(0, ToolHelper.runValidatorOnShader(ExecHelper.RedirectType.TO_BUFFER,
shaderFile).res);
assertEquals(program, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
/**
* To allow testing of the 'emitShader' method, this parses a shader from the given string,
* invokes 'emitShader' on the resulting parsed shader, and returns the result as a string.
*/
private String getStringViaEmitShader(String shader)
throws IOException, ParseTimeoutException, InterruptedException, GlslParserException {
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
PrettyPrinterVisitor.emitShader(ParseHelper.parse(shader), Optional.empty(),
new PrintStream(bytes), PrettyPrinterVisitor.DEFAULT_INDENTATION_WIDTH,
PrettyPrinterVisitor.DEFAULT_NEWLINE_SUPPLIER);
return new String(bytes.toByteArray(), StandardCharsets.UTF_8);
}
@Test
public void testNoMacrosUsedSoNoGraphicsFuzzHeader() throws Exception {
assertFalse(getStringViaEmitShader("void main() { }")
.contains(ParseHelper.END_OF_GRAPHICSFUZZ_DEFINES));
}
@Test
public void testNoMacrosUsedSoNoGraphicsFuzzHeader2() throws Exception {
// Even though this uses a macro name, it doesn't use it as a function invocation.
assertFalse(getStringViaEmitShader("void main() { int " + Constants.GLF_FUZZED + "; }")
.contains(ParseHelper.END_OF_GRAPHICSFUZZ_DEFINES));
}
@Test
public void testGraphicsFuzzMacrosDueToIdentityMacro() throws Exception {
assertTrue(getStringViaEmitShader("void main() { " + Constants.GLF_IDENTITY + "(1, 1); }")
.contains(ParseHelper.END_OF_GRAPHICSFUZZ_DEFINES));
}
@Test
public void testGraphicsFuzzMacrosDueToZeroMacro() throws Exception {
assertTrue(getStringViaEmitShader("void main() { " + Constants.GLF_ZERO + "(0); }")
.contains(ParseHelper.END_OF_GRAPHICSFUZZ_DEFINES));
}
@Test
public void testGraphicsFuzzMacrosDueToOneMacro() throws Exception {
assertTrue(getStringViaEmitShader("void main() { " + Constants.GLF_ONE + "(1); }")
.contains(ParseHelper.END_OF_GRAPHICSFUZZ_DEFINES));
}
@Test
public void testGraphicsFuzzMacrosDueToFalseMacro() throws Exception {
assertTrue(getStringViaEmitShader("void main() { " + Constants.GLF_FALSE + "(false); }")
.contains(ParseHelper.END_OF_GRAPHICSFUZZ_DEFINES));
}
@Test
public void testGraphicsFuzzMacrosDueToTrueMacro() throws Exception {
assertTrue(getStringViaEmitShader("void main() { " + Constants.GLF_TRUE + "(true); }")
.contains(ParseHelper.END_OF_GRAPHICSFUZZ_DEFINES));
}
@Test
public void testGraphicsFuzzMacrosDueToFuzzedMacro() throws Exception {
assertTrue(getStringViaEmitShader("void main() { " + Constants.GLF_FUZZED + "(1234); }")
.contains(ParseHelper.END_OF_GRAPHICSFUZZ_DEFINES));
}
@Test
public void testGraphicsFuzzMacrosDueToDeadByConstructionMacro() throws Exception {
assertTrue(getStringViaEmitShader("void main() { if(" + Constants.GLF_DEAD + "(false)) { } "
+ "}").contains(ParseHelper.END_OF_GRAPHICSFUZZ_DEFINES));
}
@Test
public void testGraphicsFuzzMacrosDueToLoopWrapperMacro() throws Exception {
assertTrue(getStringViaEmitShader("void main() { while(" + Constants.GLF_WRAPPED_LOOP
+ "(false))"
+ " {"
+ " } "
+ "}").contains(ParseHelper.END_OF_GRAPHICSFUZZ_DEFINES));
}
@Test
public void testGraphicsFuzzMacrosDueToIfFalseWrapperMacro() throws Exception {
assertTrue(getStringViaEmitShader("void main() { if(" + Constants.GLF_WRAPPED_IF_FALSE
+ "(false)) { } "
+ "}").contains(ParseHelper.END_OF_GRAPHICSFUZZ_DEFINES));
}
@Test
public void testGraphicsFuzzMacrosDueToIfTrueWrapperMacro() throws Exception {
assertTrue(getStringViaEmitShader("void main() { if(" + Constants.GLF_WRAPPED_IF_TRUE
+ "(true)) { } "
+ "}").contains(ParseHelper.END_OF_GRAPHICSFUZZ_DEFINES));
}
@Test
public void testGraphicsFuzzMacrosDueToSwitchMacro() throws Exception {
assertTrue(getStringViaEmitShader("void main() { switch(" + Constants.GLF_SWITCH
+ "(0)) { case 0: break; default: break; } "
+ "}").contains(ParseHelper.END_OF_GRAPHICSFUZZ_DEFINES));
}
@Test
public void testParseAndPrintVoidFormalParameter() throws Exception {
// For simplicity, we deliberately chuck away "void" in function formal parameters; this test
// captures that intent.
final String program = ""
+ "int foo(void)\n"
+ "{\n"
+ " return 2;\n"
+ "}\n"
+ "void main(void)\n"
+ "{\n"
+ "}\n";
final String expected = ""
+ "int foo()\n"
+ "{\n"
+ " return 2;\n"
+ "}\n"
+ "void main()\n"
+ "{\n"
+ "}\n";
assertEquals(expected, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintVoidActualParameter() throws Exception {
// For simplicity, we deliberately chuck away "void" in function actual parameters; this test
// captures that intent.
final String program = ""
+ "void foo()\n"
+ "{\n"
+ " return 2;\n"
+ "}\n"
+ "void main()\n"
+ "{\n"
+ " foo(void);\n"
+ "}\n";
final String expected = ""
+ "void foo()\n"
+ "{\n"
+ " return 2;\n"
+ "}\n"
+ "void main()\n"
+ "{\n"
+ " foo();\n"
+ "}\n";
assertEquals(expected, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintLoopWithDeclarationsInside() throws Exception {
final String program = ""
+ "void main()\n"
+ "{\n"
+ " for(int i = 0; i < 10; i ++)\n"
+ " {\n"
+ " int a;\n"
+ " int b;\n"
+ " }\n"
+ "}\n";
assertEquals(program, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void testParseAndPrintNestedLoop() throws Exception {
final String program = ""
+ "void main()\n"
+ "{\n"
+ " for(int i = 0; i < 10; i ++)\n"
+ " {\n"
+ " for(int i = 0; i < 10; i ++)\n"
+ " {\n"
+ " int a;\n"
+ " int b;\n"
+ " }\n"
+ " }\n"
+ "}\n";
assertEquals(program, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(program
)));
}
@Test
public void addBracesParameterTest() throws Exception {
final String frag =
"void main(void)\n"
+ "{\n"
+ " if (condition)\n"
+ " do_something();\n"
+ "}\n";
final String expected =
"void main(void)\n"
+ "{\n"
+ " if (condition) {\n"
+ " do_something();\n"
+ " }\n"
+ "}\n";
final File fragFile = temporaryFolder.newFile("shader.frag");
final File outFile = temporaryFolder.newFile("out.frag");
FileUtils.writeStringToFile(fragFile, frag, StandardCharsets.UTF_8);
PrettyPrint.main(new String[] {
fragFile.getAbsolutePath(),
outFile.getAbsolutePath(),
"--add-braces" });
final String prettiedFrag = FileUtils.readFileToString(outFile, StandardCharsets.UTF_8);
CompareAstsDuplicate.assertEqualAsts(prettiedFrag, expected);
}
@Test
public void multiDimensionalArraysTest() throws Exception {
final String shader =
"#version 320 es\n"
+ "const int N = 2;\n"
+ "\n"
+ "const int M = 3;\n"
+ "\n"
+ "void foo(int p[4][4][3])\n"
+ "{\n"
+ " int temp[2][M] = int[N][3](int[3](1, 2, 3), p[0][0]);\n"
+ " temp[0] = int[3](1, 2, 3);\n"
+ "}\n";
assertEquals(shader, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(shader)));
}
@Test
public void testEmitGraphicsFuzzDefines() throws Exception {
final String expected = "\n"
+ "#ifndef REDUCER\n"
+ "#define _GLF_ZERO(X, Y) (Y)\n"
+ "#define _GLF_ONE(X, Y) (Y)\n"
+ "#define _GLF_FALSE(X, Y) (Y)\n"
+ "#define _GLF_TRUE(X, Y) (Y)\n"
+ "#define _GLF_IDENTITY(X, Y) (Y)\n"
+ "#define _GLF_DEAD(X) (X)\n"
+ "#define _GLF_FUZZED(X) (X)\n"
+ "#define _GLF_WRAPPED_LOOP(X) X\n"
+ "#define _GLF_WRAPPED_IF_TRUE(X) X\n"
+ "#define _GLF_WRAPPED_IF_FALSE(X) X\n"
+ "#define _GLF_SWITCH(X) X\n"
+ "#define _GLF_MAKE_IN_BOUNDS_INT(IDX, SZ) ((IDX) < 0 ? 0 "
+ ": ((IDX) >= SZ ? SZ - 1 : (IDX)))\n"
+ "#define _GLF_MAKE_IN_BOUNDS_UINT(IDX, SZ) ((IDX) >= SZ ? SZ - 1u : (IDX))\n"
+ "#endif\n"
+ "\n"
+ "// END OF GENERATED HEADER\n";
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(bytes);
PrettyPrinterVisitor.emitGraphicsFuzzDefines(printStream, ShadingLanguageVersion.ESSL_100);
assertEquals(expected, new String(bytes.toByteArray(), StandardCharsets.UTF_8));
}
@Test
public void ifThenElseInShortIf() throws Exception {
final String shader =
"#version 320 es\n"
+ "void foo()\n"
+ "{\n"
+ " if(true)\n"
+ " if(true)\n"
+ " ;\n"
+ " else\n"
+ " ;\n"
+ " else\n"
+ " ;\n"
+ "}\n";
assertEquals(shader, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(shader)));
}
@Test
public void whileInShortIf() throws Exception {
final String shader =
"#version 320 es\n"
+ "void foo()\n"
+ "{\n"
+ " if(true)\n"
+ " while(true)\n"
+ " if(true)\n"
+ " ;\n"
+ " else\n"
+ " ;\n"
+ " else\n"
+ " ;\n"
+ "}\n";
assertEquals(shader, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(shader)));
}
@Test
public void forInShortIf() throws Exception {
final String shader =
"#version 320 es\n"
+ "void foo()\n"
+ "{\n"
+ " if(true)\n"
+ " for( ;\n"
+ " ; )\n"
+ " if(true)\n"
+ " ;\n"
+ " else\n"
+ " ;\n"
+ " else\n"
+ " ;\n"
+ "}\n";
assertEquals(shader, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(shader)));
}
@Test
public void length() throws Exception {
final String shader =
"#version 320 es\n"
+ "void main()\n"
+ "{\n"
+ " int A[5];\n"
+ " int x = A.length();\n"
+ "}\n";
assertEquals(shader, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(shader)));
}
@Test
public void coherentSsbo() throws Exception {
final String shader =
"#version 320 es\n"
+ "layout(std430, binding = 0) buffer coherent buffer_0 {\n"
+ " int a;\n"
+ "};\n";
assertEquals(shader, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(shader)));
}
@Test
public void volatileSsbo() throws Exception {
final String shader =
"#version 320 es\n"
+ "layout(std430, binding = 0) volatile buffer buffer_0 {\n"
+ " int a;\n"
+ "};\n";
assertEquals(shader, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(shader)));
}
@Test
public void restrictSsbo() throws Exception {
final String shader =
"#version 320 es\n"
+ "layout(std430, binding = 0) restrict buffer buffer_0 {\n"
+ " int a;\n"
+ "};\n";
assertEquals(shader, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(shader)));
}
@Test
public void readonlySsbo() throws Exception {
final String shader =
"#version 320 es\n"
+ "layout(std430, binding = 0) buffer readonly buffer_0 {\n"
+ " int a;\n"
+ "};\n";
assertEquals(shader, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(shader)));
}
@Test
public void writeonlySsbo() throws Exception {
final String shader =
"#version 320 es\n"
+ "layout(std430, binding = 0) writeonly buffer buffer_0 {\n"
+ " int a;\n"
+ "};\n";
assertEquals(shader, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(shader)));
}
@Test
public void ssboMultipleQualifiers() throws Exception {
final String shader =
"#version 320 es\n"
+ "layout(std430, binding = 0) volatile buffer restrict writeonly buffer_0 {\n"
+ " int a;\n"
+ "};\n";
assertEquals(shader, PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(shader)));
}
}
|
googleapis/google-cloud-java | 36,429 | java-deploy/proto-google-cloud-deploy-v1/src/main/java/com/google/cloud/deploy/v1/RuntimeConfig.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/deploy/v1/cloud_deploy.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.deploy.v1;
/**
*
*
* <pre>
* RuntimeConfig contains the runtime specific configurations for a deployment
* strategy.
* </pre>
*
* Protobuf type {@code google.cloud.deploy.v1.RuntimeConfig}
*/
public final class RuntimeConfig extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.deploy.v1.RuntimeConfig)
RuntimeConfigOrBuilder {
private static final long serialVersionUID = 0L;
// Use RuntimeConfig.newBuilder() to construct.
private RuntimeConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private RuntimeConfig() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new RuntimeConfig();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.deploy.v1.CloudDeployProto
.internal_static_google_cloud_deploy_v1_RuntimeConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.deploy.v1.CloudDeployProto
.internal_static_google_cloud_deploy_v1_RuntimeConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.deploy.v1.RuntimeConfig.class,
com.google.cloud.deploy.v1.RuntimeConfig.Builder.class);
}
private int runtimeConfigCase_ = 0;
@SuppressWarnings("serial")
private java.lang.Object runtimeConfig_;
public enum RuntimeConfigCase
implements
com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
KUBERNETES(1),
CLOUD_RUN(2),
RUNTIMECONFIG_NOT_SET(0);
private final int value;
private RuntimeConfigCase(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 RuntimeConfigCase valueOf(int value) {
return forNumber(value);
}
public static RuntimeConfigCase forNumber(int value) {
switch (value) {
case 1:
return KUBERNETES;
case 2:
return CLOUD_RUN;
case 0:
return RUNTIMECONFIG_NOT_SET;
default:
return null;
}
}
public int getNumber() {
return this.value;
}
};
public RuntimeConfigCase getRuntimeConfigCase() {
return RuntimeConfigCase.forNumber(runtimeConfigCase_);
}
public static final int KUBERNETES_FIELD_NUMBER = 1;
/**
*
*
* <pre>
* Optional. Kubernetes runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.KubernetesConfig kubernetes = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the kubernetes field is set.
*/
@java.lang.Override
public boolean hasKubernetes() {
return runtimeConfigCase_ == 1;
}
/**
*
*
* <pre>
* Optional. Kubernetes runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.KubernetesConfig kubernetes = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The kubernetes.
*/
@java.lang.Override
public com.google.cloud.deploy.v1.KubernetesConfig getKubernetes() {
if (runtimeConfigCase_ == 1) {
return (com.google.cloud.deploy.v1.KubernetesConfig) runtimeConfig_;
}
return com.google.cloud.deploy.v1.KubernetesConfig.getDefaultInstance();
}
/**
*
*
* <pre>
* Optional. Kubernetes runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.KubernetesConfig kubernetes = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
@java.lang.Override
public com.google.cloud.deploy.v1.KubernetesConfigOrBuilder getKubernetesOrBuilder() {
if (runtimeConfigCase_ == 1) {
return (com.google.cloud.deploy.v1.KubernetesConfig) runtimeConfig_;
}
return com.google.cloud.deploy.v1.KubernetesConfig.getDefaultInstance();
}
public static final int CLOUD_RUN_FIELD_NUMBER = 2;
/**
*
*
* <pre>
* Optional. Cloud Run runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.CloudRunConfig cloud_run = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the cloudRun field is set.
*/
@java.lang.Override
public boolean hasCloudRun() {
return runtimeConfigCase_ == 2;
}
/**
*
*
* <pre>
* Optional. Cloud Run runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.CloudRunConfig cloud_run = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The cloudRun.
*/
@java.lang.Override
public com.google.cloud.deploy.v1.CloudRunConfig getCloudRun() {
if (runtimeConfigCase_ == 2) {
return (com.google.cloud.deploy.v1.CloudRunConfig) runtimeConfig_;
}
return com.google.cloud.deploy.v1.CloudRunConfig.getDefaultInstance();
}
/**
*
*
* <pre>
* Optional. Cloud Run runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.CloudRunConfig cloud_run = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
@java.lang.Override
public com.google.cloud.deploy.v1.CloudRunConfigOrBuilder getCloudRunOrBuilder() {
if (runtimeConfigCase_ == 2) {
return (com.google.cloud.deploy.v1.CloudRunConfig) runtimeConfig_;
}
return com.google.cloud.deploy.v1.CloudRunConfig.getDefaultInstance();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (runtimeConfigCase_ == 1) {
output.writeMessage(1, (com.google.cloud.deploy.v1.KubernetesConfig) runtimeConfig_);
}
if (runtimeConfigCase_ == 2) {
output.writeMessage(2, (com.google.cloud.deploy.v1.CloudRunConfig) runtimeConfig_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (runtimeConfigCase_ == 1) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
1, (com.google.cloud.deploy.v1.KubernetesConfig) runtimeConfig_);
}
if (runtimeConfigCase_ == 2) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
2, (com.google.cloud.deploy.v1.CloudRunConfig) runtimeConfig_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.deploy.v1.RuntimeConfig)) {
return super.equals(obj);
}
com.google.cloud.deploy.v1.RuntimeConfig other = (com.google.cloud.deploy.v1.RuntimeConfig) obj;
if (!getRuntimeConfigCase().equals(other.getRuntimeConfigCase())) return false;
switch (runtimeConfigCase_) {
case 1:
if (!getKubernetes().equals(other.getKubernetes())) return false;
break;
case 2:
if (!getCloudRun().equals(other.getCloudRun())) 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 (runtimeConfigCase_) {
case 1:
hash = (37 * hash) + KUBERNETES_FIELD_NUMBER;
hash = (53 * hash) + getKubernetes().hashCode();
break;
case 2:
hash = (37 * hash) + CLOUD_RUN_FIELD_NUMBER;
hash = (53 * hash) + getCloudRun().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.deploy.v1.RuntimeConfig parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.deploy.v1.RuntimeConfig parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.deploy.v1.RuntimeConfig parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.deploy.v1.RuntimeConfig parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.deploy.v1.RuntimeConfig parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.deploy.v1.RuntimeConfig parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.deploy.v1.RuntimeConfig parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.deploy.v1.RuntimeConfig parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.deploy.v1.RuntimeConfig parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.deploy.v1.RuntimeConfig parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.deploy.v1.RuntimeConfig parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.deploy.v1.RuntimeConfig parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.deploy.v1.RuntimeConfig 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>
* RuntimeConfig contains the runtime specific configurations for a deployment
* strategy.
* </pre>
*
* Protobuf type {@code google.cloud.deploy.v1.RuntimeConfig}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.deploy.v1.RuntimeConfig)
com.google.cloud.deploy.v1.RuntimeConfigOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.deploy.v1.CloudDeployProto
.internal_static_google_cloud_deploy_v1_RuntimeConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.deploy.v1.CloudDeployProto
.internal_static_google_cloud_deploy_v1_RuntimeConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.deploy.v1.RuntimeConfig.class,
com.google.cloud.deploy.v1.RuntimeConfig.Builder.class);
}
// Construct using com.google.cloud.deploy.v1.RuntimeConfig.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (kubernetesBuilder_ != null) {
kubernetesBuilder_.clear();
}
if (cloudRunBuilder_ != null) {
cloudRunBuilder_.clear();
}
runtimeConfigCase_ = 0;
runtimeConfig_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.deploy.v1.CloudDeployProto
.internal_static_google_cloud_deploy_v1_RuntimeConfig_descriptor;
}
@java.lang.Override
public com.google.cloud.deploy.v1.RuntimeConfig getDefaultInstanceForType() {
return com.google.cloud.deploy.v1.RuntimeConfig.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.deploy.v1.RuntimeConfig build() {
com.google.cloud.deploy.v1.RuntimeConfig result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.deploy.v1.RuntimeConfig buildPartial() {
com.google.cloud.deploy.v1.RuntimeConfig result =
new com.google.cloud.deploy.v1.RuntimeConfig(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
buildPartialOneofs(result);
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.deploy.v1.RuntimeConfig result) {
int from_bitField0_ = bitField0_;
}
private void buildPartialOneofs(com.google.cloud.deploy.v1.RuntimeConfig result) {
result.runtimeConfigCase_ = runtimeConfigCase_;
result.runtimeConfig_ = this.runtimeConfig_;
if (runtimeConfigCase_ == 1 && kubernetesBuilder_ != null) {
result.runtimeConfig_ = kubernetesBuilder_.build();
}
if (runtimeConfigCase_ == 2 && cloudRunBuilder_ != null) {
result.runtimeConfig_ = cloudRunBuilder_.build();
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.deploy.v1.RuntimeConfig) {
return mergeFrom((com.google.cloud.deploy.v1.RuntimeConfig) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.deploy.v1.RuntimeConfig other) {
if (other == com.google.cloud.deploy.v1.RuntimeConfig.getDefaultInstance()) return this;
switch (other.getRuntimeConfigCase()) {
case KUBERNETES:
{
mergeKubernetes(other.getKubernetes());
break;
}
case CLOUD_RUN:
{
mergeCloudRun(other.getCloudRun());
break;
}
case RUNTIMECONFIG_NOT_SET:
{
break;
}
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(getKubernetesFieldBuilder().getBuilder(), extensionRegistry);
runtimeConfigCase_ = 1;
break;
} // case 10
case 18:
{
input.readMessage(getCloudRunFieldBuilder().getBuilder(), extensionRegistry);
runtimeConfigCase_ = 2;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int runtimeConfigCase_ = 0;
private java.lang.Object runtimeConfig_;
public RuntimeConfigCase getRuntimeConfigCase() {
return RuntimeConfigCase.forNumber(runtimeConfigCase_);
}
public Builder clearRuntimeConfig() {
runtimeConfigCase_ = 0;
runtimeConfig_ = null;
onChanged();
return this;
}
private int bitField0_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.deploy.v1.KubernetesConfig,
com.google.cloud.deploy.v1.KubernetesConfig.Builder,
com.google.cloud.deploy.v1.KubernetesConfigOrBuilder>
kubernetesBuilder_;
/**
*
*
* <pre>
* Optional. Kubernetes runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.KubernetesConfig kubernetes = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the kubernetes field is set.
*/
@java.lang.Override
public boolean hasKubernetes() {
return runtimeConfigCase_ == 1;
}
/**
*
*
* <pre>
* Optional. Kubernetes runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.KubernetesConfig kubernetes = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The kubernetes.
*/
@java.lang.Override
public com.google.cloud.deploy.v1.KubernetesConfig getKubernetes() {
if (kubernetesBuilder_ == null) {
if (runtimeConfigCase_ == 1) {
return (com.google.cloud.deploy.v1.KubernetesConfig) runtimeConfig_;
}
return com.google.cloud.deploy.v1.KubernetesConfig.getDefaultInstance();
} else {
if (runtimeConfigCase_ == 1) {
return kubernetesBuilder_.getMessage();
}
return com.google.cloud.deploy.v1.KubernetesConfig.getDefaultInstance();
}
}
/**
*
*
* <pre>
* Optional. Kubernetes runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.KubernetesConfig kubernetes = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setKubernetes(com.google.cloud.deploy.v1.KubernetesConfig value) {
if (kubernetesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
runtimeConfig_ = value;
onChanged();
} else {
kubernetesBuilder_.setMessage(value);
}
runtimeConfigCase_ = 1;
return this;
}
/**
*
*
* <pre>
* Optional. Kubernetes runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.KubernetesConfig kubernetes = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setKubernetes(
com.google.cloud.deploy.v1.KubernetesConfig.Builder builderForValue) {
if (kubernetesBuilder_ == null) {
runtimeConfig_ = builderForValue.build();
onChanged();
} else {
kubernetesBuilder_.setMessage(builderForValue.build());
}
runtimeConfigCase_ = 1;
return this;
}
/**
*
*
* <pre>
* Optional. Kubernetes runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.KubernetesConfig kubernetes = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder mergeKubernetes(com.google.cloud.deploy.v1.KubernetesConfig value) {
if (kubernetesBuilder_ == null) {
if (runtimeConfigCase_ == 1
&& runtimeConfig_ != com.google.cloud.deploy.v1.KubernetesConfig.getDefaultInstance()) {
runtimeConfig_ =
com.google.cloud.deploy.v1.KubernetesConfig.newBuilder(
(com.google.cloud.deploy.v1.KubernetesConfig) runtimeConfig_)
.mergeFrom(value)
.buildPartial();
} else {
runtimeConfig_ = value;
}
onChanged();
} else {
if (runtimeConfigCase_ == 1) {
kubernetesBuilder_.mergeFrom(value);
} else {
kubernetesBuilder_.setMessage(value);
}
}
runtimeConfigCase_ = 1;
return this;
}
/**
*
*
* <pre>
* Optional. Kubernetes runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.KubernetesConfig kubernetes = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder clearKubernetes() {
if (kubernetesBuilder_ == null) {
if (runtimeConfigCase_ == 1) {
runtimeConfigCase_ = 0;
runtimeConfig_ = null;
onChanged();
}
} else {
if (runtimeConfigCase_ == 1) {
runtimeConfigCase_ = 0;
runtimeConfig_ = null;
}
kubernetesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Optional. Kubernetes runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.KubernetesConfig kubernetes = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.cloud.deploy.v1.KubernetesConfig.Builder getKubernetesBuilder() {
return getKubernetesFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Optional. Kubernetes runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.KubernetesConfig kubernetes = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
@java.lang.Override
public com.google.cloud.deploy.v1.KubernetesConfigOrBuilder getKubernetesOrBuilder() {
if ((runtimeConfigCase_ == 1) && (kubernetesBuilder_ != null)) {
return kubernetesBuilder_.getMessageOrBuilder();
} else {
if (runtimeConfigCase_ == 1) {
return (com.google.cloud.deploy.v1.KubernetesConfig) runtimeConfig_;
}
return com.google.cloud.deploy.v1.KubernetesConfig.getDefaultInstance();
}
}
/**
*
*
* <pre>
* Optional. Kubernetes runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.KubernetesConfig kubernetes = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.deploy.v1.KubernetesConfig,
com.google.cloud.deploy.v1.KubernetesConfig.Builder,
com.google.cloud.deploy.v1.KubernetesConfigOrBuilder>
getKubernetesFieldBuilder() {
if (kubernetesBuilder_ == null) {
if (!(runtimeConfigCase_ == 1)) {
runtimeConfig_ = com.google.cloud.deploy.v1.KubernetesConfig.getDefaultInstance();
}
kubernetesBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.deploy.v1.KubernetesConfig,
com.google.cloud.deploy.v1.KubernetesConfig.Builder,
com.google.cloud.deploy.v1.KubernetesConfigOrBuilder>(
(com.google.cloud.deploy.v1.KubernetesConfig) runtimeConfig_,
getParentForChildren(),
isClean());
runtimeConfig_ = null;
}
runtimeConfigCase_ = 1;
onChanged();
return kubernetesBuilder_;
}
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.deploy.v1.CloudRunConfig,
com.google.cloud.deploy.v1.CloudRunConfig.Builder,
com.google.cloud.deploy.v1.CloudRunConfigOrBuilder>
cloudRunBuilder_;
/**
*
*
* <pre>
* Optional. Cloud Run runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.CloudRunConfig cloud_run = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the cloudRun field is set.
*/
@java.lang.Override
public boolean hasCloudRun() {
return runtimeConfigCase_ == 2;
}
/**
*
*
* <pre>
* Optional. Cloud Run runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.CloudRunConfig cloud_run = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The cloudRun.
*/
@java.lang.Override
public com.google.cloud.deploy.v1.CloudRunConfig getCloudRun() {
if (cloudRunBuilder_ == null) {
if (runtimeConfigCase_ == 2) {
return (com.google.cloud.deploy.v1.CloudRunConfig) runtimeConfig_;
}
return com.google.cloud.deploy.v1.CloudRunConfig.getDefaultInstance();
} else {
if (runtimeConfigCase_ == 2) {
return cloudRunBuilder_.getMessage();
}
return com.google.cloud.deploy.v1.CloudRunConfig.getDefaultInstance();
}
}
/**
*
*
* <pre>
* Optional. Cloud Run runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.CloudRunConfig cloud_run = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setCloudRun(com.google.cloud.deploy.v1.CloudRunConfig value) {
if (cloudRunBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
runtimeConfig_ = value;
onChanged();
} else {
cloudRunBuilder_.setMessage(value);
}
runtimeConfigCase_ = 2;
return this;
}
/**
*
*
* <pre>
* Optional. Cloud Run runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.CloudRunConfig cloud_run = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setCloudRun(com.google.cloud.deploy.v1.CloudRunConfig.Builder builderForValue) {
if (cloudRunBuilder_ == null) {
runtimeConfig_ = builderForValue.build();
onChanged();
} else {
cloudRunBuilder_.setMessage(builderForValue.build());
}
runtimeConfigCase_ = 2;
return this;
}
/**
*
*
* <pre>
* Optional. Cloud Run runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.CloudRunConfig cloud_run = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder mergeCloudRun(com.google.cloud.deploy.v1.CloudRunConfig value) {
if (cloudRunBuilder_ == null) {
if (runtimeConfigCase_ == 2
&& runtimeConfig_ != com.google.cloud.deploy.v1.CloudRunConfig.getDefaultInstance()) {
runtimeConfig_ =
com.google.cloud.deploy.v1.CloudRunConfig.newBuilder(
(com.google.cloud.deploy.v1.CloudRunConfig) runtimeConfig_)
.mergeFrom(value)
.buildPartial();
} else {
runtimeConfig_ = value;
}
onChanged();
} else {
if (runtimeConfigCase_ == 2) {
cloudRunBuilder_.mergeFrom(value);
} else {
cloudRunBuilder_.setMessage(value);
}
}
runtimeConfigCase_ = 2;
return this;
}
/**
*
*
* <pre>
* Optional. Cloud Run runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.CloudRunConfig cloud_run = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder clearCloudRun() {
if (cloudRunBuilder_ == null) {
if (runtimeConfigCase_ == 2) {
runtimeConfigCase_ = 0;
runtimeConfig_ = null;
onChanged();
}
} else {
if (runtimeConfigCase_ == 2) {
runtimeConfigCase_ = 0;
runtimeConfig_ = null;
}
cloudRunBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Optional. Cloud Run runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.CloudRunConfig cloud_run = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.cloud.deploy.v1.CloudRunConfig.Builder getCloudRunBuilder() {
return getCloudRunFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Optional. Cloud Run runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.CloudRunConfig cloud_run = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
@java.lang.Override
public com.google.cloud.deploy.v1.CloudRunConfigOrBuilder getCloudRunOrBuilder() {
if ((runtimeConfigCase_ == 2) && (cloudRunBuilder_ != null)) {
return cloudRunBuilder_.getMessageOrBuilder();
} else {
if (runtimeConfigCase_ == 2) {
return (com.google.cloud.deploy.v1.CloudRunConfig) runtimeConfig_;
}
return com.google.cloud.deploy.v1.CloudRunConfig.getDefaultInstance();
}
}
/**
*
*
* <pre>
* Optional. Cloud Run runtime configuration.
* </pre>
*
* <code>
* .google.cloud.deploy.v1.CloudRunConfig cloud_run = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.deploy.v1.CloudRunConfig,
com.google.cloud.deploy.v1.CloudRunConfig.Builder,
com.google.cloud.deploy.v1.CloudRunConfigOrBuilder>
getCloudRunFieldBuilder() {
if (cloudRunBuilder_ == null) {
if (!(runtimeConfigCase_ == 2)) {
runtimeConfig_ = com.google.cloud.deploy.v1.CloudRunConfig.getDefaultInstance();
}
cloudRunBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.deploy.v1.CloudRunConfig,
com.google.cloud.deploy.v1.CloudRunConfig.Builder,
com.google.cloud.deploy.v1.CloudRunConfigOrBuilder>(
(com.google.cloud.deploy.v1.CloudRunConfig) runtimeConfig_,
getParentForChildren(),
isClean());
runtimeConfig_ = null;
}
runtimeConfigCase_ = 2;
onChanged();
return cloudRunBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.deploy.v1.RuntimeConfig)
}
// @@protoc_insertion_point(class_scope:google.cloud.deploy.v1.RuntimeConfig)
private static final com.google.cloud.deploy.v1.RuntimeConfig DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.deploy.v1.RuntimeConfig();
}
public static com.google.cloud.deploy.v1.RuntimeConfig getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<RuntimeConfig> PARSER =
new com.google.protobuf.AbstractParser<RuntimeConfig>() {
@java.lang.Override
public RuntimeConfig 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<RuntimeConfig> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<RuntimeConfig> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.deploy.v1.RuntimeConfig getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,544 | java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/ExternalVpnGatewayInterface.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>
* The interface for the external VPN gateway.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.ExternalVpnGatewayInterface}
*/
public final class ExternalVpnGatewayInterface extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.ExternalVpnGatewayInterface)
ExternalVpnGatewayInterfaceOrBuilder {
private static final long serialVersionUID = 0L;
// Use ExternalVpnGatewayInterface.newBuilder() to construct.
private ExternalVpnGatewayInterface(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ExternalVpnGatewayInterface() {
ipAddress_ = "";
ipv6Address_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ExternalVpnGatewayInterface();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_ExternalVpnGatewayInterface_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_ExternalVpnGatewayInterface_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.ExternalVpnGatewayInterface.class,
com.google.cloud.compute.v1.ExternalVpnGatewayInterface.Builder.class);
}
private int bitField0_;
public static final int ID_FIELD_NUMBER = 3355;
private int id_ = 0;
/**
*
*
* <pre>
* The numeric ID of this interface. The allowed input values for this id for different redundancy types of external VPN gateway: - SINGLE_IP_INTERNALLY_REDUNDANT - 0 - TWO_IPS_REDUNDANCY - 0, 1 - FOUR_IPS_REDUNDANCY - 0, 1, 2, 3
* </pre>
*
* <code>optional uint32 id = 3355;</code>
*
* @return Whether the id field is set.
*/
@java.lang.Override
public boolean hasId() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The numeric ID of this interface. The allowed input values for this id for different redundancy types of external VPN gateway: - SINGLE_IP_INTERNALLY_REDUNDANT - 0 - TWO_IPS_REDUNDANCY - 0, 1 - FOUR_IPS_REDUNDANCY - 0, 1, 2, 3
* </pre>
*
* <code>optional uint32 id = 3355;</code>
*
* @return The id.
*/
@java.lang.Override
public int getId() {
return id_;
}
public static final int IP_ADDRESS_FIELD_NUMBER = 406272220;
@SuppressWarnings("serial")
private volatile java.lang.Object ipAddress_ = "";
/**
*
*
* <pre>
* IP address of the interface in the external VPN gateway. Only IPv4 is supported. This IP address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine.
* </pre>
*
* <code>optional string ip_address = 406272220;</code>
*
* @return Whether the ipAddress field is set.
*/
@java.lang.Override
public boolean hasIpAddress() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* IP address of the interface in the external VPN gateway. Only IPv4 is supported. This IP address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine.
* </pre>
*
* <code>optional string ip_address = 406272220;</code>
*
* @return The ipAddress.
*/
@java.lang.Override
public java.lang.String getIpAddress() {
java.lang.Object ref = ipAddress_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
ipAddress_ = s;
return s;
}
}
/**
*
*
* <pre>
* IP address of the interface in the external VPN gateway. Only IPv4 is supported. This IP address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine.
* </pre>
*
* <code>optional string ip_address = 406272220;</code>
*
* @return The bytes for ipAddress.
*/
@java.lang.Override
public com.google.protobuf.ByteString getIpAddressBytes() {
java.lang.Object ref = ipAddress_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
ipAddress_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int IPV6_ADDRESS_FIELD_NUMBER = 341563804;
@SuppressWarnings("serial")
private volatile java.lang.Object ipv6Address_ = "";
/**
*
*
* <pre>
* IPv6 address of the interface in the external VPN gateway. This IPv6 address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine. Must specify an IPv6 address (not IPV4-mapped) using any format described in RFC 4291 (e.g. 2001:db8:0:0:2d9:51:0:0). The output format is RFC 5952 format (e.g. 2001:db8::2d9:51:0:0).
* </pre>
*
* <code>optional string ipv6_address = 341563804;</code>
*
* @return Whether the ipv6Address field is set.
*/
@java.lang.Override
public boolean hasIpv6Address() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* IPv6 address of the interface in the external VPN gateway. This IPv6 address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine. Must specify an IPv6 address (not IPV4-mapped) using any format described in RFC 4291 (e.g. 2001:db8:0:0:2d9:51:0:0). The output format is RFC 5952 format (e.g. 2001:db8::2d9:51:0:0).
* </pre>
*
* <code>optional string ipv6_address = 341563804;</code>
*
* @return The ipv6Address.
*/
@java.lang.Override
public java.lang.String getIpv6Address() {
java.lang.Object ref = ipv6Address_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
ipv6Address_ = s;
return s;
}
}
/**
*
*
* <pre>
* IPv6 address of the interface in the external VPN gateway. This IPv6 address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine. Must specify an IPv6 address (not IPV4-mapped) using any format described in RFC 4291 (e.g. 2001:db8:0:0:2d9:51:0:0). The output format is RFC 5952 format (e.g. 2001:db8::2d9:51:0:0).
* </pre>
*
* <code>optional string ipv6_address = 341563804;</code>
*
* @return The bytes for ipv6Address.
*/
@java.lang.Override
public com.google.protobuf.ByteString getIpv6AddressBytes() {
java.lang.Object ref = ipv6Address_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
ipv6Address_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeUInt32(3355, id_);
}
if (((bitField0_ & 0x00000004) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 341563804, ipv6Address_);
}
if (((bitField0_ & 0x00000002) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 406272220, ipAddress_);
}
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.computeUInt32Size(3355, id_);
}
if (((bitField0_ & 0x00000004) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(341563804, ipv6Address_);
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(406272220, ipAddress_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.compute.v1.ExternalVpnGatewayInterface)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.ExternalVpnGatewayInterface other =
(com.google.cloud.compute.v1.ExternalVpnGatewayInterface) obj;
if (hasId() != other.hasId()) return false;
if (hasId()) {
if (getId() != other.getId()) return false;
}
if (hasIpAddress() != other.hasIpAddress()) return false;
if (hasIpAddress()) {
if (!getIpAddress().equals(other.getIpAddress())) return false;
}
if (hasIpv6Address() != other.hasIpv6Address()) return false;
if (hasIpv6Address()) {
if (!getIpv6Address().equals(other.getIpv6Address())) 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 (hasId()) {
hash = (37 * hash) + ID_FIELD_NUMBER;
hash = (53 * hash) + getId();
}
if (hasIpAddress()) {
hash = (37 * hash) + IP_ADDRESS_FIELD_NUMBER;
hash = (53 * hash) + getIpAddress().hashCode();
}
if (hasIpv6Address()) {
hash = (37 * hash) + IPV6_ADDRESS_FIELD_NUMBER;
hash = (53 * hash) + getIpv6Address().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1.ExternalVpnGatewayInterface parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.ExternalVpnGatewayInterface 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.ExternalVpnGatewayInterface parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.ExternalVpnGatewayInterface 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.ExternalVpnGatewayInterface parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.ExternalVpnGatewayInterface 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.ExternalVpnGatewayInterface parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.ExternalVpnGatewayInterface 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.ExternalVpnGatewayInterface parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.ExternalVpnGatewayInterface 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.ExternalVpnGatewayInterface 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.ExternalVpnGatewayInterface 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.ExternalVpnGatewayInterface 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 interface for the external VPN gateway.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.ExternalVpnGatewayInterface}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.ExternalVpnGatewayInterface)
com.google.cloud.compute.v1.ExternalVpnGatewayInterfaceOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_ExternalVpnGatewayInterface_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_ExternalVpnGatewayInterface_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.ExternalVpnGatewayInterface.class,
com.google.cloud.compute.v1.ExternalVpnGatewayInterface.Builder.class);
}
// Construct using com.google.cloud.compute.v1.ExternalVpnGatewayInterface.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
id_ = 0;
ipAddress_ = "";
ipv6Address_ = "";
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_ExternalVpnGatewayInterface_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.ExternalVpnGatewayInterface getDefaultInstanceForType() {
return com.google.cloud.compute.v1.ExternalVpnGatewayInterface.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.ExternalVpnGatewayInterface build() {
com.google.cloud.compute.v1.ExternalVpnGatewayInterface result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.ExternalVpnGatewayInterface buildPartial() {
com.google.cloud.compute.v1.ExternalVpnGatewayInterface result =
new com.google.cloud.compute.v1.ExternalVpnGatewayInterface(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.compute.v1.ExternalVpnGatewayInterface result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.id_ = id_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.ipAddress_ = ipAddress_;
to_bitField0_ |= 0x00000002;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.ipv6Address_ = ipv6Address_;
to_bitField0_ |= 0x00000004;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.compute.v1.ExternalVpnGatewayInterface) {
return mergeFrom((com.google.cloud.compute.v1.ExternalVpnGatewayInterface) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.compute.v1.ExternalVpnGatewayInterface other) {
if (other == com.google.cloud.compute.v1.ExternalVpnGatewayInterface.getDefaultInstance())
return this;
if (other.hasId()) {
setId(other.getId());
}
if (other.hasIpAddress()) {
ipAddress_ = other.ipAddress_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasIpv6Address()) {
ipv6Address_ = other.ipv6Address_;
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 26840:
{
id_ = input.readUInt32();
bitField0_ |= 0x00000001;
break;
} // case 26840
case -1562456862:
{
ipv6Address_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case -1562456862
case -1044789534:
{
ipAddress_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case -1044789534
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 id_;
/**
*
*
* <pre>
* The numeric ID of this interface. The allowed input values for this id for different redundancy types of external VPN gateway: - SINGLE_IP_INTERNALLY_REDUNDANT - 0 - TWO_IPS_REDUNDANCY - 0, 1 - FOUR_IPS_REDUNDANCY - 0, 1, 2, 3
* </pre>
*
* <code>optional uint32 id = 3355;</code>
*
* @return Whether the id field is set.
*/
@java.lang.Override
public boolean hasId() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The numeric ID of this interface. The allowed input values for this id for different redundancy types of external VPN gateway: - SINGLE_IP_INTERNALLY_REDUNDANT - 0 - TWO_IPS_REDUNDANCY - 0, 1 - FOUR_IPS_REDUNDANCY - 0, 1, 2, 3
* </pre>
*
* <code>optional uint32 id = 3355;</code>
*
* @return The id.
*/
@java.lang.Override
public int getId() {
return id_;
}
/**
*
*
* <pre>
* The numeric ID of this interface. The allowed input values for this id for different redundancy types of external VPN gateway: - SINGLE_IP_INTERNALLY_REDUNDANT - 0 - TWO_IPS_REDUNDANCY - 0, 1 - FOUR_IPS_REDUNDANCY - 0, 1, 2, 3
* </pre>
*
* <code>optional uint32 id = 3355;</code>
*
* @param value The id to set.
* @return This builder for chaining.
*/
public Builder setId(int value) {
id_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The numeric ID of this interface. The allowed input values for this id for different redundancy types of external VPN gateway: - SINGLE_IP_INTERNALLY_REDUNDANT - 0 - TWO_IPS_REDUNDANCY - 0, 1 - FOUR_IPS_REDUNDANCY - 0, 1, 2, 3
* </pre>
*
* <code>optional uint32 id = 3355;</code>
*
* @return This builder for chaining.
*/
public Builder clearId() {
bitField0_ = (bitField0_ & ~0x00000001);
id_ = 0;
onChanged();
return this;
}
private java.lang.Object ipAddress_ = "";
/**
*
*
* <pre>
* IP address of the interface in the external VPN gateway. Only IPv4 is supported. This IP address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine.
* </pre>
*
* <code>optional string ip_address = 406272220;</code>
*
* @return Whether the ipAddress field is set.
*/
public boolean hasIpAddress() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* IP address of the interface in the external VPN gateway. Only IPv4 is supported. This IP address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine.
* </pre>
*
* <code>optional string ip_address = 406272220;</code>
*
* @return The ipAddress.
*/
public java.lang.String getIpAddress() {
java.lang.Object ref = ipAddress_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
ipAddress_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* IP address of the interface in the external VPN gateway. Only IPv4 is supported. This IP address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine.
* </pre>
*
* <code>optional string ip_address = 406272220;</code>
*
* @return The bytes for ipAddress.
*/
public com.google.protobuf.ByteString getIpAddressBytes() {
java.lang.Object ref = ipAddress_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
ipAddress_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* IP address of the interface in the external VPN gateway. Only IPv4 is supported. This IP address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine.
* </pre>
*
* <code>optional string ip_address = 406272220;</code>
*
* @param value The ipAddress to set.
* @return This builder for chaining.
*/
public Builder setIpAddress(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ipAddress_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* IP address of the interface in the external VPN gateway. Only IPv4 is supported. This IP address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine.
* </pre>
*
* <code>optional string ip_address = 406272220;</code>
*
* @return This builder for chaining.
*/
public Builder clearIpAddress() {
ipAddress_ = getDefaultInstance().getIpAddress();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* IP address of the interface in the external VPN gateway. Only IPv4 is supported. This IP address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine.
* </pre>
*
* <code>optional string ip_address = 406272220;</code>
*
* @param value The bytes for ipAddress to set.
* @return This builder for chaining.
*/
public Builder setIpAddressBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ipAddress_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object ipv6Address_ = "";
/**
*
*
* <pre>
* IPv6 address of the interface in the external VPN gateway. This IPv6 address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine. Must specify an IPv6 address (not IPV4-mapped) using any format described in RFC 4291 (e.g. 2001:db8:0:0:2d9:51:0:0). The output format is RFC 5952 format (e.g. 2001:db8::2d9:51:0:0).
* </pre>
*
* <code>optional string ipv6_address = 341563804;</code>
*
* @return Whether the ipv6Address field is set.
*/
public boolean hasIpv6Address() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* IPv6 address of the interface in the external VPN gateway. This IPv6 address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine. Must specify an IPv6 address (not IPV4-mapped) using any format described in RFC 4291 (e.g. 2001:db8:0:0:2d9:51:0:0). The output format is RFC 5952 format (e.g. 2001:db8::2d9:51:0:0).
* </pre>
*
* <code>optional string ipv6_address = 341563804;</code>
*
* @return The ipv6Address.
*/
public java.lang.String getIpv6Address() {
java.lang.Object ref = ipv6Address_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
ipv6Address_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* IPv6 address of the interface in the external VPN gateway. This IPv6 address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine. Must specify an IPv6 address (not IPV4-mapped) using any format described in RFC 4291 (e.g. 2001:db8:0:0:2d9:51:0:0). The output format is RFC 5952 format (e.g. 2001:db8::2d9:51:0:0).
* </pre>
*
* <code>optional string ipv6_address = 341563804;</code>
*
* @return The bytes for ipv6Address.
*/
public com.google.protobuf.ByteString getIpv6AddressBytes() {
java.lang.Object ref = ipv6Address_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
ipv6Address_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* IPv6 address of the interface in the external VPN gateway. This IPv6 address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine. Must specify an IPv6 address (not IPV4-mapped) using any format described in RFC 4291 (e.g. 2001:db8:0:0:2d9:51:0:0). The output format is RFC 5952 format (e.g. 2001:db8::2d9:51:0:0).
* </pre>
*
* <code>optional string ipv6_address = 341563804;</code>
*
* @param value The ipv6Address to set.
* @return This builder for chaining.
*/
public Builder setIpv6Address(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ipv6Address_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* IPv6 address of the interface in the external VPN gateway. This IPv6 address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine. Must specify an IPv6 address (not IPV4-mapped) using any format described in RFC 4291 (e.g. 2001:db8:0:0:2d9:51:0:0). The output format is RFC 5952 format (e.g. 2001:db8::2d9:51:0:0).
* </pre>
*
* <code>optional string ipv6_address = 341563804;</code>
*
* @return This builder for chaining.
*/
public Builder clearIpv6Address() {
ipv6Address_ = getDefaultInstance().getIpv6Address();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* IPv6 address of the interface in the external VPN gateway. This IPv6 address can be either from your on-premise gateway or another Cloud provider's VPN gateway, it cannot be an IP address from Google Compute Engine. Must specify an IPv6 address (not IPV4-mapped) using any format described in RFC 4291 (e.g. 2001:db8:0:0:2d9:51:0:0). The output format is RFC 5952 format (e.g. 2001:db8::2d9:51:0:0).
* </pre>
*
* <code>optional string ipv6_address = 341563804;</code>
*
* @param value The bytes for ipv6Address to set.
* @return This builder for chaining.
*/
public Builder setIpv6AddressBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ipv6Address_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.ExternalVpnGatewayInterface)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.ExternalVpnGatewayInterface)
private static final com.google.cloud.compute.v1.ExternalVpnGatewayInterface DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.compute.v1.ExternalVpnGatewayInterface();
}
public static com.google.cloud.compute.v1.ExternalVpnGatewayInterface getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ExternalVpnGatewayInterface> PARSER =
new com.google.protobuf.AbstractParser<ExternalVpnGatewayInterface>() {
@java.lang.Override
public ExternalVpnGatewayInterface 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<ExternalVpnGatewayInterface> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ExternalVpnGatewayInterface> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.ExternalVpnGatewayInterface getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/xmlgraphics-batik | 36,631 | batik-bridge/src/main/java/org/apache/batik/bridge/svg12/SVGFlowRootElementBridge.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.batik.bridge.svg12;
import java.awt.Color;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.font.TextAttribute;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.Map;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.apache.batik.anim.dom.SVGOMElement;
import org.apache.batik.anim.dom.SVGOMFlowRegionElement;
import org.apache.batik.anim.dom.XBLEventSupport;
import org.apache.batik.bridge.Bridge;
import org.apache.batik.bridge.BridgeContext;
import org.apache.batik.bridge.CSSUtilities;
import org.apache.batik.bridge.CursorManager;
import org.apache.batik.bridge.FlowTextNode;
import org.apache.batik.bridge.GVTBuilder;
import org.apache.batik.bridge.SVGTextElementBridge;
import org.apache.batik.bridge.SVGUtilities;
import org.apache.batik.bridge.TextNode;
import org.apache.batik.bridge.TextUtilities;
import org.apache.batik.bridge.UserAgent;
import org.apache.batik.bridge.SVGAElementBridge;
import org.apache.batik.css.engine.CSSEngine;
import org.apache.batik.css.engine.SVGCSSEngine;
import org.apache.batik.css.engine.value.ComputedValue;
import org.apache.batik.css.engine.value.svg12.SVG12ValueConstants;
import org.apache.batik.css.engine.value.svg12.LineHeightValue;
import org.apache.batik.css.engine.value.Value;
import org.apache.batik.css.engine.value.ValueConstants;
import org.apache.batik.dom.AbstractNode;
import org.apache.batik.dom.events.NodeEventTarget;
import org.apache.batik.dom.util.XMLSupport;
import org.apache.batik.dom.util.XLinkSupport;
import org.apache.batik.gvt.CompositeGraphicsNode;
import org.apache.batik.gvt.GraphicsNode;
import org.apache.batik.gvt.flow.BlockInfo;
import org.apache.batik.gvt.flow.RegionInfo;
import org.apache.batik.gvt.flow.TextLineBreaks;
import org.apache.batik.gvt.text.GVTAttributedCharacterIterator;
import org.apache.batik.gvt.text.TextPaintInfo;
import org.apache.batik.gvt.text.TextPath;
import org.apache.batik.util.SVG12Constants;
import org.apache.batik.util.SVG12CSSConstants;
import org.apache.batik.constants.XMLConstants;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
/**
* Bridge class for the <flowRoot> element.
*
* @author <a href="mailto:deweese@apache.org">Thomas DeWeese</a>
* @version $Id$
*/
public class SVGFlowRootElementBridge extends SVG12TextElementBridge {
public static final
AttributedCharacterIterator.Attribute FLOW_PARAGRAPH =
GVTAttributedCharacterIterator.TextAttribute.FLOW_PARAGRAPH;
public static final
AttributedCharacterIterator.Attribute FLOW_EMPTY_PARAGRAPH =
GVTAttributedCharacterIterator.TextAttribute.FLOW_EMPTY_PARAGRAPH;
public static final
AttributedCharacterIterator.Attribute FLOW_LINE_BREAK =
GVTAttributedCharacterIterator.TextAttribute.FLOW_LINE_BREAK;
public static final
AttributedCharacterIterator.Attribute FLOW_REGIONS =
GVTAttributedCharacterIterator.TextAttribute.FLOW_REGIONS;
public static final
AttributedCharacterIterator.Attribute LINE_HEIGHT =
GVTAttributedCharacterIterator.TextAttribute.LINE_HEIGHT;
public static final
GVTAttributedCharacterIterator.TextAttribute TEXTPATH =
GVTAttributedCharacterIterator.TextAttribute.TEXTPATH;
public static final
GVTAttributedCharacterIterator.TextAttribute ANCHOR_TYPE =
GVTAttributedCharacterIterator.TextAttribute.ANCHOR_TYPE;
public static final
GVTAttributedCharacterIterator.TextAttribute LETTER_SPACING =
GVTAttributedCharacterIterator.TextAttribute.LETTER_SPACING;
public static final
GVTAttributedCharacterIterator.TextAttribute WORD_SPACING =
GVTAttributedCharacterIterator.TextAttribute.WORD_SPACING;
public static final
GVTAttributedCharacterIterator.TextAttribute KERNING =
GVTAttributedCharacterIterator.TextAttribute.KERNING;
/**
* Map of flowRegion elements to their graphics nodes.
*/
protected Map flowRegionNodes;
protected TextNode textNode;
protected TextNode getTextNode() { return textNode; }
/**
* Listener for flowRegion changes.
*/
protected RegionChangeListener regionChangeListener;
/**
* Constructs a new bridge for the <flowRoot> element.
*/
public SVGFlowRootElementBridge() {}
/**
* Returns the SVG namespace URI.
*/
public String getNamespaceURI() {
return SVG12Constants.SVG_NAMESPACE_URI;
}
/**
* Returns 'flowRoot'.
*/
public String getLocalName() {
return SVG12Constants.SVG_FLOW_ROOT_TAG;
}
/**
* Returns a new instance of this bridge.
*/
public Bridge getInstance() {
return new SVGFlowRootElementBridge();
}
/**
* Returns false as text is not a container.
*/
public boolean isComposite() {
return false;
}
/**
* Creates a <code>GraphicsNode</code> according to the specified parameters.
*
* @param ctx the bridge context to use
* @param e the element that describes the graphics node to build
* @return a graphics node that represents the specified element
*/
public GraphicsNode createGraphicsNode(BridgeContext ctx, Element e) {
// 'requiredFeatures', 'requiredExtensions' and 'systemLanguage'
if (!SVGUtilities.matchUserAgent(e, ctx.getUserAgent())) {
return null;
}
CompositeGraphicsNode cgn = new CompositeGraphicsNode();
// 'transform'
String s = e.getAttributeNS(null, SVG_TRANSFORM_ATTRIBUTE);
if (s.length() != 0) {
cgn.setTransform
(SVGUtilities.convertTransform(e, SVG_TRANSFORM_ATTRIBUTE, s,
ctx));
}
// 'visibility'
cgn.setVisible(CSSUtilities.convertVisibility(e));
// 'text-rendering' and 'color-rendering'
RenderingHints hints = null;
hints = CSSUtilities.convertColorRendering(e, hints);
hints = CSSUtilities.convertTextRendering (e, hints);
if (hints != null) {
cgn.setRenderingHints(hints);
}
// first child holds the flow region nodes
CompositeGraphicsNode cgn2 = new CompositeGraphicsNode();
cgn.add(cgn2);
// second child is the text node
FlowTextNode tn = (FlowTextNode)instantiateGraphicsNode();
tn.setLocation(getLocation(ctx, e));
// specify the text painter to use
if (ctx.getTextPainter() != null) {
tn.setTextPainter(ctx.getTextPainter());
}
textNode = tn;
cgn.add(tn);
associateSVGContext(ctx, e, cgn);
// traverse the children to add SVGContext
Node child = getFirstChild(e);
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
addContextToChild(ctx,(Element)child);
}
child = getNextSibling(child);
}
return cgn;
}
/**
* Creates the graphics node for this element.
*/
protected GraphicsNode instantiateGraphicsNode() {
return new FlowTextNode();
}
/**
* Returns the text node location In this case the text node may
* have serveral effective locations (one for each flow region).
* So it always returns 0,0.
*
* @param ctx the bridge context to use
* @param e the text element
*/
protected Point2D getLocation(BridgeContext ctx, Element e) {
return new Point2D.Float(0,0);
}
protected boolean isTextElement(Element e) {
if (!SVG_NAMESPACE_URI.equals(e.getNamespaceURI()))
return false;
String nodeName = e.getLocalName();
return (nodeName.equals(SVG12Constants.SVG_FLOW_DIV_TAG) ||
nodeName.equals(SVG12Constants.SVG_FLOW_LINE_TAG) ||
nodeName.equals(SVG12Constants.SVG_FLOW_PARA_TAG) ||
nodeName.equals(SVG12Constants.SVG_FLOW_REGION_BREAK_TAG) ||
nodeName.equals(SVG12Constants.SVG_FLOW_SPAN_TAG));
}
protected boolean isTextChild(Element e) {
if (!SVG_NAMESPACE_URI.equals(e.getNamespaceURI()))
return false;
String nodeName = e.getLocalName();
return (nodeName.equals(SVG12Constants.SVG_A_TAG) ||
nodeName.equals(SVG12Constants.SVG_FLOW_LINE_TAG) ||
nodeName.equals(SVG12Constants.SVG_FLOW_PARA_TAG) ||
nodeName.equals(SVG12Constants.SVG_FLOW_REGION_BREAK_TAG) ||
nodeName.equals(SVG12Constants.SVG_FLOW_SPAN_TAG));
}
/**
* Builds using the specified BridgeContext and element, the
* specified graphics node.
*
* @param ctx the bridge context to use
* @param e the element that describes the graphics node to build
* @param node the graphics node to build
*/
public void buildGraphicsNode(BridgeContext ctx,
Element e,
GraphicsNode node) {
CompositeGraphicsNode cgn = (CompositeGraphicsNode) node;
// build flowRegion shapes
boolean isStatic = !ctx.isDynamic();
if (isStatic) {
flowRegionNodes = new HashMap();
} else {
regionChangeListener = new RegionChangeListener();
}
CompositeGraphicsNode cgn2 = (CompositeGraphicsNode) cgn.get(0);
GVTBuilder builder = ctx.getGVTBuilder();
for (Node n = getFirstChild(e); n != null; n = getNextSibling(n)) {
if (n instanceof SVGOMFlowRegionElement) {
for (Node m = getFirstChild(n);
m != null;
m = getNextSibling(m)) {
if (m.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
GraphicsNode gn = builder.build(ctx, (Element) m);
if (gn != null) {
cgn2.add(gn);
if (isStatic) {
flowRegionNodes.put(m, gn);
}
}
}
if (!isStatic) {
AbstractNode an = (AbstractNode) n;
XBLEventSupport es =
(XBLEventSupport) an.initializeEventSupport();
es.addImplementationEventListenerNS
(SVG_NAMESPACE_URI, "shapechange", regionChangeListener,
false);
}
}
}
// build text node
GraphicsNode tn = (GraphicsNode) cgn.get(1);
super.buildGraphicsNode(ctx, e, tn);
// Drop references once static build is completed.
flowRegionNodes = null;
}
protected void computeLaidoutText(BridgeContext ctx,
Element e,
GraphicsNode node) {
super.computeLaidoutText(ctx, getFlowDivElement(e), node);
}
/**
* Add to the element children of the node, a
* <code>SVGContext</code> to support dynamic update. This is
* recursive, the children of the nodes are also traversed to add
* to the support elements their context
*
* @param ctx a <code>BridgeContext</code> value
* @param e an <code>Element</code> value
*
* @see org.apache.batik.dom.svg.SVGContext
* @see org.apache.batik.bridge.BridgeUpdateHandler
*/
protected void addContextToChild(BridgeContext ctx, Element e) {
if (SVG_NAMESPACE_URI.equals(e.getNamespaceURI())) {
String ln = e.getLocalName();
if (ln.equals(SVG12Constants.SVG_FLOW_DIV_TAG)
|| ln.equals(SVG12Constants.SVG_FLOW_LINE_TAG)
|| ln.equals(SVG12Constants.SVG_FLOW_PARA_TAG)
|| ln.equals(SVG12Constants.SVG_FLOW_SPAN_TAG)) {
((SVGOMElement) e).setSVGContext
(new FlowContentBridge(ctx, this, e));
}
}
// traverse the children to add SVGContext
Node child = getFirstChild(e);
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
addContextToChild(ctx,(Element)child);
}
child = getNextSibling(child);
}
}
/**
* From the <code>SVGContext</code> from the element children of the node.
*
* @param ctx the <code>BridgeContext</code> for the document
* @param e the <code>Element</code> whose subtree's elements will have
* threir <code>SVGContext</code>s removed
*
* @see org.apache.batik.dom.svg.SVGContext
* @see org.apache.batik.bridge.BridgeUpdateHandler
*/
protected void removeContextFromChild(BridgeContext ctx, Element e) {
if (SVG_NAMESPACE_URI.equals(e.getNamespaceURI())) {
String ln = e.getLocalName();
if (ln.equals(SVG12Constants.SVG_FLOW_DIV_TAG)
|| ln.equals(SVG12Constants.SVG_FLOW_LINE_TAG)
|| ln.equals(SVG12Constants.SVG_FLOW_PARA_TAG)
|| ln.equals(SVG12Constants.SVG_FLOW_SPAN_TAG)) {
((AbstractTextChildBridgeUpdateHandler)
((SVGOMElement) e).getSVGContext()).dispose();
}
}
Node child = getFirstChild(e);
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
removeContextFromChild(ctx, (Element)child);
}
child = getNextSibling(child);
}
}
/**
* Creates the attributed string which represents the given text
* element children.
*
* @param ctx the bridge context to use
* @param element the text element
*/
protected AttributedString buildAttributedString(BridgeContext ctx,
Element element) {
if (element == null) return null;
List rgns = getRegions(ctx, element);
AttributedString ret = getFlowDiv(ctx, element);
if (ret == null) return ret;
ret.addAttribute(FLOW_REGIONS, rgns, 0, 1);
TextLineBreaks.findLineBrk(ret);
// dumpACIWord(ret);
return ret;
}
protected void dumpACIWord(AttributedString as) {
if (as == null) return;
StringBuffer chars = new StringBuffer();
StringBuffer brkStr = new StringBuffer();
AttributedCharacterIterator aci = as.getIterator();
AttributedCharacterIterator.Attribute WORD_LIMIT =
TextLineBreaks.WORD_LIMIT;
for (char ch = aci.current();
ch!=AttributedCharacterIterator.DONE;
ch = aci.next()) {
chars.append( ch ).append( ' ' ).append( ' ' );
int w = (Integer) aci.getAttribute(WORD_LIMIT);
brkStr.append( w ).append( ' ' );
if (w < 10) {
// for small values append another ' '
brkStr.append( ' ' );
}
}
System.out.println( chars.toString() );
System.out.println( brkStr.toString() );
}
protected Element getFlowDivElement(Element elem) {
String eNS = elem.getNamespaceURI();
if (!eNS.equals(SVG_NAMESPACE_URI)) return null;
String nodeName = elem.getLocalName();
if (nodeName.equals(SVG12Constants.SVG_FLOW_DIV_TAG)) return elem;
if (!nodeName.equals(SVG12Constants.SVG_FLOW_ROOT_TAG)) return null;
for (Node n = getFirstChild(elem);
n != null; n = getNextSibling(n)) {
if (n.getNodeType() != Node.ELEMENT_NODE) continue;
String nNS = n.getNamespaceURI();
if (!SVG_NAMESPACE_URI.equals(nNS)) continue;
Element e = (Element)n;
String ln = e.getLocalName();
if (ln.equals(SVG12Constants.SVG_FLOW_DIV_TAG))
return e;
}
return null;
}
protected AttributedString getFlowDiv(BridgeContext ctx, Element element) {
Element flowDiv = getFlowDivElement(element);
if (flowDiv == null) return null;
return gatherFlowPara(ctx, flowDiv);
}
protected AttributedString gatherFlowPara
(BridgeContext ctx, Element div) {
TextPaintInfo divTPI = new TextPaintInfo();
// Set some basic props so we can get bounds info for complex paints.
divTPI.visible = true;
divTPI.fillPaint = Color.black;
elemTPI.put(div, divTPI);
AttributedStringBuffer asb = new AttributedStringBuffer();
List paraEnds = new ArrayList();
List paraElems = new ArrayList();
List lnLocs = new ArrayList();
for (Node n = getFirstChild(div);
n != null;
n = getNextSibling(n)) {
if (n.getNodeType() != Node.ELEMENT_NODE
|| !getNamespaceURI().equals(n.getNamespaceURI())) {
continue;
}
Element e = (Element)n;
String ln = e.getLocalName();
if (ln.equals(SVG12Constants.SVG_FLOW_PARA_TAG)) {
fillAttributedStringBuffer
(ctx, e, true, null, null, asb, lnLocs);
paraElems.add(e);
paraEnds.add(asb.length());
} else if (ln.equals(SVG12Constants.SVG_FLOW_REGION_BREAK_TAG)) {
fillAttributedStringBuffer
(ctx, e, true, null, null, asb, lnLocs);
paraElems.add(e);
paraEnds.add(asb.length());
}
}
divTPI.startChar = 0;
divTPI.endChar = asb.length()-1;
// Layer in the PARAGRAPH/LINE_BREAK Attributes so we can
// break up text chunks.
AttributedString ret = asb.toAttributedString();
if (ret == null)
return null;
// Note: The Working Group (in conjunction with XHTML working
// group) has decided that multiple line elements collapse.
int prevLN = 0;
for (Object lnLoc : lnLocs) {
int nextLN = (Integer) lnLoc;
if (nextLN == prevLN) continue;
// System.out.println("Attr: [" + prevLN + "," + nextLN + "]");
ret.addAttribute(FLOW_LINE_BREAK,
new Object(),
prevLN, nextLN);
prevLN = nextLN;
}
int start=0;
int end;
List emptyPara = null;
for (int i=0; i<paraElems.size(); i++, start=end) {
Element elem = (Element)paraElems.get(i);
end = (Integer) paraEnds.get(i);
if (start == end) {
if (emptyPara == null)
emptyPara = new LinkedList();
emptyPara.add(makeBlockInfo(ctx, elem));
continue;
}
// System.out.println("Para: [" + start + ", " + end + "]");
ret.addAttribute(FLOW_PARAGRAPH, makeBlockInfo(ctx, elem),
start, end);
if (emptyPara != null) {
ret.addAttribute(FLOW_EMPTY_PARAGRAPH, emptyPara, start, end);
emptyPara = null;
}
}
return ret;
}
/**
* Returns a list of Shapes that define the flow regions.
*/
protected List getRegions(BridgeContext ctx, Element element) {
// Element comes in as flowDiv element we want flowRoot.
element = (Element)element.getParentNode();
List ret = new LinkedList();
for (Node n = getFirstChild(element);
n != null; n = getNextSibling(n)) {
if (n.getNodeType() != Node.ELEMENT_NODE) continue;
if (!SVG12Constants.SVG_NAMESPACE_URI.equals(n.getNamespaceURI()))
continue;
Element e = (Element)n;
String ln = e.getLocalName();
if (!SVG12Constants.SVG_FLOW_REGION_TAG.equals(ln)) continue;
// our default alignment is to the top of the flow rect.
float verticalAlignment = 0.0f;
gatherRegionInfo(ctx, e, verticalAlignment, ret);
}
return ret;
}
protected void gatherRegionInfo(BridgeContext ctx, Element rgn,
float verticalAlign, List regions) {
boolean isStatic = !ctx.isDynamic();
for (Node n = getFirstChild(rgn); n != null; n = getNextSibling(n)) {
if (n.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
GraphicsNode gn = isStatic ? (GraphicsNode) flowRegionNodes.get(n)
: ctx.getGraphicsNode(n);
Shape s = gn.getOutline();
if (s == null) {
continue;
}
AffineTransform at = gn.getTransform();
if (at != null) {
s = at.createTransformedShape(s);
}
regions.add(new RegionInfo(s, verticalAlign));
}
}
protected int startLen;
/**
* Fills the given AttributedStringBuffer.
*/
protected void fillAttributedStringBuffer(BridgeContext ctx,
Element element,
boolean top,
Integer bidiLevel,
Map initialAttributes,
AttributedStringBuffer asb,
List lnLocs) {
// 'requiredFeatures', 'requiredExtensions', 'systemLanguage' &
// 'display="none".
if ((!SVGUtilities.matchUserAgent(element, ctx.getUserAgent())) ||
(!CSSUtilities.convertDisplay(element))) {
return;
}
String s = XMLSupport.getXMLSpace(element);
boolean preserve = s.equals(SVG_PRESERVE_VALUE);
boolean prevEndsWithSpace;
Element nodeElement = element;
int elementStartChar = asb.length();
if (top) {
endLimit = startLen = asb.length();
}
if (preserve) {
endLimit = startLen;
}
Map map = initialAttributes == null
? new HashMap()
: new HashMap(initialAttributes);
initialAttributes =
getAttributeMap(ctx, element, null, bidiLevel, map);
Object o = map.get(TextAttribute.BIDI_EMBEDDING);
Integer subBidiLevel = bidiLevel;
if (o != null) {
subBidiLevel = (Integer) o;
}
int lineBreak = -1;
if (lnLocs.size() != 0) {
lineBreak = (Integer) lnLocs.get(lnLocs.size() - 1);
}
for (Node n = getFirstChild(element);
n != null;
n = getNextSibling(n)) {
if (preserve) {
prevEndsWithSpace = false;
} else {
int len = asb.length();
if (len == startLen) {
prevEndsWithSpace = true;
} else {
prevEndsWithSpace = (asb.getLastChar() == ' ');
int idx = lnLocs.size()-1;
if (!prevEndsWithSpace && (idx >= 0)) {
Integer i = (Integer)lnLocs.get(idx);
if (i == len) {
prevEndsWithSpace = true;
}
}
}
}
switch (n.getNodeType()) {
case Node.ELEMENT_NODE:
// System.out.println("Element: " + n);
if (!SVG_NAMESPACE_URI.equals(n.getNamespaceURI()))
break;
nodeElement = (Element)n;
String ln = n.getLocalName();
if (ln.equals(SVG12Constants.SVG_FLOW_LINE_TAG)) {
int before = asb.length();
fillAttributedStringBuffer(ctx, nodeElement, false,
subBidiLevel, initialAttributes,
asb, lnLocs);
// System.out.println("Line: " + asb.length() +
// " - '" + asb + "'");
lineBreak = asb.length();
lnLocs.add(lineBreak);
if (before != lineBreak) {
initialAttributes = null;
}
} else if (ln.equals(SVG12Constants.SVG_FLOW_SPAN_TAG) ||
ln.equals(SVG12Constants.SVG_ALT_GLYPH_TAG)) {
int before = asb.length();
fillAttributedStringBuffer(ctx, nodeElement, false,
subBidiLevel, initialAttributes,
asb, lnLocs);
if (asb.length() != before) {
initialAttributes = null;
}
} else if (ln.equals(SVG_A_TAG)) {
if (ctx.isInteractive()) {
NodeEventTarget target = (NodeEventTarget)nodeElement;
UserAgent ua = ctx.getUserAgent();
SVGAElementBridge.CursorHolder ch;
ch = new SVGAElementBridge.CursorHolder
(CursorManager.DEFAULT_CURSOR);
target.addEventListenerNS
(XMLConstants.XML_EVENTS_NAMESPACE_URI,
SVG_EVENT_CLICK,
new SVGAElementBridge.AnchorListener(ua, ch),
false, null);
target.addEventListenerNS
(XMLConstants.XML_EVENTS_NAMESPACE_URI,
SVG_EVENT_MOUSEOVER,
new SVGAElementBridge.CursorMouseOverListener(ua,ch),
false, null);
target.addEventListenerNS
(XMLConstants.XML_EVENTS_NAMESPACE_URI,
SVG_EVENT_MOUSEOUT,
new SVGAElementBridge.CursorMouseOutListener(ua,ch),
false, null);
}
int before = asb.length();
fillAttributedStringBuffer(ctx, nodeElement, false,
subBidiLevel, initialAttributes,
asb, lnLocs);
if (asb.length() != before) {
initialAttributes = null;
}
} else if (ln.equals(SVG_TREF_TAG)) {
String uriStr = XLinkSupport.getXLinkHref((Element)n);
Element ref = ctx.getReferencedElement((Element)n, uriStr);
s = TextUtilities.getElementContent(ref);
s = normalizeString(s, preserve, prevEndsWithSpace);
if (s.length() != 0) {
int trefStart = asb.length();
Map m = new HashMap();
getAttributeMap(ctx, nodeElement, null, bidiLevel, m);
asb.append(s, m);
int trefEnd = asb.length() - 1;
TextPaintInfo tpi;
tpi = (TextPaintInfo)elemTPI.get(nodeElement);
tpi.startChar = trefStart;
tpi.endChar = trefEnd;
}
}
break;
case Node.TEXT_NODE:
case Node.CDATA_SECTION_NODE:
s = n.getNodeValue();
s = normalizeString(s, preserve, prevEndsWithSpace);
if (s.length() != 0) {
asb.append(s, map);
if (preserve) {
endLimit = asb.length();
}
initialAttributes = null;
}
}
}
if (top) {
boolean strippedSome = false;
while ((endLimit < asb.length()) && (asb.getLastChar() == ' ')) {
int idx = lnLocs.size()-1;
int len = asb.length();
if (idx >= 0) {
Integer i = (Integer)lnLocs.get(idx);
if (i >= len) {
i = len - 1;
lnLocs.set(idx, i);
idx--;
while (idx >= 0) {
i = (Integer)lnLocs.get(idx);
if (i < len-1)
break;
lnLocs.remove(idx);
idx--;
}
}
}
asb.stripLast();
strippedSome = true;
}
if (strippedSome) {
for (Object o1 : elemTPI.values()) {
TextPaintInfo tpi = (TextPaintInfo) o1;
if (tpi.endChar >= asb.length()) {
tpi.endChar = asb.length() - 1;
if (tpi.startChar > tpi.endChar)
tpi.startChar = tpi.endChar;
}
}
}
}
int elementEndChar = asb.length()-1;
TextPaintInfo tpi = (TextPaintInfo)elemTPI.get(element);
tpi.startChar = elementStartChar;
tpi.endChar = elementEndChar;
}
protected Map getAttributeMap(BridgeContext ctx,
Element element,
TextPath textPath,
Integer bidiLevel,
Map result) {
Map inheritingMap =
super.getAttributeMap(ctx, element, textPath, bidiLevel, result);
float fontSize = TextUtilities.convertFontSize(element);
float lineHeight = getLineHeight(ctx, element, fontSize);
result.put(LINE_HEIGHT, lineHeight);
return inheritingMap;
}
protected void checkMap(Map attrs) {
if (attrs.containsKey(TEXTPATH)) {
return; // Problem, unsupported attr
}
if (attrs.containsKey(ANCHOR_TYPE)) {
return; // Problem, unsupported attr
}
if (attrs.containsKey(LETTER_SPACING)) {
return; // Problem, unsupported attr
}
if (attrs.containsKey(WORD_SPACING)) {
return; // Problem, unsupported attr
}
if (attrs.containsKey(KERNING)) {
return; // Problem, unsupported attr
}
}
int marginTopIndex = -1;
int marginRightIndex = -1;
int marginBottomIndex = -1;
int marginLeftIndex = -1;
int indentIndex = -1;
int textAlignIndex = -1;
int lineHeightIndex = -1;
protected void initCSSPropertyIndexes(Element e) {
CSSEngine eng = CSSUtilities.getCSSEngine(e);
marginTopIndex = eng.getPropertyIndex(SVG12CSSConstants.CSS_MARGIN_TOP_PROPERTY);
marginRightIndex = eng.getPropertyIndex(SVG12CSSConstants.CSS_MARGIN_RIGHT_PROPERTY);
marginBottomIndex = eng.getPropertyIndex(SVG12CSSConstants.CSS_MARGIN_BOTTOM_PROPERTY);
marginLeftIndex = eng.getPropertyIndex(SVG12CSSConstants.CSS_MARGIN_LEFT_PROPERTY);
indentIndex = eng.getPropertyIndex(SVG12CSSConstants.CSS_INDENT_PROPERTY);
textAlignIndex = eng.getPropertyIndex(SVG12CSSConstants.CSS_TEXT_ALIGN_PROPERTY);
lineHeightIndex = eng.getPropertyIndex(SVG12CSSConstants.CSS_LINE_HEIGHT_PROPERTY);
}
public BlockInfo makeBlockInfo(BridgeContext ctx, Element element) {
if (marginTopIndex == -1) initCSSPropertyIndexes(element);
Value v;
v = CSSUtilities.getComputedStyle(element, marginTopIndex);
float top = v.getFloatValue();
v = CSSUtilities.getComputedStyle(element, marginRightIndex);
float right = v.getFloatValue();
v = CSSUtilities.getComputedStyle(element, marginBottomIndex);
float bottom = v.getFloatValue();
v = CSSUtilities.getComputedStyle(element, marginLeftIndex);
float left = v.getFloatValue();
v = CSSUtilities.getComputedStyle(element, indentIndex);
float indent = v.getFloatValue();
v = CSSUtilities.getComputedStyle(element, textAlignIndex);
if (v == ValueConstants.INHERIT_VALUE) {
v = CSSUtilities.getComputedStyle(element,
SVGCSSEngine.DIRECTION_INDEX);
if (v == ValueConstants.LTR_VALUE)
v = SVG12ValueConstants.START_VALUE;
else
v = SVG12ValueConstants.END_VALUE;
}
int textAlign;
if (v == SVG12ValueConstants.START_VALUE)
textAlign = BlockInfo.ALIGN_START;
else if (v == SVG12ValueConstants.MIDDLE_VALUE)
textAlign = BlockInfo.ALIGN_MIDDLE;
else if (v == SVG12ValueConstants.END_VALUE)
textAlign = BlockInfo.ALIGN_END;
else
textAlign = BlockInfo.ALIGN_FULL;
Map fontAttrs = new HashMap(20);
List fontList = getFontList(ctx, element, fontAttrs);
Float fs = (Float)fontAttrs.get(TextAttribute.SIZE);
float fontSize = fs;
float lineHeight = getLineHeight(ctx, element, fontSize);
String ln = element.getLocalName();
boolean rgnBr;
rgnBr = ln.equals(SVG12Constants.SVG_FLOW_REGION_BREAK_TAG);
return new BlockInfo(top, right, bottom, left, indent, textAlign,
lineHeight, fontList, fontAttrs, rgnBr);
}
protected float getLineHeight(BridgeContext ctx, Element element,
float fontSize) {
if (lineHeightIndex == -1) initCSSPropertyIndexes(element);
Value v = CSSUtilities.getComputedStyle(element, lineHeightIndex);
if ((v == ValueConstants.INHERIT_VALUE) ||
(v == SVG12ValueConstants.NORMAL_VALUE)) {
return fontSize*1.1f;
}
float lineHeight = v.getFloatValue();
if (v instanceof ComputedValue)
v = ((ComputedValue)v).getComputedValue();
if ((v instanceof LineHeightValue) &&
((LineHeightValue)v).getFontSizeRelative())
lineHeight *= fontSize;
return lineHeight;
}
/**
* Bridge class for flow text children that contain text.
*/
protected class FlowContentBridge extends AbstractTextChildTextContent {
/**
* Creates a new FlowContentBridge.
*/
public FlowContentBridge(BridgeContext ctx,
SVGTextElementBridge parent,
Element e) {
super(ctx, parent, e);
}
}
/**
* svg:shapechange listener for flowRegion elements.
*/
protected class RegionChangeListener implements EventListener {
/**
* Handles the svg:shapechange event.
*/
public void handleEvent(Event evt) {
// the flowRegion geometry may have changed, so relayout text
laidoutText = null;
computeLaidoutText(ctx, e, getTextNode());
}
}
}
|
apache/hive | 36,729 | ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveRelFieldTrimmer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.optimizer.calcite.rules;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import org.apache.calcite.adapter.druid.DruidQuery;
import org.apache.calcite.linq4j.Ord;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.rel.RelCollation;
import org.apache.calcite.rel.RelCollations;
import org.apache.calcite.rel.RelDistribution;
import org.apache.calcite.rel.RelFieldCollation;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.Aggregate;
import org.apache.calcite.rel.core.AggregateCall;
import org.apache.calcite.rel.core.CorrelationId;
import org.apache.calcite.rel.core.Project;
import org.apache.calcite.rel.core.TableFunctionScan;
import org.apache.calcite.rel.core.TableScan;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeField;
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.rex.RexCall;
import org.apache.calcite.rex.RexCorrelVariable;
import org.apache.calcite.rex.RexFieldAccess;
import org.apache.calcite.rex.RexLiteral;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexPermuteInputsShuttle;
import org.apache.calcite.rex.RexTableInputRef;
import org.apache.calcite.rex.RexUtil;
import org.apache.calcite.rex.RexVisitor;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql2rel.CorrelationReferenceFinder;
import org.apache.calcite.tools.RelBuilder;
import org.apache.calcite.util.ImmutableBitSet;
import org.apache.calcite.util.Pair;
import org.apache.calcite.util.mapping.IntPair;
import org.apache.calcite.util.mapping.Mapping;
import org.apache.calcite.util.mapping.MappingType;
import org.apache.calcite.util.mapping.Mappings;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.optimizer.calcite.HiveCalciteUtil;
import org.apache.hadoop.hive.ql.optimizer.calcite.RelOptHiveTable;
import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveAggregate;
import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveMultiJoin;
import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveProject;
import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveSortExchange;
import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveTableFunctionScan;
import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveTableScan;
import org.apache.hadoop.hive.ql.parse.ColumnAccessInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
public class HiveRelFieldTrimmer extends RelFieldTrimmer {
protected static final Logger LOG = LoggerFactory.getLogger(HiveRelFieldTrimmer.class);
// We initialize the field trimmer statically here and we will reuse it across
// queries. The reason is that otherwise we will create a new dispatcher with
// each instantiation, thus effectively removing the caching mechanism that is
// built within the dispatcher.
private static final HiveRelFieldTrimmer FIELD_TRIMMER_STATS =
new HiveRelFieldTrimmer(true);
private static final HiveRelFieldTrimmer FIELD_TRIMMER_NO_STATS =
new HiveRelFieldTrimmer(false);
// For testing
private static final HiveRelFieldTrimmer FIELD_TRIMMER_STATS_METHOD_DISPATCHER =
new HiveRelFieldTrimmer(true, false);
private static final HiveRelFieldTrimmer FIELD_TRIMMER_NO_STATS_METHOD_DISPATCHER =
new HiveRelFieldTrimmer(false, false);
private final boolean fetchStats;
private static final ThreadLocal<ColumnAccessInfo> COLUMN_ACCESS_INFO =
new ThreadLocal<>();
private static final ThreadLocal<Map<HiveProject, Table>> VIEW_PROJECT_TO_TABLE_SCHEMA =
new ThreadLocal<>();
protected HiveRelFieldTrimmer(boolean fetchStats) {
this(fetchStats, true);
}
private HiveRelFieldTrimmer(boolean fetchStats, boolean useLMFBasedDispatcher) {
super(useLMFBasedDispatcher);
this.fetchStats = fetchStats;
}
/**
* Returns a HiveRelFieldTrimmer instance that does not retrieve
* stats.
*/
public static HiveRelFieldTrimmer get() {
return get(false);
}
/**
* Returns a HiveRelFieldTrimmer instance that can retrieve stats.
*/
public static HiveRelFieldTrimmer get(boolean fetchStats) {
return get(fetchStats, true);
}
/**
* Returns a HiveRelFieldTrimmer instance that can retrieve stats and use
* a custom dispatcher.
*/
public static HiveRelFieldTrimmer get(boolean fetchStats, boolean useLMFBasedDispatcher) {
return fetchStats ?
(useLMFBasedDispatcher ? FIELD_TRIMMER_STATS : FIELD_TRIMMER_STATS_METHOD_DISPATCHER) :
(useLMFBasedDispatcher ? FIELD_TRIMMER_NO_STATS : FIELD_TRIMMER_NO_STATS_METHOD_DISPATCHER);
}
/**
* Trims unused fields from a relational expression.
*
* <p>We presume that all fields of the relational expression are wanted by
* its consumer, so only trim fields that are not used within the tree.
*
* @param root Root node of relational expression
* @return Trimmed relational expression
*/
@Override
public RelNode trim(RelBuilder relBuilder, RelNode root) {
return trim(relBuilder, root, null, null);
}
public RelNode trim(RelBuilder relBuilder, RelNode root,
ColumnAccessInfo columnAccessInfo, Map<HiveProject, Table> viewToTableSchema) {
try {
// Set local thread variables
COLUMN_ACCESS_INFO.set(columnAccessInfo);
VIEW_PROJECT_TO_TABLE_SCHEMA.set(viewToTableSchema);
// Execute pruning
return super.trim(relBuilder, root);
} finally {
// Always remove the local thread variables to avoid leaks
COLUMN_ACCESS_INFO.remove();
VIEW_PROJECT_TO_TABLE_SCHEMA.remove();
}
}
/**
* Trims the fields of an input relational expression.
*
* @param rel Relational expression
* @param input Input relational expression, whose fields to trim
* @param fieldsUsed Bitmap of fields needed by the consumer
* @return New relational expression and its field mapping
*/
protected TrimResult trimChild(
RelNode rel,
RelNode input,
final ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
final ImmutableBitSet.Builder fieldsUsedBuilder = fieldsUsed.rebuild();
// Correlating variables are a means for other relational expressions to use
// fields.
for (final CorrelationId correlation : rel.getVariablesSet()) {
rel.accept(
new CorrelationReferenceFinder() {
protected RexNode handle(RexFieldAccess fieldAccess) {
final RexCorrelVariable v =
(RexCorrelVariable) fieldAccess.getReferenceExpr();
if (v.id.equals(correlation)) {
fieldsUsedBuilder.set(fieldAccess.getField().getIndex());
}
return fieldAccess;
}
});
}
return dispatchTrimFields(input, fieldsUsedBuilder.build(), extraFields);
}
/**
* Variant of {@link #trimFields(RelNode, ImmutableBitSet, Set)} for
* {@link org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveMultiJoin}.
*/
public TrimResult trimFields(
HiveMultiJoin join,
ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
final int fieldCount = join.getRowType().getFieldCount();
final RexNode conditionExpr = join.getCondition();
final List<RexNode> joinFilters = join.getJoinFilters();
// Add in fields used in the condition.
final Set<RelDataTypeField> combinedInputExtraFields =
new LinkedHashSet<RelDataTypeField>(extraFields);
RelOptUtil.InputFinder inputFinder =
new RelOptUtil.InputFinder(combinedInputExtraFields, fieldsUsed);
conditionExpr.accept(inputFinder);
final ImmutableBitSet fieldsUsedPlus = inputFinder.build();
int inputStartPos = 0;
int changeCount = 0;
int newFieldCount = 0;
List<RelNode> newInputs = new ArrayList<RelNode>();
List<Mapping> inputMappings = new ArrayList<Mapping>();
for (RelNode input : join.getInputs()) {
final RelDataType inputRowType = input.getRowType();
final int inputFieldCount = inputRowType.getFieldCount();
// Compute required mapping.
ImmutableBitSet.Builder inputFieldsUsed = ImmutableBitSet.builder();
for (int bit : fieldsUsedPlus) {
if (bit >= inputStartPos && bit < inputStartPos + inputFieldCount) {
inputFieldsUsed.set(bit - inputStartPos);
}
}
Set<RelDataTypeField> inputExtraFields =
Collections.<RelDataTypeField>emptySet();
TrimResult trimResult =
trimChild(join, input, inputFieldsUsed.build(), inputExtraFields);
newInputs.add(trimResult.left);
if (trimResult.left != input) {
++changeCount;
}
final Mapping inputMapping = trimResult.right;
inputMappings.add(inputMapping);
// Move offset to point to start of next input.
inputStartPos += inputFieldCount;
newFieldCount += inputMapping.getTargetCount();
}
Mapping mapping =
Mappings.create(
MappingType.INVERSE_SURJECTION,
fieldCount,
newFieldCount);
int offset = 0;
int newOffset = 0;
for (int i = 0; i < inputMappings.size(); i++) {
Mapping inputMapping = inputMappings.get(i);
for (IntPair pair : inputMapping) {
mapping.set(pair.source + offset, pair.target + newOffset);
}
offset += inputMapping.getSourceCount();
newOffset += inputMapping.getTargetCount();
}
if (changeCount == 0
&& mapping.isIdentity()) {
return new TrimResult(join, Mappings.createIdentity(fieldCount));
}
// Build new join.
final RexVisitor<RexNode> shuttle = new RexPermuteInputsShuttle(
mapping, newInputs.toArray(new RelNode[newInputs.size()]));
RexNode newConditionExpr = conditionExpr.accept(shuttle);
List<RexNode> newJoinFilters = Lists.newArrayList();
for (RexNode joinFilter : joinFilters) {
newJoinFilters.add(joinFilter.accept(shuttle));
}
final RelDataType newRowType = RelOptUtil.permute(join.getCluster().getTypeFactory(),
join.getRowType(), mapping);
final RelNode newJoin = new HiveMultiJoin(join.getCluster(),
newInputs,
newConditionExpr,
newRowType,
join.getJoinInputs(),
join.getJoinTypes(),
newJoinFilters);
return new TrimResult(newJoin, mapping);
}
/**
* Variant of {@link #trimFields(RelNode, ImmutableBitSet, Set)} for
* {@link org.apache.calcite.adapter.druid.DruidQuery}.
*/
public TrimResult trimFields(DruidQuery dq, ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
final int fieldCount = dq.getRowType().getFieldCount();
if (fieldsUsed.equals(ImmutableBitSet.range(fieldCount))
&& extraFields.isEmpty()) {
// if there is nothing to project or if we are projecting everything
// then no need to introduce another RelNode
return trimFields(
(RelNode) dq, fieldsUsed, extraFields);
}
final RelNode newTableAccessRel = project(dq, fieldsUsed, extraFields, REL_BUILDER.get());
// Some parts of the system can't handle rows with zero fields, so
// pretend that one field is used.
if (fieldsUsed.cardinality() == 0) {
RelNode input = newTableAccessRel;
if (input instanceof Project) {
// The table has implemented the project in the obvious way - by
// creating project with 0 fields. Strip it away, and create our own
// project with one field.
Project project = (Project) input;
if (project.getRowType().getFieldCount() == 0) {
input = project.getInput();
}
}
return dummyProject(fieldCount, input);
}
final Mapping mapping = createMapping(fieldsUsed, fieldCount);
return result(newTableAccessRel, mapping);
}
private static RelNode project(DruidQuery dq, ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields, RelBuilder relBuilder) {
final int fieldCount = dq.getRowType().getFieldCount();
if (fieldsUsed.equals(ImmutableBitSet.range(fieldCount))
&& extraFields.isEmpty()) {
return dq;
}
final List<RexNode> exprList = new ArrayList<>();
final List<String> nameList = new ArrayList<>();
final RexBuilder rexBuilder = dq.getCluster().getRexBuilder();
final List<RelDataTypeField> fields = dq.getRowType().getFieldList();
// Project the subset of fields.
for (int i : fieldsUsed) {
RelDataTypeField field = fields.get(i);
exprList.add(rexBuilder.makeInputRef(dq, i));
nameList.add(field.getName());
}
// Project nulls for the extra fields. (Maybe a sub-class table has
// extra fields, but we don't.)
for (RelDataTypeField extraField : extraFields) {
exprList.add(
rexBuilder.ensureType(
extraField.getType(),
rexBuilder.constantNull(),
true));
nameList.add(extraField.getName());
}
HiveProject hp = (HiveProject) relBuilder.push(dq).project(exprList, nameList).build();
hp.setSynthetic();
return hp;
}
private boolean isRexLiteral(final RexNode rexNode) {
if(rexNode instanceof RexLiteral) {
return true;
} else if(rexNode instanceof RexCall
&& ((RexCall)rexNode).getOperator().getKind() == SqlKind.CAST){
return isRexLiteral(((RexCall)(rexNode)).getOperands().get(0));
} else {
return false;
}
}
// Given a groupset this tries to find out if the cardinality of the grouping columns could have changed
// because if not, and it consists of keys (unique + not null OR pk), we can safely remove rest of the columns
// if those are columns are not being used further up
private ImmutableBitSet generateGroupSetIfCardinalitySame(final Aggregate aggregate,
final ImmutableBitSet originalGroupSet, final ImmutableBitSet fieldsUsed) {
RexBuilder rexBuilder = aggregate.getCluster().getRexBuilder();
RelMetadataQuery mq = aggregate.getCluster().getMetadataQuery();
// map from backtracked table ref to list of gb keys and list of corresponding backtracked columns
Map<RexTableInputRef.RelTableRef, List<Pair<Integer, Integer>>> mapGBKeysLineage= new HashMap<>();
// map from table ref to list of columns (from gb keys) which are candidate to be removed
Map<RexTableInputRef.RelTableRef, List<Integer>> candidateKeys = new HashMap<>();
for(int key:originalGroupSet) {
RexNode inputRef = rexBuilder.makeInputRef(aggregate.getInput(), key);
Set<RexNode> exprLineage = mq.getExpressionLineage(aggregate.getInput(), inputRef);
if(exprLineage != null && exprLineage.size() == 1){
RexNode expr = exprLineage.iterator().next();
if(expr instanceof RexTableInputRef) {
RexTableInputRef tblRef = (RexTableInputRef)expr;
if(mapGBKeysLineage.containsKey(tblRef.getTableRef())) {
mapGBKeysLineage.get(tblRef.getTableRef()).add(Pair.of(tblRef.getIndex(), key));
} else {
List<Pair<Integer, Integer>> newList = new ArrayList<>();
newList.add(Pair.of(tblRef.getIndex(), key));
mapGBKeysLineage.put(tblRef.getTableRef(), newList);
}
} else if(RexUtil.isDeterministic(expr)){
// even though we weren't able to backtrack this key it could still be candidate for removal
// if rest of the columns contain pk/unique
Set<RexTableInputRef.RelTableRef> tableRefs = RexUtil.gatherTableReferences(Lists.newArrayList(expr));
if(tableRefs.size() == 1) {
RexTableInputRef.RelTableRef tblRef = tableRefs.iterator().next();
if(candidateKeys.containsKey(tblRef)) {
List<Integer> candidateGBKeys = candidateKeys.get(tblRef);
candidateGBKeys.add(key);
} else {
List<Integer> candidateGBKeys = new ArrayList<>();
candidateGBKeys.add(key);
candidateKeys.put(tblRef, candidateGBKeys);
}
}
}
}
}
// we want to delete all columns in original GB set except the key
ImmutableBitSet.Builder builder = ImmutableBitSet.builder();
for(Map.Entry<RexTableInputRef.RelTableRef, List<Pair<Integer, Integer>>> entry:mapGBKeysLineage.entrySet()) {
RelOptHiveTable tbl = (RelOptHiveTable)entry.getKey().getTable();
List<Pair<Integer, Integer>> gbKeyCols = entry.getValue();
ImmutableBitSet.Builder btBuilder = ImmutableBitSet.builder();
gbKeyCols.forEach(pair -> btBuilder.set(pair.left));
ImmutableBitSet backtrackedGBSet = btBuilder.build();
List<ImmutableBitSet> allKeys = tbl.getNonNullableKeys();
ImmutableBitSet currentKey = null;
for(ImmutableBitSet key:allKeys) {
if(backtrackedGBSet.contains(key)) {
// only if grouping sets consist of keys
currentKey = key;
break;
}
}
if(currentKey == null || currentKey.isEmpty()) {
continue;
}
// we have established that this gb set contains keys and it is safe to remove rest of the columns
for(Pair<Integer, Integer> gbKeyColPair:gbKeyCols) {
Integer backtrackedCol = gbKeyColPair.left;
Integer orgCol = gbKeyColPair.right;
if(!fieldsUsed.get(orgCol)
&& !currentKey.get(backtrackedCol)) {
// this could could be removed
builder.set(orgCol);
}
}
// remove candidate keys if possible
if(candidateKeys.containsKey(entry.getKey())) {
List<Integer> candidateGbKeys= candidateKeys.get(entry.getKey());
for(Integer keyToRemove:candidateGbKeys) {
if(!fieldsUsed.get(keyToRemove)) {
builder.set(keyToRemove);
}
}
}
}
ImmutableBitSet keysToRemove = builder.build();
ImmutableBitSet newGroupSet = originalGroupSet.except(keysToRemove);
assert(!newGroupSet.isEmpty());
return newGroupSet;
}
// if gby keys consist of pk/uk non-pk/non-uk columns are removed if they are not being used
private ImmutableBitSet generateNewGroupset(Aggregate aggregate, ImmutableBitSet fieldsUsed) {
ImmutableBitSet originalGroupSet = aggregate.getGroupSet();
if (aggregate.getGroupSets().size() > 1 || aggregate.getIndicatorCount() > 0
|| fieldsUsed.contains(originalGroupSet)) {
// if there is grouping sets, indicator or all the group keys are being used we do no need to proceed further
return originalGroupSet;
}
final RelNode input = aggregate.getInput();
RelMetadataQuery mq = aggregate.getCluster().getMetadataQuery();
final Set<ImmutableBitSet> uniqueKeys = mq.getUniqueKeys(input, false);
if (uniqueKeys == null || uniqueKeys.isEmpty()) {
return generateGroupSetIfCardinalitySame(aggregate, originalGroupSet, fieldsUsed);
}
// Find the maximum number of columns that can be removed by retaining a certain unique key
ImmutableBitSet columnsToRemove = ImmutableBitSet.of();
final ImmutableBitSet unusedGroupingColumns = aggregate.getGroupSet().except(fieldsUsed);
for (ImmutableBitSet key : uniqueKeys) {
ImmutableBitSet removeCandidate = unusedGroupingColumns.except(key);
if (aggregate.getGroupSet().contains(key) && removeCandidate.cardinality() > columnsToRemove.cardinality()) {
columnsToRemove = removeCandidate;
}
}
return aggregate.getGroupSet().except(columnsToRemove);
}
/**
* This method replaces group by 'constant key' with group by true (boolean)
* if and only if
* group by doesn't have grouping sets
* all keys in group by are constant
* none of the relnode above aggregate refers to these keys
*
* If all of above is true then group by is rewritten and a new project is introduced
* underneath aggregate
*
* This is mainly done so that hive is able to push down queries with
* group by 'constant key with type not supported by druid' into druid.
*
*/
private Aggregate rewriteGBConstantKeys(Aggregate aggregate, ImmutableBitSet fieldsUsed,
ImmutableBitSet aggCallFields) {
if ((aggregate.getIndicatorCount() > 0)
|| (aggregate.getGroupSet().isEmpty())
|| fieldsUsed.contains(aggregate.getGroupSet())) {
return aggregate;
}
final RelNode input = aggregate.getInput();
final RelDataType rowType = input.getRowType();
RexBuilder rexBuilder = aggregate.getCluster().getRexBuilder();
final List<RexNode> newProjects = new ArrayList<>();
final List<RexNode> inputExprs = input instanceof Project ? ((Project) input).getProjects() : null;
if (inputExprs == null || inputExprs.isEmpty()) {
return aggregate;
}
boolean allConstants = true;
for (int key : aggregate.getGroupSet()) {
// getChildExprs on Join could return less number of expressions than there are coming out of join
if (inputExprs.size() <= key || !isRexLiteral(inputExprs.get(key))) {
allConstants = false;
break;
}
}
if (allConstants) {
for (int i = 0; i < rowType.getFieldCount(); i++) {
if (aggregate.getGroupSet().get(i) && !aggCallFields.get(i)) {
newProjects.add(rexBuilder.makeLiteral(true));
} else {
newProjects.add(rexBuilder.makeInputRef(input, i));
}
}
final RelBuilder relBuilder = REL_BUILDER.get();
relBuilder.push(input);
relBuilder.project(newProjects);
Aggregate newAggregate = new HiveAggregate(aggregate.getCluster(), aggregate.getTraitSet(), relBuilder.build(),
aggregate.getGroupSet(), aggregate.getGroupSets(), aggregate.getAggCallList());
return newAggregate;
}
return aggregate;
}
@Override
public TrimResult trimFields(Aggregate aggregate, ImmutableBitSet fieldsUsed, Set<RelDataTypeField> extraFields) {
// Fields:
//
// | sys fields | group fields | indicator fields | agg functions |
//
// Two kinds of trimming:
//
// 1. If agg rel has system fields but none of these are used, create an
// agg rel with no system fields.
//
// 2. If aggregate functions are not used, remove them.
//
// But group and indicator fields stay, even if they are not used.
// Compute which input fields are used.
// agg functions
// agg functions are added first (before group sets) because rewriteGBConstantsKeys
// needs it
final ImmutableBitSet.Builder aggCallFieldsUsedBuilder = ImmutableBitSet.builder();
for (AggregateCall aggCall : aggregate.getAggCallList()) {
for (int i : aggCall.getArgList()) {
aggCallFieldsUsedBuilder.set(i);
}
if (aggCall.filterArg >= 0) {
aggCallFieldsUsedBuilder.set(aggCall.filterArg);
}
aggCallFieldsUsedBuilder.addAll(RelCollations.ordinals(aggCall.collation));
}
// transform if group by contain constant keys
ImmutableBitSet aggCallFieldsUsed = aggCallFieldsUsedBuilder.build();
aggregate = rewriteGBConstantKeys(aggregate, fieldsUsed, aggCallFieldsUsed);
// add group fields
final ImmutableBitSet.Builder inputFieldsUsed = aggregate.getGroupSet().rebuild();
inputFieldsUsed.addAll(aggCallFieldsUsed);
final RelDataType rowType = aggregate.getRowType();
// Create input with trimmed columns.
final RelNode input = aggregate.getInput();
final Set<RelDataTypeField> inputExtraFields = Collections.emptySet();
final TrimResult trimResult =
trimChild(aggregate, input, inputFieldsUsed.build(), inputExtraFields);
final RelNode newInput = trimResult.left;
final Mapping inputMapping = trimResult.right;
ImmutableBitSet originalGroupSet = aggregate.getGroupSet();
ImmutableBitSet updatedGroupSet = generateNewGroupset(aggregate, fieldsUsed);
ImmutableBitSet gbKeysDeleted = originalGroupSet.except(updatedGroupSet);
ImmutableBitSet updatedGroupFields = ImmutableBitSet.range(originalGroupSet.cardinality());
final int updatedGroupCount = updatedGroupSet.cardinality();
// we need to clear the bits corresponding to deleted gb keys
int setIdx = 0;
while(setIdx != -1) {
setIdx = gbKeysDeleted.nextSetBit(setIdx);
if(setIdx != -1) {
updatedGroupFields = updatedGroupFields.clear(setIdx);
setIdx++;
}
}
fieldsUsed =
fieldsUsed.union(updatedGroupFields);
// If the input is unchanged, and we need to project all columns,
// there's nothing to do.
if (input == newInput
&& fieldsUsed.equals(ImmutableBitSet.range(rowType.getFieldCount()))) {
return result(aggregate,
Mappings.createIdentity(rowType.getFieldCount()));
}
// update the group by keys based on inputMapping
ImmutableBitSet newGroupSet =
Mappings.apply(inputMapping, updatedGroupSet);
// Which agg calls are used by our consumer?
int originalGroupCount = aggregate.getGroupSet().cardinality();
int j = originalGroupCount;
int usedAggCallCount = 0;
for (int i = 0; i < aggregate.getAggCallList().size(); i++) {
if (fieldsUsed.get(j++)) {
++usedAggCallCount;
}
}
// Offset due to the number of system fields having changed.
Mapping mapping =
Mappings.create(
MappingType.INVERSE_SURJECTION,
rowType.getFieldCount(),
updatedGroupCount + usedAggCallCount);
// if group keys were reduced, it means we didn't have grouping therefore
// we don't need to transform group sets
ImmutableList<ImmutableBitSet> newGroupSets = null;
if(!updatedGroupSet.equals(aggregate.getGroupSet())) {
newGroupSets = ImmutableList.of(newGroupSet);
} else {
newGroupSets = ImmutableList.copyOf(
Iterables.transform(aggregate.getGroupSets(),
input1 -> Mappings.apply(inputMapping, input1)));
}
// Populate mapping of where to find the fields. System, group key and
// indicator fields first.
int gbKeyIdx = 0;
for (j = 0; j < originalGroupCount; j++) {
if(fieldsUsed.get(j)) {
mapping.set(j, gbKeyIdx);
gbKeyIdx++;
}
}
// Now create new agg calls, and populate mapping for them.
final RelBuilder relBuilder = REL_BUILDER.get();
relBuilder.push(newInput);
final List<RelBuilder.AggCall> newAggCallList = new ArrayList<>();
j = originalGroupCount; // because lookup in fieldsUsed is done using original group count
for (AggregateCall aggCall : aggregate.getAggCallList()) {
if (fieldsUsed.get(j)) {
final ImmutableList<RexNode> args =
relBuilder.fields(
Mappings.apply2(inputMapping, aggCall.getArgList()));
final RexNode filterArg = aggCall.filterArg < 0 ? null
: relBuilder.field(Mappings.apply(inputMapping, aggCall.filterArg));
RelBuilder.AggCall newAggCall =
relBuilder.aggregateCall(aggCall.getAggregation(), args)
.distinct(aggCall.isDistinct())
.filter(filterArg)
.approximate(aggCall.isApproximate())
.sort(relBuilder.fields(aggCall.collation))
.as(aggCall.name);
mapping.set(j, updatedGroupCount + newAggCallList.size());
newAggCallList.add(newAggCall);
}
++j;
}
final RelBuilder.GroupKey groupKey =
relBuilder.groupKey(newGroupSet, newGroupSets);
relBuilder.aggregate(groupKey, newAggCallList);
return result(relBuilder.build(), mapping);
}
/**
* Variant of {@link #trimFields(RelNode, ImmutableBitSet, Set)} for
* {@link org.apache.calcite.rel.logical.LogicalProject}.
*/
public TrimResult trimFields(Project project, ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
// set columnAccessInfo for ViewColumnAuthorization
final ColumnAccessInfo columnAccessInfo = COLUMN_ACCESS_INFO.get();
final Map<HiveProject, Table> viewProjectToTableSchema = VIEW_PROJECT_TO_TABLE_SCHEMA.get();
if (columnAccessInfo != null && viewProjectToTableSchema != null
&& viewProjectToTableSchema.containsKey(project)) {
for (Ord<RexNode> ord : Ord.zip(project.getProjects())) {
if (fieldsUsed.get(ord.i)) {
Table tab = viewProjectToTableSchema.get(project);
columnAccessInfo.add(tab.getCompleteName(), tab.getAllCols().get(ord.i).getName());
}
}
}
return super.trimFields(project, fieldsUsed, extraFields);
}
public TrimResult trimFields(HiveTableScan tableAccessRel, ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
final TrimResult result = super.trimFields(tableAccessRel, fieldsUsed, extraFields);
final ColumnAccessInfo columnAccessInfo = COLUMN_ACCESS_INFO.get();
if (columnAccessInfo != null) {
// Store information about column accessed by the table so it can be used
// to send only this information for column masking
final RelOptHiveTable tab = (RelOptHiveTable) tableAccessRel.getTable();
final String qualifiedName = tab.getHiveTableMD().getCompleteName();
final List<FieldSchema> allCols = tab.getHiveTableMD().getAllCols();
final boolean insideView = tableAccessRel.isInsideView();
fieldsUsed.asList().stream()
.filter(idx -> idx < tab.getNoOfNonVirtualCols())
.forEach(idx -> {
if (insideView) {
columnAccessInfo.addIndirect(qualifiedName, allCols.get(idx).getName());
} else {
columnAccessInfo.add(qualifiedName, allCols.get(idx).getName());
}
});
}
if (fetchStats) {
fetchColStats(result.getKey(), tableAccessRel, fieldsUsed, extraFields);
}
return result;
}
private void fetchColStats(RelNode key, TableScan tableAccessRel, ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
final List<Integer> iRefSet = Lists.newArrayList();
if (key instanceof Project) {
final Project project = (Project) key;
for (RexNode rx : project.getProjects()) {
iRefSet.addAll(HiveCalciteUtil.getInputRefs(rx));
}
} else {
final int fieldCount = tableAccessRel.getRowType().getFieldCount();
if (fieldsUsed.equals(ImmutableBitSet.range(fieldCount)) && extraFields.isEmpty()) {
// get all cols
iRefSet.addAll(ImmutableBitSet.range(fieldCount).asList());
}
}
//Remove any virtual cols
if (tableAccessRel instanceof HiveTableScan) {
iRefSet.removeAll(((HiveTableScan)tableAccessRel).getVirtualCols());
}
if (!iRefSet.isEmpty()) {
final RelOptTable table = tableAccessRel.getTable();
if (table instanceof RelOptHiveTable) {
((RelOptHiveTable) table).getColStat(iRefSet, true);
LOG.debug("Got col stats for {} in {}", iRefSet,
tableAccessRel.getTable().getQualifiedName());
}
}
}
protected TrimResult result(RelNode r, final Mapping mapping) {
return new TrimResult(r, mapping);
}
/**
* Variant of {@link #trimFields(RelNode, ImmutableBitSet, Set)} for {@link HiveTableFunctionScan}.
* Copied {@link org.apache.calcite.sql2rel.RelFieldTrimmer#trimFields(
* org.apache.calcite.rel.logical.LogicalTableFunctionScan, ImmutableBitSet, Set)}
* and replaced <code>tabFun</code> to {@link HiveTableFunctionScan}.
* Proper fix would be implement this in calcite.
*/
public TrimResult trimFields(
HiveTableFunctionScan tabFun,
ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
final RelDataType rowType = tabFun.getRowType();
final int fieldCount = rowType.getFieldCount();
final List<RelNode> newInputs = new ArrayList<>();
for (RelNode input : tabFun.getInputs()) {
final int inputFieldCount = input.getRowType().getFieldCount();
ImmutableBitSet inputFieldsUsed = ImmutableBitSet.range(inputFieldCount);
// Create input with trimmed columns.
final Set<RelDataTypeField> inputExtraFields =
Collections.emptySet();
TrimResult trimResult =
trimChildRestore(
tabFun, input, inputFieldsUsed, inputExtraFields);
assert trimResult.right.isIdentity();
newInputs.add(trimResult.left);
}
TableFunctionScan newTabFun = tabFun;
if (!tabFun.getInputs().equals(newInputs)) {
newTabFun = tabFun.copy(tabFun.getTraitSet(), newInputs,
tabFun.getCall(), tabFun.getElementType(), tabFun.getRowType(),
tabFun.getColumnMappings());
}
assert newTabFun.getClass() == tabFun.getClass();
// Always project all fields.
Mapping mapping = Mappings.createIdentity(fieldCount);
return result(newTabFun, mapping);
}
/**
* This method can be called to pre-register all the classes that may be
* visited during the planning phase.
*/
protected void register(List<Class<? extends RelNode>> nodeClasses) throws Throwable {
this.trimFieldsDispatcher.register(nodeClasses);
}
/**
* This method can be called at startup time to pre-register all the
* Hive classes that may be visited during the planning phase.
*/
public static void initializeFieldTrimmerClass(List<Class<? extends RelNode>> nodeClasses) {
try {
FIELD_TRIMMER_STATS.register(nodeClasses);
FIELD_TRIMMER_NO_STATS.register(nodeClasses);
} catch (Throwable t) {
// LOG it but do not fail
LOG.warn("Error initializing field trimmer instance", t);
}
}
public TrimResult trimFields(
HiveSortExchange exchange,
ImmutableBitSet fieldsUsed,
Set<RelDataTypeField> extraFields) {
final RelDataType rowType = exchange.getRowType();
final int fieldCount = rowType.getFieldCount();
final RelCollation collation = exchange.getCollation();
final RelDistribution distribution = exchange.getDistribution();
final RelNode input = exchange.getInput();
// We use the fields used by the consumer, plus any fields used as exchange
// keys.
final ImmutableBitSet.Builder inputFieldsUsed = fieldsUsed.rebuild();
for (RelFieldCollation field : collation.getFieldCollations()) {
inputFieldsUsed.set(field.getFieldIndex());
}
for (int keyIndex : distribution.getKeys()) {
inputFieldsUsed.set(keyIndex);
}
// Create input with trimmed columns.
final Set<RelDataTypeField> inputExtraFields = Collections.emptySet();
TrimResult trimResult =
trimChild(exchange, input, inputFieldsUsed.build(), inputExtraFields);
RelNode newInput = trimResult.left;
final Mapping inputMapping = trimResult.right;
// If the input is unchanged, and we need to project all columns,
// there's nothing we can do.
if (newInput == input
&& inputMapping.isIdentity()
&& fieldsUsed.cardinality() == fieldCount) {
return result(exchange, Mappings.createIdentity(fieldCount));
}
final RelBuilder relBuilder = REL_BUILDER.get();
relBuilder.push(newInput);
RelCollation newCollation = RexUtil.apply(inputMapping, collation);
RelDistribution newDistribution = distribution.apply(inputMapping);
relBuilder.sortExchange(newDistribution, newCollation);
return result(relBuilder.build(), inputMapping);
}
}
|
apache/hudi | 35,145 | hudi-common/src/test/java/org/apache/hudi/internal/schema/utils/TestAvroSchemaEvolutionUtils.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.internal.schema.utils;
import org.apache.hudi.avro.HoodieAvroUtils;
import org.apache.hudi.common.testutils.SchemaTestUtil;
import org.apache.hudi.exception.HoodieNullSchemaTypeException;
import org.apache.hudi.internal.schema.InternalSchema;
import org.apache.hudi.internal.schema.InternalSchemaBuilder;
import org.apache.hudi.internal.schema.Type;
import org.apache.hudi.internal.schema.Types;
import org.apache.hudi.internal.schema.action.TableChanges;
import org.apache.hudi.internal.schema.convert.AvroInternalSchemaConverter;
import org.apache.avro.JsonProperties;
import org.apache.avro.LogicalTypes;
import org.apache.avro.Schema;
import org.apache.avro.SchemaBuilder;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests {@link AvroSchemaEvolutionUtils}.
*/
public class TestAvroSchemaEvolutionUtils {
String schemaStr = "{\"type\":\"record\",\"name\":\"newTableName\",\"fields\":[{\"name\":\"id\",\"type\":\"int\"},{\"name\":\"data\","
+ "\"type\":[\"null\",\"string\"],\"default\":null},{\"name\":\"preferences\",\"type\":[\"null\","
+ "{\"type\":\"record\",\"name\":\"preferences\",\"namespace\":\"newTableName\",\"fields\":[{\"name\":\"feature1\","
+ "\"type\":\"boolean\"},{\"name\":\"feature2\",\"type\":[\"null\",\"boolean\"],\"default\":null}]}],"
+ "\"default\":null},{\"name\":\"locations\",\"type\":{\"type\":\"map\",\"values\":{\"type\":\"record\","
+ "\"name\":\"locations\",\"namespace\":\"newTableName\",\"fields\":[{\"name\":\"lat\",\"type\":\"float\"},{\"name\":\"long\","
+ "\"type\":\"float\"}]}}},{\"name\":\"points\",\"type\":[\"null\",{\"type\":\"array\",\"items\":[\"null\","
+ "{\"type\":\"record\",\"name\":\"points\",\"namespace\":\"newTableName\",\"fields\":[{\"name\":\"x\",\"type\":\"long\"},"
+ "{\"name\":\"y\",\"type\":\"long\"}]}]}],\"default\":null},{\"name\":\"doubles\",\"type\":{\"type\":\"array\",\"items\":\"double\"}},"
+ "{\"name\":\"properties\",\"type\":[\"null\",{\"type\":\"map\",\"values\":[\"null\",\"string\"]}],\"default\":null}]}";
@Test
public void testPrimitiveTypes() {
Schema[] avroPrimitives = new Schema[] {
Schema.create(Schema.Type.BOOLEAN),
Schema.create(Schema.Type.INT),
Schema.create(Schema.Type.LONG),
Schema.create(Schema.Type.FLOAT),
Schema.create(Schema.Type.DOUBLE),
LogicalTypes.date().addToSchema(Schema.create(Schema.Type.INT)),
LogicalTypes.timeMicros().addToSchema(Schema.create(Schema.Type.LONG)),
LogicalTypes.timestampMicros().addToSchema(Schema.create(Schema.Type.LONG)),
Schema.create(Schema.Type.STRING),
LogicalTypes.uuid().addToSchema(Schema.createFixed("t1.fixed", null, null, 16)),
Schema.createFixed("t1.fixed", null, null, 12),
Schema.create(Schema.Type.BYTES),
LogicalTypes.decimal(9, 4).addToSchema(Schema.createFixed("t1.fixed", null, null, 4))};
Type[] primitiveTypes = new Type[] {
Types.BooleanType.get(),
Types.IntType.get(),
Types.LongType.get(),
Types.FloatType.get(),
Types.DoubleType.get(),
Types.DateType.get(),
Types.TimeType.get(),
Types.TimestampType.get(),
Types.StringType.get(),
Types.UUIDType.get(),
Types.FixedType.getFixed(12),
Types.BinaryType.get(),
Types.DecimalType.get(9, 4)
};
for (int i = 0; i < primitiveTypes.length; i++) {
Type convertPrimitiveResult = AvroInternalSchemaConverter.convertToField(avroPrimitives[i]);
Assertions.assertEquals(convertPrimitiveResult, primitiveTypes[i]);
Schema convertResult = AvroInternalSchemaConverter.convert(primitiveTypes[i], "t1");
Assertions.assertEquals(convertResult, avroPrimitives[i]);
}
}
@Test
public void testRecordAndPrimitiveTypes() {
Types.RecordType record = Types.RecordType.get(Arrays.asList(new Types.Field[] {
Types.Field.get(0, "bool", Types.BooleanType.get()),
Types.Field.get(1, "int", Types.IntType.get()),
Types.Field.get(2, "long", Types.LongType.get()),
Types.Field.get(3, "float", Types.FloatType.get()),
Types.Field.get(4, "double", Types.DoubleType.get()),
Types.Field.get(5, "date", Types.DateType.get()),
Types.Field.get(6, "time", Types.TimeType.get()),
Types.Field.get(7, "timestamp", Types.TimestampType.get()),
Types.Field.get(8, "string", Types.StringType.get()),
Types.Field.get(9, "uuid", Types.UUIDType.get()),
Types.Field.get(10, "fixed", Types.FixedType.getFixed(10)),
Types.Field.get(11, "binary", Types.BinaryType.get()),
Types.Field.get(12, "decimal", Types.DecimalType.get(10, 2))
}));
Schema schema = create("t1",
new Schema.Field("bool", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.BOOLEAN)), null, JsonProperties.NULL_VALUE),
new Schema.Field("int", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.INT)), null, JsonProperties.NULL_VALUE),
new Schema.Field("long", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.LONG)), null, JsonProperties.NULL_VALUE),
new Schema.Field("float", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.FLOAT)), null, JsonProperties.NULL_VALUE),
new Schema.Field("double", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.DOUBLE)), null, JsonProperties.NULL_VALUE),
new Schema.Field("date", AvroInternalSchemaConverter.nullableSchema(LogicalTypes.date().addToSchema(Schema.create(Schema.Type.INT))), null, JsonProperties.NULL_VALUE),
new Schema.Field("time", AvroInternalSchemaConverter.nullableSchema(LogicalTypes.timeMicros().addToSchema(Schema.create(Schema.Type.LONG))), null, JsonProperties.NULL_VALUE),
new Schema.Field("timestamp", AvroInternalSchemaConverter.nullableSchema(LogicalTypes.timestampMicros().addToSchema(Schema.create(Schema.Type.LONG))), null, JsonProperties.NULL_VALUE),
new Schema.Field("string", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.STRING)), null, JsonProperties.NULL_VALUE),
new Schema.Field("uuid", AvroInternalSchemaConverter.nullableSchema(LogicalTypes.uuid().addToSchema(Schema.createFixed("t1.uuid.fixed", null, null, 16))), null, JsonProperties.NULL_VALUE),
new Schema.Field("fixed", AvroInternalSchemaConverter.nullableSchema(Schema.createFixed("t1.fixed.fixed", null, null, 10)), null, JsonProperties.NULL_VALUE),
new Schema.Field("binary", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.BYTES)), null, JsonProperties.NULL_VALUE),
new Schema.Field("decimal", AvroInternalSchemaConverter.nullableSchema(LogicalTypes.decimal(10, 2)
.addToSchema(Schema.createFixed("t1.decimal.fixed", null, null, 5))), null, JsonProperties.NULL_VALUE));
Schema convertedSchema = AvroInternalSchemaConverter.convert(record, "t1");
Assertions.assertEquals(convertedSchema, schema);
Types.RecordType convertedRecord = AvroInternalSchemaConverter.convert(schema).getRecord();
Assertions.assertEquals(convertedRecord, record);
}
private Schema create(String name, Schema.Field... fields) {
return Schema.createRecord(name, null, null, false, Arrays.asList(fields));
}
@Test
public void testArrayType() {
Type arrayNestRecordType = Types.ArrayType.get(0, false,
Types.RecordType.get(Arrays.asList(Types.Field.get(1, false, "a", Types.FloatType.get()),
Types.Field.get(2, false, "b", Types.FloatType.get()))));
Schema schema = SchemaBuilder.array().items(create("t1",
new Schema.Field("a", Schema.create(Schema.Type.FLOAT), null, null),
new Schema.Field("b", Schema.create(Schema.Type.FLOAT), null, null)));
Schema convertedSchema = AvroInternalSchemaConverter.convert(arrayNestRecordType, "t1");
Assertions.assertEquals(convertedSchema, schema);
Types.ArrayType convertedRecord = (Types.ArrayType) AvroInternalSchemaConverter.convertToField(schema);
Assertions.assertEquals(convertedRecord, arrayNestRecordType);
}
@Test
public void testComplexConvert() {
Schema schema = new Schema.Parser().parse(schemaStr);
Types.RecordType recordType = Types.RecordType.get(Types.Field.get(0, false, "id", Types.IntType.get()),
Types.Field.get(1, true, "data", Types.StringType.get()),
Types.Field.get(2, true, "preferences",
Types.RecordType.get(Types.Field.get(7, false, "feature1",
Types.BooleanType.get()), Types.Field.get(8, true, "feature2", Types.BooleanType.get()))),
Types.Field.get(3, false, "locations", Types.MapType.get(9, 10, Types.StringType.get(),
Types.RecordType.get(Types.Field.get(11, false, "lat", Types.FloatType.get()), Types.Field.get(12, false, "long", Types.FloatType.get())), false)),
Types.Field.get(4, true, "points", Types.ArrayType.get(13, true,
Types.RecordType.get(Types.Field.get(14, false, "x", Types.LongType.get()), Types.Field.get(15, false, "y", Types.LongType.get())))),
Types.Field.get(5, false, "doubles", Types.ArrayType.get(16, false, Types.DoubleType.get())),
Types.Field.get(6, true, "properties", Types.MapType.get(17, 18, Types.StringType.get(), Types.StringType.get()))
);
InternalSchema internalSchema = new InternalSchema(recordType);
Type convertRecord = AvroInternalSchemaConverter.convert(schema).getRecord();
Assertions.assertEquals(convertRecord, internalSchema.getRecord());
Assertions.assertEquals(schema, AvroInternalSchemaConverter.convert(internalSchema, "newTableName"));
}
@Test
public void testNullFieldType() {
Schema schema = create("t1",
new Schema.Field("nullField", Schema.create(Schema.Type.NULL), null, JsonProperties.NULL_VALUE));
Throwable t = assertThrows(HoodieNullSchemaTypeException.class,
() -> AvroInternalSchemaConverter.convert(schema));
assertTrue(t.getMessage().contains("'t1.nullField'"));
Schema schemaArray = create("t2",
new Schema.Field("nullArray", Schema.createArray(Schema.create(Schema.Type.NULL)), null, null));
t = assertThrows(HoodieNullSchemaTypeException.class,
() -> AvroInternalSchemaConverter.convert(schemaArray));
assertTrue(t.getMessage().contains("'t2.nullArray.element'"));
Schema schemaMap = create("t3",
new Schema.Field("nullMap", Schema.createMap(Schema.create(Schema.Type.NULL)), null, null));
t = assertThrows(HoodieNullSchemaTypeException.class,
() -> AvroInternalSchemaConverter.convert(schemaMap));
assertTrue(t.getMessage().contains("'t3.nullMap.value'"));
Schema schemaComplex = create("t4",
new Schema.Field("complexField", Schema.createMap(
create("nestedStruct",
new Schema.Field("nestedArray", Schema.createArray(Schema.createMap(Schema.create(Schema.Type.NULL))),
null, null))), null, null));
t = assertThrows(HoodieNullSchemaTypeException.class,
() -> AvroInternalSchemaConverter.convert(schemaComplex));
assertTrue(t.getMessage().contains("'t4.nestedStruct.nestedArray.element.value'"));
}
@Test
public void testRefreshNewId() {
Types.RecordType record = Types.RecordType.get(Types.Field.get(0, false, "id", Types.IntType.get()),
Types.Field.get(1, true, "data", Types.StringType.get()),
Types.Field.get(2, true, "preferences",
Types.RecordType.get(Types.Field.get(4, false, "feature1",
Types.BooleanType.get()), Types.Field.get(5, true, "feature2", Types.BooleanType.get()))),
Types.Field.get(3, false, "locations", Types.MapType.get(6, 7, Types.StringType.get(),
Types.RecordType.get(Types.Field.get(8, false, "lat", Types.FloatType.get()), Types.Field.get(9, false, "long", Types.FloatType.get())), false))
);
AtomicInteger newId = new AtomicInteger(100);
Types.RecordType recordWithNewId = (Types.RecordType) InternalSchemaBuilder.getBuilder().refreshNewId(record, newId);
Types.RecordType newRecord = Types.RecordType.get(Types.Field.get(100, false, "id", Types.IntType.get()),
Types.Field.get(101, true, "data", Types.StringType.get()),
Types.Field.get(102, true, "preferences",
Types.RecordType.get(Types.Field.get(104, false, "feature1",
Types.BooleanType.get()), Types.Field.get(105, true, "feature2", Types.BooleanType.get()))),
Types.Field.get(103, false, "locations", Types.MapType.get(106, 107, Types.StringType.get(),
Types.RecordType.get(Types.Field.get(108, false, "lat", Types.FloatType.get()), Types.Field.get(109, false, "long", Types.FloatType.get())), false))
);
Assertions.assertEquals(newRecord, recordWithNewId);
}
@Test
public void testFixNullOrdering() {
Schema schema = SchemaTestUtil.getSchemaFromResource(TestAvroSchemaEvolutionUtils.class, "/nullWrong.avsc");
Schema expectedSchema = SchemaTestUtil.getSchemaFromResource(TestAvroSchemaEvolutionUtils.class, "/nullRight.avsc");
Assertions.assertEquals(expectedSchema, AvroInternalSchemaConverter.fixNullOrdering(schema));
Assertions.assertEquals(expectedSchema, AvroInternalSchemaConverter.fixNullOrdering(expectedSchema));
}
@Test
public void testFixNullOrderingSameSchemaCheck() {
Schema schema = SchemaTestUtil.getSchemaFromResource(TestAvroSchemaEvolutionUtils.class, "/source_evolved.avsc");
Assertions.assertEquals(schema, AvroInternalSchemaConverter.fixNullOrdering(schema));
}
public enum Enum {
ENUM1, ENUM2
}
/**
* test record data type changes.
* int => long/float/double/string
* long => float/double/string
* float => double/String
* double => String/Decimal
* Decimal => Decimal/String
* String => date/decimal
* date => String
* enum => String
*/
@Test
public void testReWriteRecordWithTypeChanged() {
String enumSchema = "{\"type\":\"enum\",\"name\":\"Enum\",\"namespace\":\"org.apache.hudi.internal.schema.utils.TestAvroSchemaEvolutionUtils\",\"symbols\":[\"ENUM1\",\"ENUM2\"]}";
Schema avroSchema = new Schema.Parser().parse("{\"type\":\"record\",\"name\":\"h0_record\",\"namespace\":\"hoodie.h0\",\"fields\""
+ ":[{\"name\":\"id\",\"type\":[\"null\",\"int\"],\"default\":null},"
+ "{\"name\":\"comb\",\"type\":[\"null\",\"int\"],\"default\":null},"
+ "{\"name\":\"com1\",\"type\":[\"null\",\"int\"],\"default\":null},"
+ "{\"name\":\"col0\",\"type\":[\"null\",\"int\"],\"default\":null},"
+ "{\"name\":\"col1\",\"type\":[\"null\",\"long\"],\"default\":null},"
+ "{\"name\":\"col11\",\"type\":[\"null\",\"long\"],\"default\":null},"
+ "{\"name\":\"col12\",\"type\":[\"null\",\"long\"],\"default\":null},"
+ "{\"name\":\"col2\",\"type\":[\"null\",\"float\"],\"default\":null},"
+ "{\"name\":\"col21\",\"type\":[\"null\",\"float\"],\"default\":null},"
+ "{\"name\":\"col3\",\"type\":[\"null\",\"double\"],\"default\":null},"
+ "{\"name\":\"col31\",\"type\":[\"null\",\"double\"],\"default\":null},"
+ "{\"name\":\"col4\",\"type\":[\"null\",{\"type\":\"fixed\",\"name\":\"fixed\",\"namespace\":\"hoodie.h0.h0_record.col4\","
+ "\"size\":5,\"logicalType\":\"decimal\",\"precision\":10,\"scale\":4}],\"default\":null},"
+ "{\"name\":\"col41\",\"type\":[\"null\",{\"type\":\"fixed\",\"name\":\"fixed\",\"namespace\":\"hoodie.h0.h0_record.col41\","
+ "\"size\":5,\"logicalType\":\"decimal\",\"precision\":10,\"scale\":4}],\"default\":null},"
+ "{\"name\":\"col5\",\"type\":[\"null\",\"string\"],\"default\":null},"
+ "{\"name\":\"col51\",\"type\":[\"null\",\"string\"],\"default\":null},"
+ "{\"name\":\"col6\",\"type\":[\"null\",{\"type\":\"int\",\"logicalType\":\"date\"}],\"default\":null},"
+ "{\"name\":\"col7\",\"type\":[\"null\",{\"type\":\"long\",\"logicalType\":\"timestamp-micros\"}],\"default\":null},"
+ "{\"name\":\"col8\",\"type\":[\"null\",\"boolean\"],\"default\":null},"
+ "{\"name\":\"col9\",\"type\":[\"null\",\"bytes\"],\"default\":null},{\"name\":\"par\",\"type\":[\"null\",{\"type\":\"int\",\"logicalType\":\"date\"}],\"default\":null},"
+ "{\"name\":\"enum\",\"type\":[\"null\"," + enumSchema + "],\"default\":null}"
+ "]}");
// create a test record with avroSchema
GenericData.Record avroRecord = new GenericData.Record(avroSchema);
avroRecord.put("id", 1);
avroRecord.put("comb", 100);
avroRecord.put("com1", -100);
avroRecord.put("col0", 256);
avroRecord.put("col1", 1000L);
avroRecord.put("col11", -100L);
avroRecord.put("col12", 2000L);
avroRecord.put("col2", -5.001f);
avroRecord.put("col21", 5.001f);
avroRecord.put("col3", 12.999d);
avroRecord.put("col31", 9999.999d);
Schema currentDecimalType = avroSchema.getField("col4").schema().getTypes().get(1);
BigDecimal bd = new BigDecimal("123.456").setScale(((LogicalTypes.Decimal) currentDecimalType.getLogicalType()).getScale());
avroRecord.put("col4", HoodieAvroUtils.DECIMAL_CONVERSION.toFixed(bd, currentDecimalType, currentDecimalType.getLogicalType()));
Schema currentDecimalType1 = avroSchema.getField("col41").schema().getTypes().get(1);
BigDecimal bd1 = new BigDecimal("7890.456").setScale(((LogicalTypes.Decimal) currentDecimalType1.getLogicalType()).getScale());
avroRecord.put("col41", HoodieAvroUtils.DECIMAL_CONVERSION.toFixed(bd1, currentDecimalType1, currentDecimalType1.getLogicalType()));
avroRecord.put("col5", "2011-01-01");
avroRecord.put("col51", "199.342");
avroRecord.put("col6", 18987);
avroRecord.put("col7", 1640491505000000L);
avroRecord.put("col8", false);
ByteBuffer bb = ByteBuffer.wrap(new byte[] {97, 48, 53});
avroRecord.put("col9", bb);
avroRecord.put("enum", new GenericData.EnumSymbol(new Schema.Parser().parse(enumSchema), Enum.ENUM1));
Assertions.assertEquals(GenericData.get().validate(avroSchema, avroRecord), true);
InternalSchema internalSchema = AvroInternalSchemaConverter.convert(avroSchema);
// do change type operation
TableChanges.ColumnUpdateChange updateChange = TableChanges.ColumnUpdateChange.get(internalSchema);
updateChange
.updateColumnType("id", Types.LongType.get())
.updateColumnType("comb", Types.FloatType.get())
.updateColumnType("com1", Types.DoubleType.get())
.updateColumnType("col0", Types.StringType.get())
.updateColumnType("col1", Types.FloatType.get())
.updateColumnType("col11", Types.DoubleType.get())
.updateColumnType("col12", Types.StringType.get())
.updateColumnType("col2", Types.DoubleType.get())
.updateColumnType("col21", Types.StringType.get())
.updateColumnType("col3", Types.StringType.get())
.updateColumnType("col31", Types.DecimalType.get(18, 9))
.updateColumnType("col4", Types.DecimalType.get(18, 9))
.updateColumnType("col41", Types.StringType.get())
.updateColumnType("col5", Types.DateType.get())
.updateColumnType("col51", Types.DecimalType.get(18, 9))
.updateColumnType("col6", Types.StringType.get())
.updateColumnType("enum", Types.StringType.get());
InternalSchema newSchema = SchemaChangeUtils.applyTableChanges2Schema(internalSchema, updateChange);
Schema newAvroSchema = AvroInternalSchemaConverter.convert(newSchema, avroSchema.getFullName());
GenericRecord newRecord = HoodieAvroUtils.rewriteRecordWithNewSchema(avroRecord, newAvroSchema, Collections.emptyMap());
Assertions.assertEquals("ENUM1", newRecord.get("enum"));
Assertions.assertEquals(GenericData.get().validate(newAvroSchema, newRecord), true);
}
@Test
public void testReWriteNestRecord() {
Types.RecordType record = Types.RecordType.get(Types.Field.get(0, false, "id", Types.IntType.get()),
Types.Field.get(1, true, "data", Types.StringType.get()),
Types.Field.get(2, true, "preferences",
Types.RecordType.get(Types.Field.get(5, false, "feature1",
Types.BooleanType.get()), Types.Field.get(6, true, "feature2", Types.BooleanType.get()))),
Types.Field.get(3, false,"doubles", Types.ArrayType.get(7, false, Types.DoubleType.get())),
Types.Field.get(4, false, "locations", Types.MapType.get(8, 9, Types.StringType.get(),
Types.RecordType.get(Types.Field.get(10, false, "lat", Types.FloatType.get()), Types.Field.get(11, false, "long", Types.FloatType.get())), false))
);
Schema schema = AvroInternalSchemaConverter.convert(record, "test1");
GenericData.Record avroRecord = new GenericData.Record(schema);
GenericData.get().validate(schema, avroRecord);
avroRecord.put("id", 2);
avroRecord.put("data", "xs");
// fill record type
GenericData.Record preferencesRecord = new GenericData.Record(AvroInternalSchemaConverter.convert(record.fieldType("preferences"), "test1.preferences"));
preferencesRecord.put("feature1", false);
preferencesRecord.put("feature2", true);
Assertions.assertEquals(GenericData.get().validate(AvroInternalSchemaConverter.convert(record.fieldType("preferences"), "test1.preferences"), preferencesRecord), true);
avroRecord.put("preferences", preferencesRecord);
// fill mapType
Map<String, GenericData.Record> locations = new HashMap<>();
Schema mapSchema = AvroInternalSchemaConverter.convert(((Types.MapType)record.fieldByNameCaseInsensitive("locations").type()).valueType(), "test1.locations");
GenericData.Record locationsValue = new GenericData.Record(mapSchema);
locationsValue.put("lat", 1.2f);
locationsValue.put("long", 1.4f);
GenericData.Record locationsValue1 = new GenericData.Record(mapSchema);
locationsValue1.put("lat", 2.2f);
locationsValue1.put("long", 2.4f);
locations.put("key1", locationsValue);
locations.put("key2", locationsValue1);
avroRecord.put("locations", locations);
List<Double> doubles = new ArrayList<>();
doubles.add(2.0d);
doubles.add(3.0d);
avroRecord.put("doubles", doubles);
// do check
Assertions.assertTrue(GenericData.get().validate(schema, avroRecord));
// create newSchema
Types.RecordType newRecord = Types.RecordType.get(
Types.Field.get(0, false, "id", Types.IntType.get()),
Types.Field.get(1, true, "data", Types.StringType.get()),
Types.Field.get(2, true, "preferences",
Types.RecordType.get(
Types.Field.get(5, false, "feature1", Types.BooleanType.get()),
Types.Field.get(5, true, "featurex", Types.BooleanType.get()),
Types.Field.get(6, true, "feature2", Types.BooleanType.get()))),
Types.Field.get(3, false,"doubles", Types.ArrayType.get(7, false, Types.DoubleType.get())),
Types.Field.get(4, false, "locations", Types.MapType.get(8, 9, Types.StringType.get(),
Types.RecordType.get(
Types.Field.get(10, true, "laty", Types.FloatType.get()),
Types.Field.get(11, false, "long", Types.FloatType.get())), false)
)
);
Schema newAvroSchema = AvroInternalSchemaConverter.convert(newRecord, schema.getName());
GenericRecord newAvroRecord = HoodieAvroUtils.rewriteRecordWithNewSchema(avroRecord, newAvroSchema, Collections.emptyMap());
// test the correctly of rewrite
Assertions.assertEquals(GenericData.get().validate(newAvroSchema, newAvroRecord), true);
// test rewrite with rename
InternalSchema internalSchema = AvroInternalSchemaConverter.convert(schema);
// do change rename operation
TableChanges.ColumnUpdateChange updateChange = TableChanges.ColumnUpdateChange.get(internalSchema);
updateChange
.renameColumn("id", "idx")
.renameColumn("data", "datax")
.renameColumn("preferences.feature1", "f1")
.renameColumn("preferences.feature2", "f2")
.renameColumn("locations.value.lat", "lt");
InternalSchema internalSchemaRename = SchemaChangeUtils.applyTableChanges2Schema(internalSchema, updateChange);
Schema avroSchemaRename = AvroInternalSchemaConverter.convert(internalSchemaRename, schema.getFullName());
Map<String, String> renameCols = InternalSchemaUtils.collectRenameCols(internalSchema, internalSchemaRename);
GenericRecord avroRecordRename = HoodieAvroUtils.rewriteRecordWithNewSchema(avroRecord, avroSchemaRename, renameCols);
// test the correctly of rewrite
Assertions.assertEquals(GenericData.get().validate(avroSchemaRename, avroRecordRename), true);
}
@Test
public void testEvolutionSchemaFromNewAvroSchema() {
Types.RecordType oldRecord = Types.RecordType.get(
Types.Field.get(0, false, "id", Types.IntType.get()),
Types.Field.get(1, true, "data", Types.StringType.get()),
Types.Field.get(2, true, "preferences",
Types.RecordType.get(
Types.Field.get(5, false, "feature1", Types.BooleanType.get()),
Types.Field.get(6, true, "featurex", Types.BooleanType.get()),
Types.Field.get(7, true, "feature2", Types.BooleanType.get()))),
Types.Field.get(3, false,"doubles", Types.ArrayType.get(8, false, Types.DoubleType.get())),
Types.Field.get(4, false, "locations", Types.MapType.get(9, 10, Types.StringType.get(),
Types.RecordType.get(
Types.Field.get(11, false, "laty", Types.FloatType.get()),
Types.Field.get(12, false, "long", Types.FloatType.get())), false)
)
);
InternalSchema oldSchema = new InternalSchema(oldRecord);
Types.RecordType evolvedRecord = Types.RecordType.get(
Types.Field.get(0, false, "id", Types.IntType.get()),
Types.Field.get(1, true, "data", Types.StringType.get()),
Types.Field.get(2, true, "preferences",
Types.RecordType.get(
Types.Field.get(5, false, "feature1", Types.BooleanType.get()),
Types.Field.get(5, true, "featurex", Types.BooleanType.get()),
Types.Field.get(6, true, "feature2", Types.BooleanType.get()),
Types.Field.get(5, true, "feature3", Types.BooleanType.get()))),
Types.Field.get(3, false,"doubles", Types.ArrayType.get(7, false, Types.DoubleType.get())),
Types.Field.get(4, false, "locations", Types.MapType.get(8, 9, Types.StringType.get(),
Types.RecordType.get(
Types.Field.get(10, false, "laty", Types.FloatType.get()),
Types.Field.get(11, false, "long", Types.FloatType.get())), false)
),
Types.Field.get(0, false, "add1", Types.IntType.get()),
Types.Field.get(2, true, "addStruct",
Types.RecordType.get(
Types.Field.get(5, false, "nest1", Types.BooleanType.get()),
Types.Field.get(5, true, "nest2", Types.BooleanType.get())))
);
evolvedRecord = (Types.RecordType)InternalSchemaBuilder.getBuilder().refreshNewId(evolvedRecord, new AtomicInteger(0));
Schema evolvedAvroSchema = AvroInternalSchemaConverter.convert(evolvedRecord, "test1");
InternalSchema result = AvroSchemaEvolutionUtils.reconcileSchema(evolvedAvroSchema, oldSchema, false);
Types.RecordType checkedRecord = Types.RecordType.get(
Types.Field.get(0, false, "id", Types.IntType.get()),
Types.Field.get(1, true, "data", Types.StringType.get()),
Types.Field.get(2, true, "preferences",
Types.RecordType.get(
Types.Field.get(5, false, "feature1", Types.BooleanType.get()),
Types.Field.get(6, true, "featurex", Types.BooleanType.get()),
Types.Field.get(7, true, "feature2", Types.BooleanType.get()),
Types.Field.get(17, true, "feature3", Types.BooleanType.get()))),
Types.Field.get(3, false,"doubles", Types.ArrayType.get(8, false, Types.DoubleType.get())),
Types.Field.get(4, false, "locations", Types.MapType.get(9, 10, Types.StringType.get(),
Types.RecordType.get(
Types.Field.get(11, false, "laty", Types.FloatType.get()),
Types.Field.get(12, false, "long", Types.FloatType.get())), false)
),
Types.Field.get(13, true, "add1", Types.IntType.get()),
Types.Field.get(14, true, "addStruct",
Types.RecordType.get(
Types.Field.get(15, false, "nest1", Types.BooleanType.get()),
Types.Field.get(16, true, "nest2", Types.BooleanType.get())))
);
Assertions.assertEquals(result.getRecord(), checkedRecord);
}
@Test
public void testReconcileSchema() {
// simple schema test
// a: boolean, b: int, c: long, d: date
Schema schema = create("simple",
new Schema.Field("a", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.BOOLEAN)), null, JsonProperties.NULL_VALUE),
new Schema.Field("b", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.INT)), null, JsonProperties.NULL_VALUE),
new Schema.Field("c", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.LONG)), null, JsonProperties.NULL_VALUE),
new Schema.Field("d", AvroInternalSchemaConverter.nullableSchema(LogicalTypes.date().addToSchema(Schema.create(Schema.Type.INT))), null, JsonProperties.NULL_VALUE));
// a: boolean, c: long, c_1: long, d: date
Schema incomingSchema = create("simpleIncoming",
new Schema.Field("a", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.BOOLEAN)), null, JsonProperties.NULL_VALUE),
new Schema.Field("a1", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.LONG)), null, JsonProperties.NULL_VALUE),
new Schema.Field("c", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.LONG)), null, JsonProperties.NULL_VALUE),
new Schema.Field("c1", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.LONG)), null, JsonProperties.NULL_VALUE),
new Schema.Field("c2", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.LONG)), null, JsonProperties.NULL_VALUE),
new Schema.Field("d", AvroInternalSchemaConverter.nullableSchema(LogicalTypes.date().addToSchema(Schema.create(Schema.Type.INT))), null, JsonProperties.NULL_VALUE),
new Schema.Field("d1", AvroInternalSchemaConverter.nullableSchema(LogicalTypes.date().addToSchema(Schema.create(Schema.Type.INT))), null, JsonProperties.NULL_VALUE),
new Schema.Field("d2", AvroInternalSchemaConverter.nullableSchema(LogicalTypes.date().addToSchema(Schema.create(Schema.Type.INT))), null, JsonProperties.NULL_VALUE));
Schema simpleCheckSchema = new Schema.Parser().parse("{\"type\":\"record\",\"name\":\"simple\",\"fields\":[{\"name\":\"a\",\"type\":[\"null\",\"boolean\"],\"default\":null},"
+ "{\"name\":\"b\",\"type\":[\"null\",\"int\"],\"default\":null},"
+ "{\"name\":\"c\",\"type\":[\"null\",\"long\"],\"default\":null},"
+ "{\"name\":\"d\",\"type\":[\"null\",{\"type\":\"int\",\"logicalType\":\"date\"}],\"default\":null},"
+ "{\"name\":\"a1\",\"type\":[\"null\",\"long\"],\"default\":null},"
+ "{\"name\":\"c1\",\"type\":[\"null\",\"long\"],\"default\":null},{\"name\":\"c2\",\"type\":[\"null\",\"long\"],\"default\":null},"
+ "{\"name\":\"d1\",\"type\":[\"null\",{\"type\":\"int\",\"logicalType\":\"date\"}],\"default\":null},"
+ "{\"name\":\"d2\",\"type\":[\"null\",{\"type\":\"int\",\"logicalType\":\"date\"}],\"default\":null}]}");
Schema simpleReconcileSchema = AvroInternalSchemaConverter.convert(AvroSchemaEvolutionUtils
.reconcileSchema(incomingSchema, AvroInternalSchemaConverter.convert(schema), false), "schemaNameFallback");
Assertions.assertEquals(simpleCheckSchema, simpleReconcileSchema);
}
@Test
public void testNotEvolveSchemaIfReconciledSchemaUnchanged() {
// a: boolean, c: long, c_1: long, d: date
Schema oldSchema = create("simple",
new Schema.Field("a", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.BOOLEAN)), null, JsonProperties.NULL_VALUE),
new Schema.Field("b", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.INT)), null, JsonProperties.NULL_VALUE),
new Schema.Field("c", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.LONG)), null, JsonProperties.NULL_VALUE),
new Schema.Field("d", AvroInternalSchemaConverter.nullableSchema(LogicalTypes.date().addToSchema(Schema.create(Schema.Type.INT))), null, JsonProperties.NULL_VALUE));
// incoming schema is part of old schema
// a: boolean, b: int, c: long
Schema incomingSchema = create("simple",
new Schema.Field("a", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.BOOLEAN)), null, JsonProperties.NULL_VALUE),
new Schema.Field("b", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.INT)), null, JsonProperties.NULL_VALUE),
new Schema.Field("c", AvroInternalSchemaConverter.nullableSchema(Schema.create(Schema.Type.LONG)), null, JsonProperties.NULL_VALUE));
InternalSchema oldInternalSchema = AvroInternalSchemaConverter.convert(oldSchema);
// set a non-default schema id for old table schema, e.g., 2.
oldInternalSchema.setSchemaId(2);
InternalSchema evolvedSchema = AvroSchemaEvolutionUtils.reconcileSchema(incomingSchema, oldInternalSchema, false);
// the evolved schema should be the old table schema, since there is no type change at all.
Assertions.assertEquals(oldInternalSchema, evolvedSchema);
}
}
|
googleapis/google-cloud-java | 36,380 | java-service-management/proto-google-cloud-service-management-v1/src/main/java/com/google/api/servicemanagement/v1/ListServicesRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/servicemanagement/v1/servicemanager.proto
// Protobuf Java Version: 3.25.8
package com.google.api.servicemanagement.v1;
/**
*
*
* <pre>
* Request message for `ListServices` method.
* </pre>
*
* Protobuf type {@code google.api.servicemanagement.v1.ListServicesRequest}
*/
public final class ListServicesRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.api.servicemanagement.v1.ListServicesRequest)
ListServicesRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListServicesRequest.newBuilder() to construct.
private ListServicesRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListServicesRequest() {
producerProjectId_ = "";
pageToken_ = "";
consumerId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListServicesRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.api.servicemanagement.v1.ServiceManagerProto
.internal_static_google_api_servicemanagement_v1_ListServicesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.api.servicemanagement.v1.ServiceManagerProto
.internal_static_google_api_servicemanagement_v1_ListServicesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.api.servicemanagement.v1.ListServicesRequest.class,
com.google.api.servicemanagement.v1.ListServicesRequest.Builder.class);
}
public static final int PRODUCER_PROJECT_ID_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object producerProjectId_ = "";
/**
*
*
* <pre>
* Include services produced by the specified project.
* </pre>
*
* <code>string producer_project_id = 1;</code>
*
* @return The producerProjectId.
*/
@java.lang.Override
public java.lang.String getProducerProjectId() {
java.lang.Object ref = producerProjectId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
producerProjectId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Include services produced by the specified project.
* </pre>
*
* <code>string producer_project_id = 1;</code>
*
* @return The bytes for producerProjectId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getProducerProjectIdBytes() {
java.lang.Object ref = producerProjectId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
producerProjectId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 5;
private int pageSize_ = 0;
/**
*
*
* <pre>
* The max number of items to include in the response list. Page size is 50
* if not specified. Maximum value is 500.
* </pre>
*
* <code>int32 page_size = 5;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 6;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Token identifying which result to start with; returned by a previous list
* call.
* </pre>
*
* <code>string page_token = 6;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Token identifying which result to start with; returned by a previous list
* call.
* </pre>
*
* <code>string page_token = 6;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CONSUMER_ID_FIELD_NUMBER = 7;
@SuppressWarnings("serial")
private volatile java.lang.Object consumerId_ = "";
/**
*
*
* <pre>
* Include services consumed by the specified consumer.
*
* The Google Service Management implementation accepts the following
* forms:
* - project:<project_id>
* </pre>
*
* <code>string consumer_id = 7 [deprecated = true];</code>
*
* @deprecated google.api.servicemanagement.v1.ListServicesRequest.consumer_id is deprecated. See
* google/api/servicemanagement/v1/servicemanager.proto;l=278
* @return The consumerId.
*/
@java.lang.Override
@java.lang.Deprecated
public java.lang.String getConsumerId() {
java.lang.Object ref = consumerId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
consumerId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Include services consumed by the specified consumer.
*
* The Google Service Management implementation accepts the following
* forms:
* - project:<project_id>
* </pre>
*
* <code>string consumer_id = 7 [deprecated = true];</code>
*
* @deprecated google.api.servicemanagement.v1.ListServicesRequest.consumer_id is deprecated. See
* google/api/servicemanagement/v1/servicemanager.proto;l=278
* @return The bytes for consumerId.
*/
@java.lang.Override
@java.lang.Deprecated
public com.google.protobuf.ByteString getConsumerIdBytes() {
java.lang.Object ref = consumerId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
consumerId_ = 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(producerProjectId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, producerProjectId_);
}
if (pageSize_ != 0) {
output.writeInt32(5, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 6, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(consumerId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 7, consumerId_);
}
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(producerProjectId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, producerProjectId_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(5, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(consumerId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(7, consumerId_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.api.servicemanagement.v1.ListServicesRequest)) {
return super.equals(obj);
}
com.google.api.servicemanagement.v1.ListServicesRequest other =
(com.google.api.servicemanagement.v1.ListServicesRequest) obj;
if (!getProducerProjectId().equals(other.getProducerProjectId())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getConsumerId().equals(other.getConsumerId())) 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) + PRODUCER_PROJECT_ID_FIELD_NUMBER;
hash = (53 * hash) + getProducerProjectId().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) + CONSUMER_ID_FIELD_NUMBER;
hash = (53 * hash) + getConsumerId().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.api.servicemanagement.v1.ListServicesRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.servicemanagement.v1.ListServicesRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.api.servicemanagement.v1.ListServicesRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.servicemanagement.v1.ListServicesRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.api.servicemanagement.v1.ListServicesRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.servicemanagement.v1.ListServicesRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.api.servicemanagement.v1.ListServicesRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.api.servicemanagement.v1.ListServicesRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.api.servicemanagement.v1.ListServicesRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.api.servicemanagement.v1.ListServicesRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.api.servicemanagement.v1.ListServicesRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.api.servicemanagement.v1.ListServicesRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.api.servicemanagement.v1.ListServicesRequest 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 `ListServices` method.
* </pre>
*
* Protobuf type {@code google.api.servicemanagement.v1.ListServicesRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.api.servicemanagement.v1.ListServicesRequest)
com.google.api.servicemanagement.v1.ListServicesRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.api.servicemanagement.v1.ServiceManagerProto
.internal_static_google_api_servicemanagement_v1_ListServicesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.api.servicemanagement.v1.ServiceManagerProto
.internal_static_google_api_servicemanagement_v1_ListServicesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.api.servicemanagement.v1.ListServicesRequest.class,
com.google.api.servicemanagement.v1.ListServicesRequest.Builder.class);
}
// Construct using com.google.api.servicemanagement.v1.ListServicesRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
producerProjectId_ = "";
pageSize_ = 0;
pageToken_ = "";
consumerId_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.api.servicemanagement.v1.ServiceManagerProto
.internal_static_google_api_servicemanagement_v1_ListServicesRequest_descriptor;
}
@java.lang.Override
public com.google.api.servicemanagement.v1.ListServicesRequest getDefaultInstanceForType() {
return com.google.api.servicemanagement.v1.ListServicesRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.api.servicemanagement.v1.ListServicesRequest build() {
com.google.api.servicemanagement.v1.ListServicesRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.api.servicemanagement.v1.ListServicesRequest buildPartial() {
com.google.api.servicemanagement.v1.ListServicesRequest result =
new com.google.api.servicemanagement.v1.ListServicesRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.api.servicemanagement.v1.ListServicesRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.producerProjectId_ = producerProjectId_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.consumerId_ = consumerId_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.api.servicemanagement.v1.ListServicesRequest) {
return mergeFrom((com.google.api.servicemanagement.v1.ListServicesRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.api.servicemanagement.v1.ListServicesRequest other) {
if (other == com.google.api.servicemanagement.v1.ListServicesRequest.getDefaultInstance())
return this;
if (!other.getProducerProjectId().isEmpty()) {
producerProjectId_ = other.producerProjectId_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getConsumerId().isEmpty()) {
consumerId_ = other.consumerId_;
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:
{
producerProjectId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 40:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 40
case 50:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 50
case 58:
{
consumerId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 58
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 producerProjectId_ = "";
/**
*
*
* <pre>
* Include services produced by the specified project.
* </pre>
*
* <code>string producer_project_id = 1;</code>
*
* @return The producerProjectId.
*/
public java.lang.String getProducerProjectId() {
java.lang.Object ref = producerProjectId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
producerProjectId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Include services produced by the specified project.
* </pre>
*
* <code>string producer_project_id = 1;</code>
*
* @return The bytes for producerProjectId.
*/
public com.google.protobuf.ByteString getProducerProjectIdBytes() {
java.lang.Object ref = producerProjectId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
producerProjectId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Include services produced by the specified project.
* </pre>
*
* <code>string producer_project_id = 1;</code>
*
* @param value The producerProjectId to set.
* @return This builder for chaining.
*/
public Builder setProducerProjectId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
producerProjectId_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Include services produced by the specified project.
* </pre>
*
* <code>string producer_project_id = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearProducerProjectId() {
producerProjectId_ = getDefaultInstance().getProducerProjectId();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Include services produced by the specified project.
* </pre>
*
* <code>string producer_project_id = 1;</code>
*
* @param value The bytes for producerProjectId to set.
* @return This builder for chaining.
*/
public Builder setProducerProjectIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
producerProjectId_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* The max number of items to include in the response list. Page size is 50
* if not specified. Maximum value is 500.
* </pre>
*
* <code>int32 page_size = 5;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* The max number of items to include in the response list. Page size is 50
* if not specified. Maximum value is 500.
* </pre>
*
* <code>int32 page_size = 5;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The max number of items to include in the response list. Page size is 50
* if not specified. Maximum value is 500.
* </pre>
*
* <code>int32 page_size = 5;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Token identifying which result to start with; returned by a previous list
* call.
* </pre>
*
* <code>string page_token = 6;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Token identifying which result to start with; returned by a previous list
* call.
* </pre>
*
* <code>string page_token = 6;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Token identifying which result to start with; returned by a previous list
* call.
* </pre>
*
* <code>string page_token = 6;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Token identifying which result to start with; returned by a previous list
* call.
* </pre>
*
* <code>string page_token = 6;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Token identifying which result to start with; returned by a previous list
* call.
* </pre>
*
* <code>string page_token = 6;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object consumerId_ = "";
/**
*
*
* <pre>
* Include services consumed by the specified consumer.
*
* The Google Service Management implementation accepts the following
* forms:
* - project:<project_id>
* </pre>
*
* <code>string consumer_id = 7 [deprecated = true];</code>
*
* @deprecated google.api.servicemanagement.v1.ListServicesRequest.consumer_id is deprecated.
* See google/api/servicemanagement/v1/servicemanager.proto;l=278
* @return The consumerId.
*/
@java.lang.Deprecated
public java.lang.String getConsumerId() {
java.lang.Object ref = consumerId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
consumerId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Include services consumed by the specified consumer.
*
* The Google Service Management implementation accepts the following
* forms:
* - project:<project_id>
* </pre>
*
* <code>string consumer_id = 7 [deprecated = true];</code>
*
* @deprecated google.api.servicemanagement.v1.ListServicesRequest.consumer_id is deprecated.
* See google/api/servicemanagement/v1/servicemanager.proto;l=278
* @return The bytes for consumerId.
*/
@java.lang.Deprecated
public com.google.protobuf.ByteString getConsumerIdBytes() {
java.lang.Object ref = consumerId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
consumerId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Include services consumed by the specified consumer.
*
* The Google Service Management implementation accepts the following
* forms:
* - project:<project_id>
* </pre>
*
* <code>string consumer_id = 7 [deprecated = true];</code>
*
* @deprecated google.api.servicemanagement.v1.ListServicesRequest.consumer_id is deprecated.
* See google/api/servicemanagement/v1/servicemanager.proto;l=278
* @param value The consumerId to set.
* @return This builder for chaining.
*/
@java.lang.Deprecated
public Builder setConsumerId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
consumerId_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Include services consumed by the specified consumer.
*
* The Google Service Management implementation accepts the following
* forms:
* - project:<project_id>
* </pre>
*
* <code>string consumer_id = 7 [deprecated = true];</code>
*
* @deprecated google.api.servicemanagement.v1.ListServicesRequest.consumer_id is deprecated.
* See google/api/servicemanagement/v1/servicemanager.proto;l=278
* @return This builder for chaining.
*/
@java.lang.Deprecated
public Builder clearConsumerId() {
consumerId_ = getDefaultInstance().getConsumerId();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Include services consumed by the specified consumer.
*
* The Google Service Management implementation accepts the following
* forms:
* - project:<project_id>
* </pre>
*
* <code>string consumer_id = 7 [deprecated = true];</code>
*
* @deprecated google.api.servicemanagement.v1.ListServicesRequest.consumer_id is deprecated.
* See google/api/servicemanagement/v1/servicemanager.proto;l=278
* @param value The bytes for consumerId to set.
* @return This builder for chaining.
*/
@java.lang.Deprecated
public Builder setConsumerIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
consumerId_ = 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.api.servicemanagement.v1.ListServicesRequest)
}
// @@protoc_insertion_point(class_scope:google.api.servicemanagement.v1.ListServicesRequest)
private static final com.google.api.servicemanagement.v1.ListServicesRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.api.servicemanagement.v1.ListServicesRequest();
}
public static com.google.api.servicemanagement.v1.ListServicesRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListServicesRequest> PARSER =
new com.google.protobuf.AbstractParser<ListServicesRequest>() {
@java.lang.Override
public ListServicesRequest 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<ListServicesRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListServicesRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.api.servicemanagement.v1.ListServicesRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/hudi | 36,378 | hudi-client/hudi-client-common/src/test/java/org/apache/hudi/table/upgrade/TestEightToNineUpgradeHandler.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.upgrade;
import org.apache.hudi.common.config.ConfigProperty;
import org.apache.hudi.common.engine.HoodieEngineContext;
import org.apache.hudi.common.model.AWSDmsAvroPayload;
import org.apache.hudi.common.model.DefaultHoodieRecordPayload;
import org.apache.hudi.common.model.EventTimeAvroPayload;
import org.apache.hudi.common.model.HoodieIndexDefinition;
import org.apache.hudi.common.model.HoodieIndexMetadata;
import org.apache.hudi.common.model.HoodieRecordMerger;
import org.apache.hudi.common.model.HoodieTableType;
import org.apache.hudi.common.model.OverwriteNonDefaultsWithLatestAvroPayload;
import org.apache.hudi.common.model.OverwriteWithLatestAvroPayload;
import org.apache.hudi.common.model.PartialUpdateAvroPayload;
import org.apache.hudi.common.model.debezium.MySqlDebeziumAvroPayload;
import org.apache.hudi.common.model.debezium.PostgresDebeziumAvroPayload;
import org.apache.hudi.common.table.HoodieTableConfig;
import org.apache.hudi.common.table.HoodieTableMetaClient;
import org.apache.hudi.common.table.HoodieTableVersion;
import org.apache.hudi.common.table.PartialUpdateMode;
import org.apache.hudi.common.util.Option;
import org.apache.hudi.common.util.StringUtils;
import org.apache.hudi.config.HoodieWriteConfig;
import org.apache.hudi.metadata.HoodieIndexVersion;
import org.apache.hudi.storage.HoodieStorage;
import org.apache.hudi.storage.StoragePath;
import org.apache.hudi.table.HoodieTable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.MockedStatic;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import static org.apache.hudi.common.config.RecordMergeMode.COMMIT_TIME_ORDERING;
import static org.apache.hudi.common.config.RecordMergeMode.EVENT_TIME_ORDERING;
import static org.apache.hudi.common.model.DefaultHoodieRecordPayload.DELETE_KEY;
import static org.apache.hudi.common.model.DefaultHoodieRecordPayload.DELETE_MARKER;
import static org.apache.hudi.common.model.debezium.DebeziumConstants.FLATTENED_FILE_COL_NAME;
import static org.apache.hudi.common.model.debezium.DebeziumConstants.FLATTENED_LSN_COL_NAME;
import static org.apache.hudi.common.model.debezium.DebeziumConstants.FLATTENED_POS_COL_NAME;
import static org.apache.hudi.common.table.HoodieTableConfig.DEBEZIUM_UNAVAILABLE_VALUE;
import static org.apache.hudi.common.table.HoodieTableConfig.LEGACY_PAYLOAD_CLASS_NAME;
import static org.apache.hudi.common.table.HoodieTableConfig.PARTIAL_UPDATE_MODE;
import static org.apache.hudi.common.table.HoodieTableConfig.PARTIAL_UPDATE_UNAVAILABLE_VALUE;
import static org.apache.hudi.common.table.HoodieTableConfig.PAYLOAD_CLASS_NAME;
import static org.apache.hudi.common.table.HoodieTableConfig.RECORD_MERGE_MODE;
import static org.apache.hudi.common.table.HoodieTableConfig.RECORD_MERGE_PROPERTY_PREFIX;
import static org.apache.hudi.common.table.HoodieTableConfig.RECORD_MERGE_STRATEGY_ID;
import static org.apache.hudi.common.table.PartialUpdateMode.FILL_UNAVAILABLE;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class TestEightToNineUpgradeHandler {
private final EightToNineUpgradeHandler handler = new EightToNineUpgradeHandler();
private final HoodieStorage storage = mock(HoodieStorage.class);
private final HoodieEngineContext context = mock(HoodieEngineContext.class);
private final HoodieTable table = mock(HoodieTable.class);
private final HoodieTableMetaClient metaClient = mock(HoodieTableMetaClient.class);
private final HoodieTableConfig tableConfig = mock(HoodieTableConfig.class);
private final SupportsUpgradeDowngrade upgradeDowngradeHelper =
mock(SupportsUpgradeDowngrade.class);
private final HoodieWriteConfig config = mock(HoodieWriteConfig.class);
private static final Map<ConfigProperty, String> DEFAULT_CONFIG_UPDATED = Collections.emptyMap();
private static final Set<ConfigProperty> DEFAULT_CONFIG_REMOVED = Collections.emptySet();
private static final UpgradeDowngrade.TableConfigChangeSet DEFAULT_UPGRADE_RESULT =
new UpgradeDowngrade.TableConfigChangeSet(DEFAULT_CONFIG_UPDATED, DEFAULT_CONFIG_REMOVED);
private static final String INSTANT_TIME = "20231201120000";
private StoragePath indexDefPath;
@TempDir
private Path tempDir;
@BeforeEach
public void setUp() throws IOException {
when(upgradeDowngradeHelper.getTable(any(), any())).thenReturn(table);
when(table.getMetaClient()).thenReturn(metaClient);
when(metaClient.getTableConfig()).thenReturn(tableConfig);
when(config.autoUpgrade()).thenReturn(true);
// Setup common mocks
when(upgradeDowngradeHelper.getTable(config, context)).thenReturn(table);
when(table.getMetaClient()).thenReturn(metaClient);
when(metaClient.getTableConfig()).thenReturn(tableConfig);
when(metaClient.getStorage()).thenReturn(storage);
when(tableConfig.getTableVersion()).thenReturn(HoodieTableVersion.EIGHT);
when(tableConfig.getOrderingFieldsStr()).thenReturn(Option.empty());
// Use a temp file for index definition path
indexDefPath = new StoragePath(tempDir.resolve("index.json").toString());
when(metaClient.getIndexDefinitionPath()).thenReturn(indexDefPath.toString());
// Mock storage methods for file creation
when(storage.exists(any(StoragePath.class))).thenReturn(false);
when(storage.createNewFile(any(StoragePath.class))).thenReturn(true);
// Mock create method to capture written content
ByteArrayOutputStream capturedContent = new ByteArrayOutputStream();
when(storage.create(any(StoragePath.class), anyBoolean())).thenReturn(capturedContent);
// Mock autoUpgrade to return true
when(config.autoUpgrade()).thenReturn(true);
}
static Stream<Arguments> payloadClassTestCases() {
return Stream.of(
Arguments.of(
DefaultHoodieRecordPayload.class.getName(),
"",
null,
null,
"DefaultHoodieRecordPayload"
),
Arguments.of(
EventTimeAvroPayload.class.getName(),
"",
EVENT_TIME_ORDERING.name(),
null,
"EventTimeAvroPayload"
),
Arguments.of(
OverwriteWithLatestAvroPayload.class.getName(),
"",
null,
null,
"OverwriteWithLatestAvroPayload"
),
Arguments.of(
AWSDmsAvroPayload.class.getName(),
RECORD_MERGE_PROPERTY_PREFIX + DELETE_KEY + "=Op,"
+ RECORD_MERGE_PROPERTY_PREFIX + DELETE_MARKER + "=D", // mergeProperties
COMMIT_TIME_ORDERING.name(),
null,
"AWSDmsAvroPayload"
),
Arguments.of(
PostgresDebeziumAvroPayload.class.getName(),
RECORD_MERGE_PROPERTY_PREFIX + PARTIAL_UPDATE_UNAVAILABLE_VALUE + "=" + DEBEZIUM_UNAVAILABLE_VALUE + ","
+ RECORD_MERGE_PROPERTY_PREFIX + DELETE_KEY + "=_change_operation_type,"
+ RECORD_MERGE_PROPERTY_PREFIX + DELETE_MARKER + "=d",
EVENT_TIME_ORDERING.name(),
FILL_UNAVAILABLE.name(),
"PostgresDebeziumAvroPayload"
),
Arguments.of(
PartialUpdateAvroPayload.class.getName(),
"",
EVENT_TIME_ORDERING.name(),
PartialUpdateMode.IGNORE_DEFAULTS.name(),
"PartialUpdateAvroPayload"
),
Arguments.of(
MySqlDebeziumAvroPayload.class.getName(),
RECORD_MERGE_PROPERTY_PREFIX + DELETE_KEY + "=_change_operation_type,"
+ RECORD_MERGE_PROPERTY_PREFIX + DELETE_MARKER + "=d",
EVENT_TIME_ORDERING.name(),
null,
"MySqlDebeziumAvroPayload"
),
Arguments.of(
OverwriteNonDefaultsWithLatestAvroPayload.class.getName(),
"",
COMMIT_TIME_ORDERING.name(),
PartialUpdateMode.IGNORE_DEFAULTS.name(),
"OverwriteNonDefaultsWithLatestAvroPayload"
)
);
}
@ParameterizedTest(name = "testUpgradeWith{4}")
@MethodSource("payloadClassTestCases")
void testUpgradeWithPayloadClass(String payloadClassName, String expectedMergeProperties,
String expectedRecordMergeMode, String expectedPartialUpdateMode,
String testName) {
try (org.mockito.MockedStatic<UpgradeDowngradeUtils> utilities =
org.mockito.Mockito.mockStatic(UpgradeDowngradeUtils.class)) {
utilities.when(() -> UpgradeDowngradeUtils.rollbackFailedWritesAndCompact(
any(), any(), any(), any(), anyBoolean(), any()))
.thenAnswer(invocation -> null);
when(tableConfig.getPayloadClass()).thenReturn(payloadClassName);
when(tableConfig.getTableType()).thenReturn(HoodieTableType.MERGE_ON_READ);
when(tableConfig.getRecordMergeStrategyId()).thenReturn(HoodieRecordMerger.CUSTOM_MERGE_STRATEGY_UUID);
when(metaClient.getIndexMetadata()).thenReturn(Option.empty());
UpgradeDowngrade.TableConfigChangeSet propertiesToHandle =
handler.upgrade(config, context, "anyInstant", upgradeDowngradeHelper);
Map<ConfigProperty, String> propertiesToAdd = propertiesToHandle.propertiesToUpdate();
Set<ConfigProperty> propertiesToRemove = propertiesToHandle.propertiesToDelete();
// Assert merge properties
if (!StringUtils.isNullOrEmpty(expectedMergeProperties)) {
String[] configs = expectedMergeProperties.split(",");
for (String config : configs) {
String[] kv = config.split("=");
boolean found = false;
for (Map.Entry<ConfigProperty, String> e : propertiesToAdd.entrySet()) {
if (e.getKey().key().equals(kv[0])) {
assertEquals(kv[1], e.getValue());
found = true;
}
}
assertTrue(found);
}
}
// Assert record merge mode
if (expectedRecordMergeMode == null) {
assertFalse(propertiesToAdd.containsKey(RECORD_MERGE_MODE));
} else {
assertTrue(propertiesToAdd.containsKey(RECORD_MERGE_MODE));
assertEquals(expectedRecordMergeMode, propertiesToAdd.get(RECORD_MERGE_MODE));
}
// Assert partial update mode
if (expectedPartialUpdateMode != null) {
assertTrue(propertiesToAdd.containsKey(PARTIAL_UPDATE_MODE));
assertEquals(expectedPartialUpdateMode, propertiesToAdd.get(PARTIAL_UPDATE_MODE));
} else {
assertFalse(propertiesToAdd.containsKey(PARTIAL_UPDATE_MODE));
}
// Assert payload class change
assertPayloadClassChange(propertiesToAdd, propertiesToRemove, payloadClassName);
}
}
@Test
void testUpgradeWithNoIndexMetadata() {
try (MockedStatic<UpgradeDowngradeUtils> mockedUtils = mockStatic(UpgradeDowngradeUtils.class)) {
// Mock the static method to do nothing - avoid NPE
mockedUtils.when(() -> UpgradeDowngradeUtils.rollbackFailedWritesAndCompact(
any(HoodieTable.class),
any(HoodieEngineContext.class),
any(HoodieWriteConfig.class),
any(SupportsUpgradeDowngrade.class),
anyBoolean(),
any(HoodieTableVersion.class)
)).thenAnswer(invocation -> null); // Do nothing
// Setup: No index metadata present
when(metaClient.getIndexMetadata()).thenReturn(Option.empty());
// Execute
UpgradeDowngrade.TableConfigChangeSet result =
handler.upgrade(config, context, INSTANT_TIME, upgradeDowngradeHelper);
// Verify
assertEquals(DEFAULT_UPGRADE_RESULT.propertiesToUpdate(), result.propertiesToUpdate());
assertEquals(
Collections.singleton(RECORD_MERGE_STRATEGY_ID), result.propertiesToDelete());
}
}
private void assertPayloadClassChange(Map<ConfigProperty, String> propertiesToAdd,
Set<ConfigProperty> propertiesToRemove,
String payloadClass) {
if (payloadClass.equals(MySqlDebeziumAvroPayload.class.getName()) || payloadClass.equals(PostgresDebeziumAvroPayload.class.getName())) {
assertEquals(3, propertiesToRemove.size());
assertTrue(propertiesToRemove.contains(HoodieTableConfig.PRECOMBINE_FIELD));
} else {
assertEquals(2, propertiesToRemove.size());
}
assertTrue(propertiesToRemove.contains(PAYLOAD_CLASS_NAME));
assertTrue(propertiesToRemove.contains(RECORD_MERGE_STRATEGY_ID));
assertTrue(propertiesToAdd.containsKey(LEGACY_PAYLOAD_CLASS_NAME));
assertEquals(
payloadClass,
propertiesToAdd.get(LEGACY_PAYLOAD_CLASS_NAME));
if (payloadClass.equals(MySqlDebeziumAvroPayload.class.getName())) {
assertTrue(propertiesToAdd.containsKey(HoodieTableConfig.ORDERING_FIELDS));
assertEquals(FLATTENED_FILE_COL_NAME + "," + FLATTENED_POS_COL_NAME, propertiesToAdd.get(HoodieTableConfig.ORDERING_FIELDS));
} else if (payloadClass.equals(PostgresDebeziumAvroPayload.class.getName())) {
assertEquals(FLATTENED_LSN_COL_NAME, propertiesToAdd.get(HoodieTableConfig.ORDERING_FIELDS));
}
}
@Test
void testUpgradeWithMissingIndexVersion() throws IOException {
try (MockedStatic<UpgradeDowngradeUtils> mockedUtils = mockStatic(UpgradeDowngradeUtils.class);
MockedStatic<HoodieTableMetaClient> mockedMetaClient = mockStatic(HoodieTableMetaClient.class)) {
// Mock the static method to do nothing - avoid NPE
mockedUtils.when(() -> UpgradeDowngradeUtils.rollbackFailedWritesAndCompact(
any(HoodieTable.class),
any(HoodieEngineContext.class),
any(HoodieWriteConfig.class),
any(SupportsUpgradeDowngrade.class),
anyBoolean(),
any(HoodieTableVersion.class)
)).thenAnswer(invocation -> null); // Do nothing
// Mock the writeIndexMetadataToStorage to call the real method
mockedMetaClient.when(() -> HoodieTableMetaClient.writeIndexMetadataToStorage(
any(),
any(String.class),
any(HoodieIndexMetadata.class),
any(HoodieTableVersion.class)
)).thenCallRealMethod();
// Setup: Index metadata present with missing versions
HoodieIndexMetadata indexMetadata = createIndexMetadataWithMissingVersions();
assertNull(indexMetadata.getIndexDefinitions().get("column_stats").getVersion());
assertNull(indexMetadata.getIndexDefinitions().get("secondary_index_idx_price").getVersion());
when(metaClient.getIndexMetadata()).thenReturn(Option.of(indexMetadata));
// Capture the output stream to verify written content
ByteArrayOutputStream capturedContent = new ByteArrayOutputStream();
when(storage.create(eq(indexDefPath), eq(true))).thenReturn(capturedContent);
// Execute
UpgradeDowngrade.TableConfigChangeSet result =
handler.upgrade(config, context, INSTANT_TIME, upgradeDowngradeHelper);
// Verify
assertEquals(DEFAULT_UPGRADE_RESULT.propertiesToUpdate(), result.propertiesToUpdate());
assertEquals(
Collections.singleton(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
result.propertiesToDelete());
// Verify storage methods were called correctly
// Note: createFileInPath directly calls create() when contentWriter is present
verify(storage).create(indexDefPath, true);
// Verify the written content by parsing the JSON and validating the object
String writtenJson = capturedContent.toString();
// Expected JSON for table version 8 with V1 versions
String expectedJson = "{\n"
+ " \"indexDefinitions\": {\n"
+ " \"column_stats\": {\n"
+ " \"indexName\": \"column_stats\",\n"
+ " \"indexType\": \"column_stats\",\n"
+ " \"indexFunction\": \"column_stats\",\n"
+ " \"sourceFields\": [\"field1\", \"field2\"],\n"
+ " \"indexOptions\": {},\n"
+ " \"version\": \"V1\"\n"
+ " },\n"
+ " \"secondary_index_idx_price\": {\n"
+ " \"indexName\": \"secondary_index_idx_price\",\n"
+ " \"indexType\": \"secondary_index\",\n"
+ " \"indexFunction\": \"identity\",\n"
+ " \"sourceFields\": [\"price\"],\n"
+ " \"indexOptions\": {},\n"
+ " \"version\": \"V1\"\n"
+ " }\n"
+ " }\n"
+ "}";
// Parse the written JSON and validate against expected
HoodieIndexMetadata writtenMetadata = HoodieIndexMetadata.fromJson(writtenJson);
HoodieIndexMetadata expectedMetadata = HoodieIndexMetadata.fromJson(expectedJson);
// Validate the parsed objects match
assertEquals(expectedMetadata.getIndexDefinitions().size(), writtenMetadata.getIndexDefinitions().size());
// Validate column_stats index
HoodieIndexDefinition writtenColumnStats = writtenMetadata.getIndexDefinitions().get("column_stats");
HoodieIndexDefinition expectedColumnStats = expectedMetadata.getIndexDefinitions().get("column_stats");
assertEquals(expectedColumnStats.getIndexName(), writtenColumnStats.getIndexName());
assertEquals(expectedColumnStats.getIndexType(), writtenColumnStats.getIndexType());
assertEquals(expectedColumnStats.getIndexFunction(), writtenColumnStats.getIndexFunction());
assertEquals(expectedColumnStats.getSourceFields(), writtenColumnStats.getSourceFields());
assertEquals(expectedColumnStats.getIndexOptions(), writtenColumnStats.getIndexOptions());
assertEquals(expectedColumnStats.getVersion(), writtenColumnStats.getVersion());
// Validate secondary_index_idx_price index
HoodieIndexDefinition writtenSecondaryIndex = writtenMetadata.getIndexDefinitions().get("secondary_index_idx_price");
HoodieIndexDefinition expectedSecondaryIndex = expectedMetadata.getIndexDefinitions().get("secondary_index_idx_price");
assertEquals(expectedSecondaryIndex.getIndexName(), writtenSecondaryIndex.getIndexName());
assertEquals(expectedSecondaryIndex.getIndexType(), writtenSecondaryIndex.getIndexType());
assertEquals(expectedSecondaryIndex.getIndexFunction(), writtenSecondaryIndex.getIndexFunction());
assertEquals(expectedSecondaryIndex.getSourceFields(), writtenSecondaryIndex.getSourceFields());
assertEquals(expectedSecondaryIndex.getIndexOptions(), writtenSecondaryIndex.getIndexOptions());
assertEquals(expectedSecondaryIndex.getVersion(), writtenSecondaryIndex.getVersion());
}
}
@Test
void testUpgradeWithIndexMetadataHavingVersions() {
try (MockedStatic<UpgradeDowngradeUtils> mockedUtils = mockStatic(UpgradeDowngradeUtils.class)) {
// Mock the static method to do nothing - avoid NPE
mockedUtils.when(() -> UpgradeDowngradeUtils.rollbackFailedWritesAndCompact(
any(HoodieTable.class),
any(HoodieEngineContext.class),
any(HoodieWriteConfig.class),
any(SupportsUpgradeDowngrade.class),
anyBoolean(),
any(HoodieTableVersion.class)
)).thenAnswer(invocation -> null); // Do nothing
// Setup: Index metadata present with existing versions
HoodieIndexMetadata indexMetadata = createIndexMetadataWithVersions();
// TODO: assert index defs of indexMetadata have version field
// Note: Since we can't import HoodieIndexVersion due to dependency issues,
// we'll skip this test for now and focus on testing the storage functionality
when(metaClient.getIndexMetadata()).thenReturn(Option.of(indexMetadata));
// Execute
UpgradeDowngrade.TableConfigChangeSet result =
handler.upgrade(config, context, INSTANT_TIME, upgradeDowngradeHelper);
// Verify
assertEquals(DEFAULT_UPGRADE_RESULT.propertiesToUpdate(), result.propertiesToUpdate());
assertEquals(
Collections.singleton(RECORD_MERGE_STRATEGY_ID), result.propertiesToDelete());
}
}
@Test
void testUpgradeWithEmptyIndexMetadata() {
try (MockedStatic<UpgradeDowngradeUtils> mockedUtils = mockStatic(UpgradeDowngradeUtils.class)) {
// Mock the static method to do nothing - avoid NPE
mockedUtils.when(() -> UpgradeDowngradeUtils.rollbackFailedWritesAndCompact(
any(HoodieTable.class),
any(HoodieEngineContext.class),
any(HoodieWriteConfig.class),
any(SupportsUpgradeDowngrade.class),
anyBoolean(),
any(HoodieTableVersion.class)
)).thenAnswer(invocation -> null); // Do nothing
// Setup: Empty index metadata (no index definitions)
HoodieIndexMetadata indexMetadata = new HoodieIndexMetadata();
when(metaClient.getIndexMetadata()).thenReturn(Option.of(indexMetadata));
// Execute
UpgradeDowngrade.TableConfigChangeSet result =
handler.upgrade(config, context, INSTANT_TIME, upgradeDowngradeHelper);
// Verify
assertEquals(DEFAULT_UPGRADE_RESULT.propertiesToUpdate(), result.propertiesToUpdate());
assertEquals(
Collections.singleton(RECORD_MERGE_STRATEGY_ID), result.propertiesToDelete());
}
}
@Test
void testUpgradeWithFileAlreadyExists() throws IOException {
try (MockedStatic<UpgradeDowngradeUtils> mockedUtils = mockStatic(UpgradeDowngradeUtils.class);
MockedStatic<HoodieTableMetaClient> mockedMetaClient = mockStatic(HoodieTableMetaClient.class)) {
// Mock the static method to do nothing - avoid NPE
mockedUtils.when(() -> UpgradeDowngradeUtils.rollbackFailedWritesAndCompact(
any(HoodieTable.class),
any(HoodieEngineContext.class),
any(HoodieWriteConfig.class),
any(SupportsUpgradeDowngrade.class),
anyBoolean(),
any(HoodieTableVersion.class)
)).thenAnswer(invocation -> null); // Do nothing
// Mock the writeIndexMetadataToStorage to call the real method
mockedMetaClient.when(() -> HoodieTableMetaClient.writeIndexMetadataToStorage(
any(),
any(String.class),
any(HoodieIndexMetadata.class),
any(HoodieTableVersion.class)
)).thenCallRealMethod();
// Setup: File already exists
HoodieIndexMetadata indexMetadata = createIndexMetadataWithMissingVersions();
when(metaClient.getIndexMetadata()).thenReturn(Option.of(indexMetadata));
when(storage.exists(indexDefPath)).thenReturn(true);
// Capture the output stream to verify written content
ByteArrayOutputStream capturedContent = new ByteArrayOutputStream();
when(storage.create(eq(indexDefPath), eq(true))).thenReturn(capturedContent);
// Execute
UpgradeDowngrade.TableConfigChangeSet result =
handler.upgrade(config, context, INSTANT_TIME, upgradeDowngradeHelper);
// Verify
assertEquals(DEFAULT_UPGRADE_RESULT.propertiesToUpdate(), result.propertiesToUpdate());
assertEquals(
Collections.singleton(HoodieTableConfig.RECORD_MERGE_STRATEGY_ID),
result.propertiesToDelete());
// Verify storage methods were called correctly
// Note: createFileInPath directly calls create() when contentWriter is present
verify(storage).create(indexDefPath, true);
// Verify the written content by parsing the JSON and validating the object
String writtenJson = capturedContent.toString();
// Expected JSON for table version 8 with V1 versions
String expectedJson = "{\n"
+ " \"indexDefinitions\": {\n"
+ " \"column_stats\": {\n"
+ " \"indexName\": \"column_stats\",\n"
+ " \"indexType\": \"column_stats\",\n"
+ " \"indexFunction\": \"column_stats\",\n"
+ " \"sourceFields\": [\"field1\", \"field2\"],\n"
+ " \"indexOptions\": {},\n"
+ " \"version\": \"V1\"\n"
+ " },\n"
+ " \"secondary_index_idx_price\": {\n"
+ " \"indexName\": \"secondary_index_idx_price\",\n"
+ " \"indexType\": \"secondary_index\",\n"
+ " \"indexFunction\": \"identity\",\n"
+ " \"sourceFields\": [\"price\"],\n"
+ " \"indexOptions\": {},\n"
+ " \"version\": \"V1\"\n"
+ " }\n"
+ " }\n"
+ "}";
// Parse the written JSON and validate against expected
HoodieIndexMetadata writtenMetadata = HoodieIndexMetadata.fromJson(writtenJson);
HoodieIndexMetadata expectedMetadata = HoodieIndexMetadata.fromJson(expectedJson);
// Validate the parsed objects match
assertEquals(expectedMetadata.getIndexDefinitions().size(), writtenMetadata.getIndexDefinitions().size());
// Validate column_stats index
HoodieIndexDefinition writtenColumnStats = writtenMetadata.getIndexDefinitions().get("column_stats");
HoodieIndexDefinition expectedColumnStats = expectedMetadata.getIndexDefinitions().get("column_stats");
assertEquals(expectedColumnStats.getIndexName(), writtenColumnStats.getIndexName());
assertEquals(expectedColumnStats.getIndexType(), writtenColumnStats.getIndexType());
assertEquals(expectedColumnStats.getIndexFunction(), writtenColumnStats.getIndexFunction());
assertEquals(expectedColumnStats.getSourceFields(), writtenColumnStats.getSourceFields());
assertEquals(expectedColumnStats.getIndexOptions(), writtenColumnStats.getIndexOptions());
assertEquals(expectedColumnStats.getVersion(), writtenColumnStats.getVersion());
// Validate secondary_index_idx_price index
HoodieIndexDefinition writtenSecondaryIndex = writtenMetadata.getIndexDefinitions().get("secondary_index_idx_price");
HoodieIndexDefinition expectedSecondaryIndex = expectedMetadata.getIndexDefinitions().get("secondary_index_idx_price");
assertEquals(expectedSecondaryIndex.getIndexName(), writtenSecondaryIndex.getIndexName());
assertEquals(expectedSecondaryIndex.getIndexType(), writtenSecondaryIndex.getIndexType());
assertEquals(expectedSecondaryIndex.getIndexFunction(), writtenSecondaryIndex.getIndexFunction());
assertEquals(expectedSecondaryIndex.getSourceFields(), writtenSecondaryIndex.getSourceFields());
assertEquals(expectedSecondaryIndex.getIndexOptions(), writtenSecondaryIndex.getIndexOptions());
assertEquals(expectedSecondaryIndex.getVersion(), writtenSecondaryIndex.getVersion());
}
}
/**
* Creates index metadata with missing version fields (simulating table version 8 scenario)
*/
private HoodieIndexMetadata createIndexMetadataWithMissingVersions() {
Map<String, HoodieIndexDefinition> indexDefinitions = new HashMap<>();
// Column stats index without version
HoodieIndexDefinition columnStatsDef = HoodieIndexDefinition.newBuilder()
.withIndexName("column_stats")
.withIndexType("column_stats")
.withIndexFunction("column_stats")
.withSourceFields(java.util.Arrays.asList("field1", "field2"))
.withIndexOptions(Collections.emptyMap())
.build();
// Secondary index without version
HoodieIndexDefinition secondaryIndexDef = HoodieIndexDefinition.newBuilder()
.withIndexName("secondary_index_idx_price")
.withIndexType("secondary_index")
.withIndexFunction("identity")
.withSourceFields(java.util.Arrays.asList("price"))
.withIndexOptions(Collections.emptyMap())
.build();
indexDefinitions.put("column_stats", columnStatsDef);
indexDefinitions.put("secondary_index_idx_price", secondaryIndexDef);
return new HoodieIndexMetadata(indexDefinitions);
}
/**
* Creates index metadata with existing version fields
*/
private HoodieIndexMetadata createIndexMetadataWithVersions() {
Map<String, HoodieIndexDefinition> indexDefinitions = new HashMap<>();
// Note: Since we can't import HoodieIndexVersion due to dependency issues,
// we'll create index definitions without version attributes for now
// Column stats index with version
HoodieIndexDefinition columnStatsDef = HoodieIndexDefinition.newBuilder()
.withIndexName("column_stats")
.withIndexType("column_stats")
.withIndexFunction("column_stats")
.withSourceFields(java.util.Arrays.asList("field1", "field2"))
.withIndexOptions(Collections.emptyMap())
.withVersion(HoodieIndexVersion.V1)
.build();
// Secondary index with version
HoodieIndexDefinition secondaryIndexDef = HoodieIndexDefinition.newBuilder()
.withIndexName("secondary_index_idx_price")
.withIndexType("secondary_index")
.withIndexFunction("identity")
.withSourceFields(java.util.Arrays.asList("price"))
.withIndexOptions(Collections.emptyMap())
.withVersion(HoodieIndexVersion.V1)
.build();
indexDefinitions.put("column_stats", columnStatsDef);
indexDefinitions.put("secondary_index_idx_price", secondaryIndexDef);
return new HoodieIndexMetadata(indexDefinitions);
}
@Test
void testPopulateIndexVersionIfMissing() {
try (MockedStatic<UpgradeDowngradeUtils> mockedUtils = mockStatic(UpgradeDowngradeUtils.class)) {
// Mock the static method to do nothing - avoid NPE
mockedUtils.when(() -> UpgradeDowngradeUtils.rollbackFailedWritesAndCompact(
any(HoodieTable.class),
any(HoodieEngineContext.class),
any(HoodieWriteConfig.class),
any(SupportsUpgradeDowngrade.class),
anyBoolean(),
any(HoodieTableVersion.class)
)).thenAnswer(invocation -> null); // Do nothing
// Test with table version 8 - should populate missing versions with V1
HoodieIndexMetadata indexMetadata = loadIndexDefFromResource("indexMissingVersion1.json");
// Verify initial state - no versions
assertNull(indexMetadata.getIndexDefinitions().get("column_stats").getVersion());
assertNull(indexMetadata.getIndexDefinitions().get("secondary_index_idx_price").getVersion());
// Apply the method
EightToNineUpgradeHandler.populateIndexVersionIfMissing(Option.of(indexMetadata));
// Verify versions are populated with V1
assertEquals(HoodieIndexVersion.V1, indexMetadata.getIndexDefinitions().get("column_stats").getVersion());
assertEquals(HoodieIndexVersion.V1, indexMetadata.getIndexDefinitions().get("secondary_index_idx_price").getVersion());
// Verify other fields remain unchanged
validateAllFieldsExcludingVersion(indexMetadata);
}
}
@Test
void testPopulateIndexVersionIfMissingWithMixedVersions() {
try (MockedStatic<UpgradeDowngradeUtils> mockedUtils = mockStatic(UpgradeDowngradeUtils.class)) {
// Mock the static method to do nothing - avoid NPE
mockedUtils.when(() -> UpgradeDowngradeUtils.rollbackFailedWritesAndCompact(
any(HoodieTable.class),
any(HoodieEngineContext.class),
any(HoodieWriteConfig.class),
any(SupportsUpgradeDowngrade.class),
anyBoolean(),
any(HoodieTableVersion.class)
)).thenAnswer(invocation -> null); // Do nothing
// Test with indexMissingVersion2.json which has some versions already set
HoodieIndexMetadata indexMetadata = loadIndexDefFromResource("indexMissingVersion2.json");
// Verify initial state - column_stats has no version, secondary_index has V2
assertNull(indexMetadata.getIndexDefinitions().get("column_stats").getVersion());
assertEquals(HoodieIndexVersion.V2, indexMetadata.getIndexDefinitions().get("secondary_index_idx_price").getVersion());
// Apply the method with table version 8
EightToNineUpgradeHandler.populateIndexVersionIfMissing(Option.of(indexMetadata));
// Verify column_stats gets V1, secondary_index remains V2 (since it already had a version)
assertEquals(HoodieIndexVersion.V1, indexMetadata.getIndexDefinitions().get("column_stats").getVersion());
assertEquals(HoodieIndexVersion.V2, indexMetadata.getIndexDefinitions().get("secondary_index_idx_price").getVersion());
}
}
@Test
void testPopulateIndexVersionIfMissingWithEmptyOption() {
try (MockedStatic<UpgradeDowngradeUtils> mockedUtils = mockStatic(UpgradeDowngradeUtils.class)) {
// Mock the static method to do nothing - avoid NPE
mockedUtils.when(() -> UpgradeDowngradeUtils.rollbackFailedWritesAndCompact(
any(HoodieTable.class),
any(HoodieEngineContext.class),
any(HoodieWriteConfig.class),
any(SupportsUpgradeDowngrade.class),
anyBoolean(),
any(HoodieTableVersion.class)
)).thenAnswer(invocation -> null); // Do nothing
// Test with empty option - should not throw exception
assertDoesNotThrow(() ->
EightToNineUpgradeHandler.populateIndexVersionIfMissing(Option.empty()));
}
}
private static HoodieIndexMetadata loadIndexDefFromResource(String resourceName) {
try {
String resourcePath = TestEightToNineUpgradeHandler.class.getClassLoader().getResource(resourceName).toString();
return HoodieIndexMetadata.fromJson(new String(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(new java.net.URI(resourcePath)))));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void validateAllFieldsExcludingVersion(HoodieIndexMetadata loadedDef) {
HoodieIndexDefinition colStatsDef = loadedDef.getIndexDefinitions().get("column_stats");
assertEquals("column_stats", colStatsDef.getIndexName());
assertEquals("column_stats", colStatsDef.getIndexType());
assertEquals("column_stats", colStatsDef.getIndexFunction());
assertEquals(Collections.emptyMap(), colStatsDef.getIndexOptions());
assertEquals(Arrays.asList(
"_hoodie_commit_time", "_hoodie_partition_path", "_hoodie_record_key", "key", "secKey", "partition", "intField",
"city", "textField1", "textField2", "textField3", "textField4", "decimalField", "longField", "incrLongField", "round"),
colStatsDef.getSourceFields());
HoodieIndexDefinition secIdxDef = loadedDef.getIndexDefinitions().get("secondary_index_idx_price");
assertEquals("secondary_index_idx_price", secIdxDef.getIndexName());
assertEquals("secondary_index", secIdxDef.getIndexType());
assertEquals("identity", secIdxDef.getIndexFunction());
assertEquals(Collections.singletonList("price"), secIdxDef.getSourceFields());
assertEquals(Collections.emptyMap(), secIdxDef.getIndexOptions());
}
}
|
googleapis/google-cloud-java | 36,618 | java-dialogflow/grpc-google-cloud-dialogflow-v2/src/main/java/com/google/cloud/dialogflow/v2/VersionsGrpc.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.v2;
import static io.grpc.MethodDescriptor.generateFullMethodName;
/**
*
*
* <pre>
* Service for managing [Versions][google.cloud.dialogflow.v2.Version].
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler",
comments = "Source: google/cloud/dialogflow/v2/version.proto")
@io.grpc.stub.annotations.GrpcGenerated
public final class VersionsGrpc {
private VersionsGrpc() {}
public static final java.lang.String SERVICE_NAME = "google.cloud.dialogflow.v2.Versions";
// Static method descriptors that strictly reflect the proto.
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2.ListVersionsRequest,
com.google.cloud.dialogflow.v2.ListVersionsResponse>
getListVersionsMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "ListVersions",
requestType = com.google.cloud.dialogflow.v2.ListVersionsRequest.class,
responseType = com.google.cloud.dialogflow.v2.ListVersionsResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2.ListVersionsRequest,
com.google.cloud.dialogflow.v2.ListVersionsResponse>
getListVersionsMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2.ListVersionsRequest,
com.google.cloud.dialogflow.v2.ListVersionsResponse>
getListVersionsMethod;
if ((getListVersionsMethod = VersionsGrpc.getListVersionsMethod) == null) {
synchronized (VersionsGrpc.class) {
if ((getListVersionsMethod = VersionsGrpc.getListVersionsMethod) == null) {
VersionsGrpc.getListVersionsMethod =
getListVersionsMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.v2.ListVersionsRequest,
com.google.cloud.dialogflow.v2.ListVersionsResponse>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "ListVersions"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2.ListVersionsRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2.ListVersionsResponse
.getDefaultInstance()))
.setSchemaDescriptor(new VersionsMethodDescriptorSupplier("ListVersions"))
.build();
}
}
}
return getListVersionsMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2.GetVersionRequest, com.google.cloud.dialogflow.v2.Version>
getGetVersionMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "GetVersion",
requestType = com.google.cloud.dialogflow.v2.GetVersionRequest.class,
responseType = com.google.cloud.dialogflow.v2.Version.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2.GetVersionRequest, com.google.cloud.dialogflow.v2.Version>
getGetVersionMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2.GetVersionRequest,
com.google.cloud.dialogflow.v2.Version>
getGetVersionMethod;
if ((getGetVersionMethod = VersionsGrpc.getGetVersionMethod) == null) {
synchronized (VersionsGrpc.class) {
if ((getGetVersionMethod = VersionsGrpc.getGetVersionMethod) == null) {
VersionsGrpc.getGetVersionMethod =
getGetVersionMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.v2.GetVersionRequest,
com.google.cloud.dialogflow.v2.Version>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetVersion"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2.GetVersionRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2.Version.getDefaultInstance()))
.setSchemaDescriptor(new VersionsMethodDescriptorSupplier("GetVersion"))
.build();
}
}
}
return getGetVersionMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2.CreateVersionRequest,
com.google.cloud.dialogflow.v2.Version>
getCreateVersionMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "CreateVersion",
requestType = com.google.cloud.dialogflow.v2.CreateVersionRequest.class,
responseType = com.google.cloud.dialogflow.v2.Version.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2.CreateVersionRequest,
com.google.cloud.dialogflow.v2.Version>
getCreateVersionMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2.CreateVersionRequest,
com.google.cloud.dialogflow.v2.Version>
getCreateVersionMethod;
if ((getCreateVersionMethod = VersionsGrpc.getCreateVersionMethod) == null) {
synchronized (VersionsGrpc.class) {
if ((getCreateVersionMethod = VersionsGrpc.getCreateVersionMethod) == null) {
VersionsGrpc.getCreateVersionMethod =
getCreateVersionMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.v2.CreateVersionRequest,
com.google.cloud.dialogflow.v2.Version>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "CreateVersion"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2.CreateVersionRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2.Version.getDefaultInstance()))
.setSchemaDescriptor(new VersionsMethodDescriptorSupplier("CreateVersion"))
.build();
}
}
}
return getCreateVersionMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2.UpdateVersionRequest,
com.google.cloud.dialogflow.v2.Version>
getUpdateVersionMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "UpdateVersion",
requestType = com.google.cloud.dialogflow.v2.UpdateVersionRequest.class,
responseType = com.google.cloud.dialogflow.v2.Version.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2.UpdateVersionRequest,
com.google.cloud.dialogflow.v2.Version>
getUpdateVersionMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2.UpdateVersionRequest,
com.google.cloud.dialogflow.v2.Version>
getUpdateVersionMethod;
if ((getUpdateVersionMethod = VersionsGrpc.getUpdateVersionMethod) == null) {
synchronized (VersionsGrpc.class) {
if ((getUpdateVersionMethod = VersionsGrpc.getUpdateVersionMethod) == null) {
VersionsGrpc.getUpdateVersionMethod =
getUpdateVersionMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.v2.UpdateVersionRequest,
com.google.cloud.dialogflow.v2.Version>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "UpdateVersion"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2.UpdateVersionRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2.Version.getDefaultInstance()))
.setSchemaDescriptor(new VersionsMethodDescriptorSupplier("UpdateVersion"))
.build();
}
}
}
return getUpdateVersionMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2.DeleteVersionRequest, com.google.protobuf.Empty>
getDeleteVersionMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "DeleteVersion",
requestType = com.google.cloud.dialogflow.v2.DeleteVersionRequest.class,
responseType = com.google.protobuf.Empty.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2.DeleteVersionRequest, com.google.protobuf.Empty>
getDeleteVersionMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2.DeleteVersionRequest, com.google.protobuf.Empty>
getDeleteVersionMethod;
if ((getDeleteVersionMethod = VersionsGrpc.getDeleteVersionMethod) == null) {
synchronized (VersionsGrpc.class) {
if ((getDeleteVersionMethod = VersionsGrpc.getDeleteVersionMethod) == null) {
VersionsGrpc.getDeleteVersionMethod =
getDeleteVersionMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.v2.DeleteVersionRequest,
com.google.protobuf.Empty>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "DeleteVersion"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2.DeleteVersionRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.protobuf.Empty.getDefaultInstance()))
.setSchemaDescriptor(new VersionsMethodDescriptorSupplier("DeleteVersion"))
.build();
}
}
}
return getDeleteVersionMethod;
}
/** Creates a new async stub that supports all call types for the service */
public static VersionsStub newStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<VersionsStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<VersionsStub>() {
@java.lang.Override
public VersionsStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new VersionsStub(channel, callOptions);
}
};
return VersionsStub.newStub(factory, channel);
}
/** Creates a new blocking-style stub that supports all types of calls on the service */
public static VersionsBlockingV2Stub newBlockingV2Stub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<VersionsBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<VersionsBlockingV2Stub>() {
@java.lang.Override
public VersionsBlockingV2Stub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new VersionsBlockingV2Stub(channel, callOptions);
}
};
return VersionsBlockingV2Stub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static VersionsBlockingStub newBlockingStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<VersionsBlockingStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<VersionsBlockingStub>() {
@java.lang.Override
public VersionsBlockingStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new VersionsBlockingStub(channel, callOptions);
}
};
return VersionsBlockingStub.newStub(factory, channel);
}
/** Creates a new ListenableFuture-style stub that supports unary calls on the service */
public static VersionsFutureStub newFutureStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<VersionsFutureStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<VersionsFutureStub>() {
@java.lang.Override
public VersionsFutureStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new VersionsFutureStub(channel, callOptions);
}
};
return VersionsFutureStub.newStub(factory, channel);
}
/**
*
*
* <pre>
* Service for managing [Versions][google.cloud.dialogflow.v2.Version].
* </pre>
*/
public interface AsyncService {
/**
*
*
* <pre>
* Returns the list of all versions of the specified agent.
* </pre>
*/
default void listVersions(
com.google.cloud.dialogflow.v2.ListVersionsRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2.ListVersionsResponse>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getListVersionsMethod(), responseObserver);
}
/**
*
*
* <pre>
* Retrieves the specified agent version.
* </pre>
*/
default void getVersion(
com.google.cloud.dialogflow.v2.GetVersionRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2.Version> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetVersionMethod(), responseObserver);
}
/**
*
*
* <pre>
* Creates an agent version.
* The new version points to the agent instance in the "default" environment.
* </pre>
*/
default void createVersion(
com.google.cloud.dialogflow.v2.CreateVersionRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2.Version> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getCreateVersionMethod(), responseObserver);
}
/**
*
*
* <pre>
* Updates the specified agent version.
* Note that this method does not allow you to update the state of the agent
* the given version points to. It allows you to update only mutable
* properties of the version resource.
* </pre>
*/
default void updateVersion(
com.google.cloud.dialogflow.v2.UpdateVersionRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2.Version> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getUpdateVersionMethod(), responseObserver);
}
/**
*
*
* <pre>
* Delete the specified agent version.
* </pre>
*/
default void deleteVersion(
com.google.cloud.dialogflow.v2.DeleteVersionRequest request,
io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getDeleteVersionMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service Versions.
*
* <pre>
* Service for managing [Versions][google.cloud.dialogflow.v2.Version].
* </pre>
*/
public abstract static class VersionsImplBase implements io.grpc.BindableService, AsyncService {
@java.lang.Override
public final io.grpc.ServerServiceDefinition bindService() {
return VersionsGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service Versions.
*
* <pre>
* Service for managing [Versions][google.cloud.dialogflow.v2.Version].
* </pre>
*/
public static final class VersionsStub extends io.grpc.stub.AbstractAsyncStub<VersionsStub> {
private VersionsStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected VersionsStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new VersionsStub(channel, callOptions);
}
/**
*
*
* <pre>
* Returns the list of all versions of the specified agent.
* </pre>
*/
public void listVersions(
com.google.cloud.dialogflow.v2.ListVersionsRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2.ListVersionsResponse>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getListVersionsMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Retrieves the specified agent version.
* </pre>
*/
public void getVersion(
com.google.cloud.dialogflow.v2.GetVersionRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2.Version> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getGetVersionMethod(), getCallOptions()), request, responseObserver);
}
/**
*
*
* <pre>
* Creates an agent version.
* The new version points to the agent instance in the "default" environment.
* </pre>
*/
public void createVersion(
com.google.cloud.dialogflow.v2.CreateVersionRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2.Version> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getCreateVersionMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Updates the specified agent version.
* Note that this method does not allow you to update the state of the agent
* the given version points to. It allows you to update only mutable
* properties of the version resource.
* </pre>
*/
public void updateVersion(
com.google.cloud.dialogflow.v2.UpdateVersionRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2.Version> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getUpdateVersionMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Delete the specified agent version.
* </pre>
*/
public void deleteVersion(
com.google.cloud.dialogflow.v2.DeleteVersionRequest request,
io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getDeleteVersionMethod(), getCallOptions()),
request,
responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service Versions.
*
* <pre>
* Service for managing [Versions][google.cloud.dialogflow.v2.Version].
* </pre>
*/
public static final class VersionsBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<VersionsBlockingV2Stub> {
private VersionsBlockingV2Stub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected VersionsBlockingV2Stub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new VersionsBlockingV2Stub(channel, callOptions);
}
/**
*
*
* <pre>
* Returns the list of all versions of the specified agent.
* </pre>
*/
public com.google.cloud.dialogflow.v2.ListVersionsResponse listVersions(
com.google.cloud.dialogflow.v2.ListVersionsRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getListVersionsMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Retrieves the specified agent version.
* </pre>
*/
public com.google.cloud.dialogflow.v2.Version getVersion(
com.google.cloud.dialogflow.v2.GetVersionRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetVersionMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Creates an agent version.
* The new version points to the agent instance in the "default" environment.
* </pre>
*/
public com.google.cloud.dialogflow.v2.Version createVersion(
com.google.cloud.dialogflow.v2.CreateVersionRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCreateVersionMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Updates the specified agent version.
* Note that this method does not allow you to update the state of the agent
* the given version points to. It allows you to update only mutable
* properties of the version resource.
* </pre>
*/
public com.google.cloud.dialogflow.v2.Version updateVersion(
com.google.cloud.dialogflow.v2.UpdateVersionRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUpdateVersionMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Delete the specified agent version.
* </pre>
*/
public com.google.protobuf.Empty deleteVersion(
com.google.cloud.dialogflow.v2.DeleteVersionRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getDeleteVersionMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do limited synchronous rpc calls to service Versions.
*
* <pre>
* Service for managing [Versions][google.cloud.dialogflow.v2.Version].
* </pre>
*/
public static final class VersionsBlockingStub
extends io.grpc.stub.AbstractBlockingStub<VersionsBlockingStub> {
private VersionsBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected VersionsBlockingStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new VersionsBlockingStub(channel, callOptions);
}
/**
*
*
* <pre>
* Returns the list of all versions of the specified agent.
* </pre>
*/
public com.google.cloud.dialogflow.v2.ListVersionsResponse listVersions(
com.google.cloud.dialogflow.v2.ListVersionsRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getListVersionsMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Retrieves the specified agent version.
* </pre>
*/
public com.google.cloud.dialogflow.v2.Version getVersion(
com.google.cloud.dialogflow.v2.GetVersionRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetVersionMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Creates an agent version.
* The new version points to the agent instance in the "default" environment.
* </pre>
*/
public com.google.cloud.dialogflow.v2.Version createVersion(
com.google.cloud.dialogflow.v2.CreateVersionRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCreateVersionMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Updates the specified agent version.
* Note that this method does not allow you to update the state of the agent
* the given version points to. It allows you to update only mutable
* properties of the version resource.
* </pre>
*/
public com.google.cloud.dialogflow.v2.Version updateVersion(
com.google.cloud.dialogflow.v2.UpdateVersionRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUpdateVersionMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Delete the specified agent version.
* </pre>
*/
public com.google.protobuf.Empty deleteVersion(
com.google.cloud.dialogflow.v2.DeleteVersionRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getDeleteVersionMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service Versions.
*
* <pre>
* Service for managing [Versions][google.cloud.dialogflow.v2.Version].
* </pre>
*/
public static final class VersionsFutureStub
extends io.grpc.stub.AbstractFutureStub<VersionsFutureStub> {
private VersionsFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected VersionsFutureStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new VersionsFutureStub(channel, callOptions);
}
/**
*
*
* <pre>
* Returns the list of all versions of the specified agent.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.dialogflow.v2.ListVersionsResponse>
listVersions(com.google.cloud.dialogflow.v2.ListVersionsRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getListVersionsMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Retrieves the specified agent version.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.dialogflow.v2.Version>
getVersion(com.google.cloud.dialogflow.v2.GetVersionRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getGetVersionMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Creates an agent version.
* The new version points to the agent instance in the "default" environment.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.dialogflow.v2.Version>
createVersion(com.google.cloud.dialogflow.v2.CreateVersionRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getCreateVersionMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Updates the specified agent version.
* Note that this method does not allow you to update the state of the agent
* the given version points to. It allows you to update only mutable
* properties of the version resource.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.dialogflow.v2.Version>
updateVersion(com.google.cloud.dialogflow.v2.UpdateVersionRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getUpdateVersionMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Delete the specified agent version.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.google.protobuf.Empty>
deleteVersion(com.google.cloud.dialogflow.v2.DeleteVersionRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getDeleteVersionMethod(), getCallOptions()), request);
}
}
private static final int METHODID_LIST_VERSIONS = 0;
private static final int METHODID_GET_VERSION = 1;
private static final int METHODID_CREATE_VERSION = 2;
private static final int METHODID_UPDATE_VERSION = 3;
private static final int METHODID_DELETE_VERSION = 4;
private static final class MethodHandlers<Req, Resp>
implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final AsyncService serviceImpl;
private final int methodId;
MethodHandlers(AsyncService serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_LIST_VERSIONS:
serviceImpl.listVersions(
(com.google.cloud.dialogflow.v2.ListVersionsRequest) request,
(io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2.ListVersionsResponse>)
responseObserver);
break;
case METHODID_GET_VERSION:
serviceImpl.getVersion(
(com.google.cloud.dialogflow.v2.GetVersionRequest) request,
(io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2.Version>)
responseObserver);
break;
case METHODID_CREATE_VERSION:
serviceImpl.createVersion(
(com.google.cloud.dialogflow.v2.CreateVersionRequest) request,
(io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2.Version>)
responseObserver);
break;
case METHODID_UPDATE_VERSION:
serviceImpl.updateVersion(
(com.google.cloud.dialogflow.v2.UpdateVersionRequest) request,
(io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2.Version>)
responseObserver);
break;
case METHODID_DELETE_VERSION:
serviceImpl.deleteVersion(
(com.google.cloud.dialogflow.v2.DeleteVersionRequest) request,
(io.grpc.stub.StreamObserver<com.google.protobuf.Empty>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getListVersionsMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.v2.ListVersionsRequest,
com.google.cloud.dialogflow.v2.ListVersionsResponse>(
service, METHODID_LIST_VERSIONS)))
.addMethod(
getGetVersionMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.v2.GetVersionRequest,
com.google.cloud.dialogflow.v2.Version>(service, METHODID_GET_VERSION)))
.addMethod(
getCreateVersionMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.v2.CreateVersionRequest,
com.google.cloud.dialogflow.v2.Version>(service, METHODID_CREATE_VERSION)))
.addMethod(
getUpdateVersionMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.v2.UpdateVersionRequest,
com.google.cloud.dialogflow.v2.Version>(service, METHODID_UPDATE_VERSION)))
.addMethod(
getDeleteVersionMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.v2.DeleteVersionRequest, com.google.protobuf.Empty>(
service, METHODID_DELETE_VERSION)))
.build();
}
private abstract static class VersionsBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoFileDescriptorSupplier,
io.grpc.protobuf.ProtoServiceDescriptorSupplier {
VersionsBaseDescriptorSupplier() {}
@java.lang.Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return com.google.cloud.dialogflow.v2.VersionProto.getDescriptor();
}
@java.lang.Override
public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() {
return getFileDescriptor().findServiceByName("Versions");
}
}
private static final class VersionsFileDescriptorSupplier extends VersionsBaseDescriptorSupplier {
VersionsFileDescriptorSupplier() {}
}
private static final class VersionsMethodDescriptorSupplier extends VersionsBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
private final java.lang.String methodName;
VersionsMethodDescriptorSupplier(java.lang.String methodName) {
this.methodName = methodName;
}
@java.lang.Override
public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() {
return getServiceDescriptor().findMethodByName(methodName);
}
}
private static volatile io.grpc.ServiceDescriptor serviceDescriptor;
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (VersionsGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor =
result =
io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new VersionsFileDescriptorSupplier())
.addMethod(getListVersionsMethod())
.addMethod(getGetVersionMethod())
.addMethod(getCreateVersionMethod())
.addMethod(getUpdateVersionMethod())
.addMethod(getDeleteVersionMethod())
.build();
}
}
}
return result;
}
}
|
apache/hadoop | 36,461 | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDataNodeVolumeFailure.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.datanode;
import static org.apache.hadoop.test.MetricsAsserts.getLongCounter;
import static org.apache.hadoop.test.MetricsAsserts.getMetrics;
import static org.apache.hadoop.test.PlatformAssumptions.assumeNotWindows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.BlockReader;
import org.apache.hadoop.hdfs.ClientContext;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.DFSUtilClient;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.RemotePeerFactory;
import org.apache.hadoop.hdfs.client.impl.BlockReaderFactory;
import org.apache.hadoop.hdfs.client.impl.DfsClientConf;
import org.apache.hadoop.hdfs.net.Peer;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockManager;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockManagerTestUtil;
import org.apache.hadoop.hdfs.server.common.Storage;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsDatasetSpi;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsVolumeSpi;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.AddBlockPoolException;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsDatasetTestUtil;
import org.apache.hadoop.hdfs.server.namenode.FSNamesystem;
import org.apache.hadoop.hdfs.server.protocol.DatanodeRegistration;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
import org.apache.hadoop.hdfs.server.protocol.VolumeFailureSummary;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.metrics2.MetricsRecordBuilder;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.test.GenericTestUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.function.Supplier;
/**
* Fine-grain testing of block files and locations after volume failure.
*/
@Timeout(120)
public class TestDataNodeVolumeFailure {
private final static Logger LOG = LoggerFactory.getLogger(
TestDataNodeVolumeFailure.class);
final private int block_size = 512;
MiniDFSCluster cluster = null;
private Configuration conf;
final int dn_num = 2;
final int blocks_num = 30;
final short repl=2;
File dataDir = null;
File data_fail = null;
File failedDir = null;
private FileSystem fs;
// mapping blocks to Meta files(physical files) and locs(NameNode locations)
private class BlockLocs {
public int num_files = 0;
public int num_locs = 0;
}
// block id to BlockLocs
final Map<String, BlockLocs> block_map = new HashMap<String, BlockLocs> ();
@BeforeEach
public void setUp() throws Exception {
// bring up a cluster of 2
conf = new HdfsConfiguration();
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, block_size);
// Allow a single volume failure (there are two volumes)
conf.setInt(DFSConfigKeys.DFS_DATANODE_FAILED_VOLUMES_TOLERATED_KEY, 1);
conf.setInt(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 30);
conf.setTimeDuration(DFSConfigKeys.DFS_DATANODE_DISK_CHECK_MIN_GAP_KEY,
0, TimeUnit.MILLISECONDS);
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(dn_num).build();
cluster.waitActive();
fs = cluster.getFileSystem();
dataDir = new File(cluster.getDataDirectory());
}
@AfterEach
public void tearDown() throws Exception {
if(data_fail != null) {
FileUtil.setWritable(data_fail, true);
data_fail = null;
}
if(failedDir != null) {
FileUtil.setWritable(failedDir, true);
failedDir = null;
}
if(cluster != null) {
cluster.shutdown();
cluster = null;
}
}
/*
* Verify the number of blocks and files are correct after volume failure,
* and that we can replicate to both datanodes even after a single volume
* failure if the configuration parameter allows this.
*/
@Test
@Timeout(value = 120)
public void testVolumeFailure() throws Exception {
System.out.println("Data dir: is " + dataDir.getPath());
// Data dir structure is dataDir/data[1-4]/[current,tmp...]
// data1,2 is for datanode 1, data2,3 - datanode2
String filename = "/test.txt";
Path filePath = new Path(filename);
// we use only small number of blocks to avoid creating subdirs in the data dir..
int filesize = block_size*blocks_num;
DFSTestUtil.createFile(fs, filePath, filesize, repl, 1L);
DFSTestUtil.waitReplication(fs, filePath, repl);
System.out.println("file " + filename + "(size " +
filesize + ") is created and replicated");
// fail the volume
// delete/make non-writable one of the directories (failed volume)
data_fail = cluster.getInstanceStorageDir(1, 0);
failedDir = MiniDFSCluster.getFinalizedDir(data_fail,
cluster.getNamesystem().getBlockPoolId());
if (failedDir.exists() &&
//!FileUtil.fullyDelete(failedDir)
!deteteBlocks(failedDir)
) {
throw new IOException("Could not delete hdfs directory '" + failedDir + "'");
}
data_fail.setReadOnly();
failedDir.setReadOnly();
System.out.println("Deleteing " + failedDir.getPath() + "; exist=" + failedDir.exists());
// access all the blocks on the "failed" DataNode,
// we need to make sure that the "failed" volume is being accessed -
// and that will cause failure, blocks removal, "emergency" block report
triggerFailure(filename, filesize);
// DN eventually have latest volume failure information for next heartbeat
final DataNode dn = cluster.getDataNodes().get(1);
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
final VolumeFailureSummary summary =
dn.getFSDataset().getVolumeFailureSummary();
return summary != null &&
summary.getFailedStorageLocations() != null &&
summary.getFailedStorageLocations().length == 1;
}
}, 10, 30 * 1000);
// trigger DN to send heartbeat
DataNodeTestUtils.triggerHeartbeat(dn);
final BlockManager bm = cluster.getNamesystem().getBlockManager();
// trigger NN handel heartbeat
BlockManagerTestUtil.checkHeartbeat(bm);
// NN now should have latest volume failure
assertEquals(1, cluster.getNamesystem().getVolumeFailuresTotal());
// assert failedStorageLocations
assertTrue(dn.getFSDataset().getVolumeFailureSummary()
.getFailedStorageLocations()[0]
.contains("[DISK]"));
// verify number of blocks and files...
verify(filename, filesize);
// create another file (with one volume failed).
System.out.println("creating file test1.txt");
Path fileName1 = new Path("/test1.txt");
DFSTestUtil.createFile(fs, fileName1, filesize, repl, 1L);
// should be able to replicate to both nodes (2 DN, repl=2)
DFSTestUtil.waitReplication(fs, fileName1, repl);
System.out.println("file " + fileName1.getName() +
" is created and replicated");
}
/*
* If one of the sub-folders under the finalized directory is unreadable,
* either due to permissions or a filesystem corruption, the DN will fail
* to read it when scanning it for blocks to load into the replica map. This
* test ensures the DN does not exit and reports the failed volume to the
* NN (HDFS-14333). This is done by using a simulated FsDataset that throws
* an exception for a failed volume when the block pool is initialized.
*/
@Test
@Timeout(value = 15)
public void testDnStartsAfterDiskErrorScanningBlockPool() throws Exception {
// Don't use the cluster configured in the setup() method for this test.
cluster.shutdown(true);
cluster.close();
conf.set(DFSConfigKeys.DFS_DATANODE_FSDATASET_FACTORY_KEY,
BadDiskFSDataset.Factory.class.getName());
final MiniDFSCluster localCluster = new MiniDFSCluster
.Builder(conf).numDataNodes(1).build();
try {
localCluster.waitActive();
DataNode dn = localCluster.getDataNodes().get(0);
try {
localCluster.waitDatanodeFullyStarted(dn, 3000);
} catch (TimeoutException e) {
fail("Datanode did not get fully started");
}
assertTrue(dn.isDatanodeUp());
// trigger DN to send heartbeat
DataNodeTestUtils.triggerHeartbeat(dn);
final BlockManager bm = localCluster.getNamesystem().getBlockManager();
// trigger NN handle heartbeat
BlockManagerTestUtil.checkHeartbeat(bm);
// NN now should have the failed volume
assertEquals(1, localCluster.getNamesystem().getVolumeFailuresTotal());
} finally {
localCluster.close();
}
}
/**
* Test that DataStorage and BlockPoolSliceStorage remove the failed volume
* after failure.
*/
@Test
@Timeout(value = 150)
public void testFailedVolumeBeingRemovedFromDataNode()
throws Exception {
// The test uses DataNodeTestUtils#injectDataDirFailure() to simulate
// volume failures which is currently not supported on Windows.
assumeNotWindows();
Path file1 = new Path("/test1");
DFSTestUtil.createFile(fs, file1, 1024, (short) 2, 1L);
DFSTestUtil.waitReplication(fs, file1, (short) 2);
File dn0Vol1 = cluster.getInstanceStorageDir(0, 0);
DataNodeTestUtils.injectDataDirFailure(dn0Vol1);
DataNode dn0 = cluster.getDataNodes().get(0);
DataNodeTestUtils.waitForDiskError(dn0,
DataNodeTestUtils.getVolume(dn0, dn0Vol1));
// Verify dn0Vol1 has been completely removed from DN0.
// 1. dn0Vol1 is removed from DataStorage.
DataStorage storage = dn0.getStorage();
assertEquals(1, storage.getNumStorageDirs());
for (int i = 0; i < storage.getNumStorageDirs(); i++) {
Storage.StorageDirectory sd = storage.getStorageDir(i);
assertFalse(sd.getRoot().getAbsolutePath().startsWith(
dn0Vol1.getAbsolutePath()
));
}
final String bpid = cluster.getNamesystem().getBlockPoolId();
BlockPoolSliceStorage bpsStorage = storage.getBPStorage(bpid);
assertEquals(1, bpsStorage.getNumStorageDirs());
for (int i = 0; i < bpsStorage.getNumStorageDirs(); i++) {
Storage.StorageDirectory sd = bpsStorage.getStorageDir(i);
assertFalse(sd.getRoot().getAbsolutePath().startsWith(
dn0Vol1.getAbsolutePath()
));
}
// 2. dn0Vol1 is removed from FsDataset
FsDatasetSpi<? extends FsVolumeSpi> data = dn0.getFSDataset();
try (FsDatasetSpi.FsVolumeReferences vols = data.getFsVolumeReferences()) {
for (FsVolumeSpi volume : vols) {
assertFalse(new File(volume.getStorageLocation().getUri())
.getAbsolutePath().startsWith(dn0Vol1.getAbsolutePath()
));
}
}
// 3. all blocks on dn0Vol1 have been removed.
for (ReplicaInfo replica : FsDatasetTestUtil.getReplicas(data, bpid)) {
assertNotNull(replica.getVolume());
assertFalse(new File(replica.getVolume().getStorageLocation().getUri())
.getAbsolutePath().startsWith(dn0Vol1.getAbsolutePath()
));
}
// 4. dn0Vol1 is not in DN0's configuration and dataDirs anymore.
String[] dataDirStrs =
dn0.getConf().get(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY).split(",");
assertEquals(1, dataDirStrs.length);
assertFalse(dataDirStrs[0].contains(dn0Vol1.getAbsolutePath()));
}
/**
* Test DataNode stops when the number of failed volumes exceeds
* dfs.datanode.failed.volumes.tolerated .
*/
@Test
@Timeout(value = 10)
public void testDataNodeShutdownAfterNumFailedVolumeExceedsTolerated()
throws Exception {
// The test uses DataNodeTestUtils#injectDataDirFailure() to simulate
// volume failures which is currently not supported on Windows.
assumeNotWindows();
// make both data directories to fail on dn0
final File dn0Vol1 = cluster.getInstanceStorageDir(0, 0);
final File dn0Vol2 = cluster.getInstanceStorageDir(0, 1);
DataNodeTestUtils.injectDataDirFailure(dn0Vol1, dn0Vol2);
DataNode dn0 = cluster.getDataNodes().get(0);
DataNodeTestUtils.waitForDiskError(dn0,
DataNodeTestUtils.getVolume(dn0, dn0Vol1));
DataNodeTestUtils.waitForDiskError(dn0,
DataNodeTestUtils.getVolume(dn0, dn0Vol2));
// DN0 should stop after the number of failure disks exceed tolerated
// value (1).
dn0.checkDiskError();
assertFalse(dn0.shouldRun());
}
/**
* Test that DN does not shutdown, as long as failure volumes being hot swapped.
*/
@Test
public void testVolumeFailureRecoveredByHotSwappingVolume()
throws Exception {
// The test uses DataNodeTestUtils#injectDataDirFailure() to simulate
// volume failures which is currently not supported on Windows.
assumeNotWindows();
final File dn0Vol1 = cluster.getInstanceStorageDir(0, 0);
final File dn0Vol2 = cluster.getInstanceStorageDir(0, 1);
final DataNode dn0 = cluster.getDataNodes().get(0);
final String oldDataDirs = dn0.getConf().get(
DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY);
// Fail dn0Vol1 first.
DataNodeTestUtils.injectDataDirFailure(dn0Vol1);
DataNodeTestUtils.waitForDiskError(dn0,
DataNodeTestUtils.getVolume(dn0, dn0Vol1));
// Hot swap out the failure volume.
String dataDirs = dn0Vol2.getPath();
assertThat(
dn0.reconfigurePropertyImpl(
DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY, dataDirs))
.isEqualTo(dn0.getConf().get(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY));
// Fix failure volume dn0Vol1 and remount it back.
DataNodeTestUtils.restoreDataDirFromFailure(dn0Vol1);
assertThat(
dn0.reconfigurePropertyImpl(
DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY, oldDataDirs))
.isEqualTo(dn0.getConf().get(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY));
// Fail dn0Vol2. Now since dn0Vol1 has been fixed, DN0 has sufficient
// resources, thus it should keep running.
DataNodeTestUtils.injectDataDirFailure(dn0Vol2);
DataNodeTestUtils.waitForDiskError(dn0,
DataNodeTestUtils.getVolume(dn0, dn0Vol2));
assertTrue(dn0.shouldRun());
}
/**
* Test {@link DataNode#refreshVolumes(String)} not deadLock with
* {@link BPOfferService#registrationSucceeded(BPServiceActor,
* DatanodeRegistration)}.
*/
@Test
@Timeout(value = 10)
public void testRefreshDeadLock() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
DataNodeFaultInjector.set(new DataNodeFaultInjector() {
public void delayWhenOfferServiceHoldLock() {
try {
latch.await();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
DataNode dn = cluster.getDataNodes().get(0);
File volume = cluster.getInstanceStorageDir(0, 0);
String dataDirs = volume.getPath();
List<BPOfferService> allBpOs = dn.getAllBpOs();
BPOfferService service = allBpOs.get(0);
BPServiceActor actor = service.getBPServiceActors().get(0);
DatanodeRegistration bpRegistration = actor.getBpRegistration();
Thread register = new Thread(() -> {
try {
service.registrationSucceeded(actor, bpRegistration);
} catch (IOException e) {
e.printStackTrace();
}
});
register.start();
String newdir = dataDirs + "tmp";
// Make sure service have get writelock
latch.countDown();
String result = dn.reconfigurePropertyImpl(
DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY, newdir);
assertNotNull(result);
}
/**
* Test changing the number of volumes does not impact the disk failure
* tolerance.
*/
@Test
public void testTolerateVolumeFailuresAfterAddingMoreVolumes()
throws Exception {
// The test uses DataNodeTestUtils#injectDataDirFailure() to simulate
// volume failures which is currently not supported on Windows.
assumeNotWindows();
final File dn0Vol1 = cluster.getInstanceStorageDir(0, 0);
final File dn0Vol2 = cluster.getInstanceStorageDir(0, 1);
final File dn0VolNew = new File(dataDir, "data_new");
final DataNode dn0 = cluster.getDataNodes().get(0);
final String oldDataDirs = dn0.getConf().get(
DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY);
// Add a new volume to DN0
assertThat(
dn0.reconfigurePropertyImpl(
DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY,
oldDataDirs + "," + dn0VolNew.getAbsolutePath()))
.isEqualTo(dn0.getConf().get(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY));
// Fail dn0Vol1 first and hot swap it.
DataNodeTestUtils.injectDataDirFailure(dn0Vol1);
DataNodeTestUtils.waitForDiskError(dn0,
DataNodeTestUtils.getVolume(dn0, dn0Vol1));
assertTrue(dn0.shouldRun());
// Fail dn0Vol2, now dn0 should stop, because we only tolerate 1 disk failure.
DataNodeTestUtils.injectDataDirFailure(dn0Vol2);
DataNodeTestUtils.waitForDiskError(dn0,
DataNodeTestUtils.getVolume(dn0, dn0Vol2));
dn0.checkDiskError();
assertFalse(dn0.shouldRun());
}
/**
* Test that there are under replication blocks after vol failures
*/
@Test
public void testUnderReplicationAfterVolFailure() throws Exception {
// The test uses DataNodeTestUtils#injectDataDirFailure() to simulate
// volume failures which is currently not supported on Windows.
assumeNotWindows();
// Bring up one more datanode
cluster.startDataNodes(conf, 1, true, null, null);
cluster.waitActive();
final BlockManager bm = cluster.getNamesystem().getBlockManager();
Path file1 = new Path("/test1");
DFSTestUtil.createFile(fs, file1, 1024, (short)3, 1L);
DFSTestUtil.waitReplication(fs, file1, (short)3);
// Fail the first volume on both datanodes
File dn1Vol1 = cluster.getInstanceStorageDir(0, 0);
File dn2Vol1 = cluster.getInstanceStorageDir(1, 0);
DataNodeTestUtils.injectDataDirFailure(dn1Vol1, dn2Vol1);
Path file2 = new Path("/test2");
DFSTestUtil.createFile(fs, file2, 1024, (short)3, 1L);
DFSTestUtil.waitReplication(fs, file2, (short)3);
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
// underReplicatedBlocks are due to failed volumes
long underReplicatedBlocks = bm.getLowRedundancyBlocksCount()
+ bm.getPendingReconstructionBlocksCount();
if (underReplicatedBlocks > 0) {
return true;
}
LOG.info("There is no under replicated block after volume failure.");
return false;
}
}, 500, 60000);
}
/**
* Test if there is volume failure, the DataNode will fail to start.
*
* We fail a volume by setting the parent directory non-writable.
*/
@Test
@Timeout(value = 120)
public void testDataNodeFailToStartWithVolumeFailure() throws Exception {
// Method to simulate volume failures is currently not supported on Windows.
assumeNotWindows();
failedDir = new File(dataDir, "failedDir");
assertTrue(failedDir.mkdir() && failedDir.setReadOnly(),
"Failed to fail a volume by setting it non-writable");
startNewDataNodeWithDiskFailure(new File(failedDir, "newDir1"), false);
}
/**
* DataNode will start and tolerate one failing disk according to config.
*
* We fail a volume by setting the parent directory non-writable.
*/
@Test
@Timeout(value = 120)
public void testDNStartAndTolerateOneVolumeFailure() throws Exception {
// Method to simulate volume failures is currently not supported on Windows.
assumeNotWindows();
failedDir = new File(dataDir, "failedDir");
assertTrue(failedDir.mkdir() && failedDir.setReadOnly(),
"Failed to fail a volume by setting it non-writable");
startNewDataNodeWithDiskFailure(new File(failedDir, "newDir1"), true);
}
/**
* Test if data directory is not readable/writable, DataNode won't start.
*/
@Test
@Timeout(value = 120)
public void testDNFailToStartWithDataDirNonWritable() throws Exception {
// Method to simulate volume failures is currently not supported on Windows.
assumeNotWindows();
final File readOnlyDir = new File(dataDir, "nonWritable");
assertTrue(readOnlyDir.mkdir() && readOnlyDir.setReadOnly(),
"Set the data dir permission non-writable");
startNewDataNodeWithDiskFailure(new File(readOnlyDir, "newDir1"), false);
}
/**
* DataNode will start and tolerate one non-writable data directory
* according to config.
*/
@Test
@Timeout(value = 120)
public void testDNStartAndTolerateOneDataDirNonWritable() throws Exception {
// Method to simulate volume failures is currently not supported on Windows.
assumeNotWindows();
final File readOnlyDir = new File(dataDir, "nonWritable");
assertTrue(readOnlyDir.mkdir() && readOnlyDir.setReadOnly(),
"Set the data dir permission non-writable");
startNewDataNodeWithDiskFailure(new File(readOnlyDir, "newDir1"), true);
}
/**
* @param badDataDir bad data dir, either disk failure or non-writable
* @param tolerated true if one volume failure is allowed else false
*/
private void startNewDataNodeWithDiskFailure(File badDataDir,
boolean tolerated) throws Exception {
final File data5 = new File(dataDir, "data5");
final String newDirs = badDataDir.toString() + "," + data5.toString();
final Configuration newConf = new Configuration(conf);
newConf.set(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY, newDirs);
LOG.info("Setting dfs.datanode.data.dir for new DataNode as {}", newDirs);
newConf.setInt(DFSConfigKeys.DFS_DATANODE_FAILED_VOLUMES_TOLERATED_KEY,
tolerated ? 1 : 0);
// bring up one more DataNode
assertEquals(repl, cluster.getDataNodes().size());
try {
cluster.startDataNodes(newConf, 1, false, null, null);
assertTrue(tolerated, "Failed to get expected IOException");
} catch (IOException ioe) {
assertFalse(tolerated, "Unexpected IOException " + ioe);
return;
}
assertEquals(repl + 1, cluster.getDataNodes().size());
// create new file and it should be able to replicate to 3 nodes
final Path p = new Path("/test1.txt");
DFSTestUtil.createFile(fs, p, block_size * blocks_num, (short) 3, 1L);
DFSTestUtil.waitReplication(fs, p, (short) (repl + 1));
}
/**
* verifies two things:
* 1. number of locations of each block in the name node
* matches number of actual files
* 2. block files + pending block equals to total number of blocks that a file has
* including the replication (HDFS file has 30 blocks, repl=2 - total 60
* @param fn - file name
* @param fs - file size
* @throws IOException
*/
private void verify(String fn, int fs) throws IOException{
// now count how many physical blocks are there
int totalReal = countRealBlocks(block_map);
System.out.println("countRealBlocks counted " + totalReal + " blocks");
// count how many blocks store in NN structures.
int totalNN = countNNBlocks(block_map, fn, fs);
System.out.println("countNNBlocks counted " + totalNN + " blocks");
for(String bid : block_map.keySet()) {
BlockLocs bl = block_map.get(bid);
// System.out.println(bid + "->" + bl.num_files + "vs." + bl.num_locs);
// number of physical files (1 or 2) should be same as number of datanodes
// in the list of the block locations
assertEquals(bl.num_files, bl.num_locs, "Num files should match num locations");
}
assertEquals(totalReal, totalNN, "Num physical blocks should match num stored in the NN");
// now check the number of under-replicated blocks
FSNamesystem fsn = cluster.getNamesystem();
// force update of all the metric counts by calling computeDatanodeWork
BlockManagerTestUtil.getComputedDatanodeWork(fsn.getBlockManager());
// get all the counts
long underRepl = fsn.getUnderReplicatedBlocks();
long pendRepl = fsn.getPendingReplicationBlocks();
long totalRepl = underRepl + pendRepl;
System.out.println("underreplicated after = "+ underRepl +
" and pending repl =" + pendRepl + "; total underRepl = " + totalRepl);
System.out.println("total blocks (real and replicating):" +
(totalReal + totalRepl) + " vs. all files blocks " + blocks_num*2);
// together all the blocks should be equal to all real + all underreplicated
assertEquals(totalReal + totalRepl, blocks_num * repl, "Incorrect total block count");
}
/**
* go to each block on the 2nd DataNode until it fails...
* @param path
* @param size
* @throws IOException
*/
private void triggerFailure(String path, long size) throws IOException {
NamenodeProtocols nn = cluster.getNameNodeRpc();
List<LocatedBlock> locatedBlocks =
nn.getBlockLocations(path, 0, size).getLocatedBlocks();
for (LocatedBlock lb : locatedBlocks) {
DatanodeInfo dinfo = lb.getLocations()[1];
ExtendedBlock b = lb.getBlock();
try {
accessBlock(dinfo, lb);
} catch (IOException e) {
System.out.println("Failure triggered, on block: " + b.getBlockId() +
"; corresponding volume should be removed by now");
break;
}
}
}
/**
* simulate failure delete all the block files
* @param dir
* @throws IOException
*/
private boolean deteteBlocks(File dir) {
Collection<File> fileList = FileUtils.listFiles(dir,
TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
for(File f : fileList) {
if(f.getName().startsWith(Block.BLOCK_FILE_PREFIX)) {
System.out.println("Deleting file " + f);
if(!f.delete())
return false;
}
}
return true;
}
/**
* try to access a block on a data node. If fails - throws exception
* @param datanode
* @param lblock
* @throws IOException
*/
private void accessBlock(DatanodeInfo datanode, LocatedBlock lblock)
throws IOException {
InetSocketAddress targetAddr = null;
ExtendedBlock block = lblock.getBlock();
targetAddr = NetUtils.createSocketAddr(datanode.getXferAddr());
BlockReader blockReader = new BlockReaderFactory(new DfsClientConf(conf)).
setInetSocketAddress(targetAddr).
setBlock(block).
setFileName(BlockReaderFactory.getFileName(targetAddr,
"test-blockpoolid", block.getBlockId())).
setBlockToken(lblock.getBlockToken()).
setStartOffset(0).
setLength(0).
setVerifyChecksum(true).
setClientName("TestDataNodeVolumeFailure").
setDatanodeInfo(datanode).
setCachingStrategy(CachingStrategy.newDefaultStrategy()).
setClientCacheContext(ClientContext.getFromConf(conf)).
setConfiguration(conf).
setRemotePeerFactory(new RemotePeerFactory() {
@Override
public Peer newConnectedPeer(InetSocketAddress addr,
Token<BlockTokenIdentifier> blockToken, DatanodeID datanodeId)
throws IOException {
Peer peer = null;
Socket sock = NetUtils.getDefaultSocketFactory(conf).createSocket();
try {
sock.connect(addr, HdfsConstants.READ_TIMEOUT);
sock.setSoTimeout(HdfsConstants.READ_TIMEOUT);
peer = DFSUtilClient.peerFromSocket(sock);
} finally {
if (peer == null) {
IOUtils.closeSocket(sock);
}
}
return peer;
}
}).
build();
blockReader.close();
}
/**
* Count datanodes that have copies of the blocks for a file
* put it into the map
* @param map
* @param path
* @param size
* @return
* @throws IOException
*/
private int countNNBlocks(Map<String, BlockLocs> map, String path, long size)
throws IOException {
int total = 0;
NamenodeProtocols nn = cluster.getNameNodeRpc();
List<LocatedBlock> locatedBlocks =
nn.getBlockLocations(path, 0, size).getLocatedBlocks();
//System.out.println("Number of blocks: " + locatedBlocks.size());
for(LocatedBlock lb : locatedBlocks) {
String blockId = ""+lb.getBlock().getBlockId();
//System.out.print(blockId + ": ");
DatanodeInfo[] dn_locs = lb.getLocations();
BlockLocs bl = map.get(blockId);
if(bl == null) {
bl = new BlockLocs();
}
//System.out.print(dn_info.name+",");
total += dn_locs.length;
bl.num_locs += dn_locs.length;
map.put(blockId, bl);
//System.out.println();
}
return total;
}
/**
* look for real blocks
* by counting *.meta files in all the storage dirs
* @param map
* @return
*/
private int countRealBlocks(Map<String, BlockLocs> map) {
int total = 0;
final String bpid = cluster.getNamesystem().getBlockPoolId();
for(int i=0; i<dn_num; i++) {
for(int j=0; j<=1; j++) {
File storageDir = cluster.getInstanceStorageDir(i, j);
File dir = MiniDFSCluster.getFinalizedDir(storageDir, bpid);
if(dir == null) {
System.out.println("dir is null for dn=" + i + " and data_dir=" + j);
continue;
}
List<File> res = MiniDFSCluster.getAllBlockMetadataFiles(dir);
if(res == null) {
System.out.println("res is null for dir = " + dir + " i=" + i + " and j=" + j);
continue;
}
//System.out.println("for dn" + i + "." + j + ": " + dir + "=" + res.length+ " files");
//int ii = 0;
for(File f: res) {
String s = f.getName();
// cut off "blk_-" at the beginning and ".meta" at the end
assertNotNull(s, "Block file name should not be null");
String bid = s.substring(s.indexOf("_")+1, s.lastIndexOf("_"));
//System.out.println(ii++ + ". block " + s + "; id=" + bid);
BlockLocs val = map.get(bid);
if(val == null) {
val = new BlockLocs();
}
val.num_files ++; // one more file for the block
map.put(bid, val);
}
//System.out.println("dir1="+dir.getPath() + "blocks=" + res.length);
//System.out.println("dir2="+dir2.getPath() + "blocks=" + res2.length);
total += res.size();
}
}
return total;
}
private static class BadDiskFSDataset extends SimulatedFSDataset {
BadDiskFSDataset(DataStorage storage, Configuration conf) {
super(storage, conf);
}
private String[] failedStorageLocations = null;
@Override
public void addBlockPool(String bpid, Configuration conf) {
super.addBlockPool(bpid, conf);
Map<FsVolumeSpi, IOException>
unhealthyDataDirs = new HashMap<>();
unhealthyDataDirs.put(this.getStorages().get(0).getVolume(),
new IOException());
throw new AddBlockPoolException(unhealthyDataDirs);
}
@Override
public synchronized void removeVolumes(Collection<StorageLocation> volumes,
boolean clearFailure) {
Iterator<StorageLocation> itr = volumes.iterator();
String[] failedLocations = new String[volumes.size()];
int index = 0;
while(itr.hasNext()) {
StorageLocation s = itr.next();
failedLocations[index] = s.getUri().getPath();
index += 1;
}
failedStorageLocations = failedLocations;
}
@Override
public void handleVolumeFailures(Set<FsVolumeSpi> failedVolumes) {
// do nothing
}
@Override
public VolumeFailureSummary getVolumeFailureSummary() {
if (failedStorageLocations != null) {
return new VolumeFailureSummary(failedStorageLocations, 0, 0);
} else {
return new VolumeFailureSummary(ArrayUtils.EMPTY_STRING_ARRAY, 0, 0);
}
}
static class Factory extends FsDatasetSpi.Factory<BadDiskFSDataset> {
@Override
public BadDiskFSDataset newInstance(DataNode datanode,
DataStorage storage, Configuration conf) throws IOException {
return new BadDiskFSDataset(storage, conf);
}
@Override
public boolean isSimulated() {
return true;
}
}
}
/*
* Verify the failed volume can be cheched during dn startup
*/
@Test
@Timeout(value = 120)
public void testVolumeFailureDuringStartup() throws Exception {
LOG.debug("Data dir: is " + dataDir.getPath());
// fail the volume
data_fail = cluster.getInstanceStorageDir(1, 0);
failedDir = MiniDFSCluster.getFinalizedDir(data_fail,
cluster.getNamesystem().getBlockPoolId());
failedDir.setReadOnly();
// restart the dn
cluster.restartDataNode(1);
final DataNode dn = cluster.getDataNodes().get(1);
// should get the failed volume during startup
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
return dn.getFSDataset() !=null &&
dn.getFSDataset().getVolumeFailureSummary() != null &&
dn.getFSDataset().getVolumeFailureSummary().
getFailedStorageLocations()!= null &&
dn.getFSDataset().getVolumeFailureSummary().
getFailedStorageLocations().length == 1;
}
}, 10, 30 * 1000);
}
/*
* Fail two volumes, and check the metrics of VolumeFailures
*/
@Test
public void testVolumeFailureTwo() throws Exception {
// fail two volumes
data_fail = cluster.getInstanceStorageDir(1, 0);
failedDir = MiniDFSCluster.getFinalizedDir(data_fail,
cluster.getNamesystem().getBlockPoolId());
failedDir.setReadOnly();
data_fail = cluster.getInstanceStorageDir(1, 1);
failedDir = MiniDFSCluster.getFinalizedDir(data_fail,
cluster.getNamesystem().getBlockPoolId());
failedDir.setReadOnly();
final DataNode dn = cluster.getDataNodes().get(1);
dn.checkDiskError();
MetricsRecordBuilder rb = getMetrics(dn.getMetrics().name());
long volumeFailures = getLongCounter("VolumeFailures", rb);
assertEquals(2, volumeFailures);
}
}
|
openjdk/jdk8 | 36,839 | jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/server/EndpointFactory.java | /*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.server;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import com.sun.xml.internal.stream.buffer.MutableXMLStreamBuffer;
import com.sun.xml.internal.ws.api.BindingID;
import com.sun.xml.internal.ws.api.WSBinding;
import com.sun.xml.internal.ws.api.WSFeatureList;
import com.sun.xml.internal.ws.api.databinding.DatabindingConfig;
import com.sun.xml.internal.ws.api.databinding.DatabindingFactory;
import com.sun.xml.internal.ws.api.databinding.MetadataReader;
import com.sun.xml.internal.ws.api.databinding.WSDLGenInfo;
import com.sun.xml.internal.ws.api.model.SEIModel;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLModel;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLPort;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLService;
import com.sun.xml.internal.ws.api.policy.PolicyResolver;
import com.sun.xml.internal.ws.api.policy.PolicyResolverFactory;
import com.sun.xml.internal.ws.api.server.AsyncProvider;
import com.sun.xml.internal.ws.api.server.Container;
import com.sun.xml.internal.ws.api.server.ContainerResolver;
import com.sun.xml.internal.ws.api.server.InstanceResolver;
import com.sun.xml.internal.ws.api.server.Invoker;
import com.sun.xml.internal.ws.api.server.SDDocument;
import com.sun.xml.internal.ws.api.server.SDDocumentSource;
import com.sun.xml.internal.ws.api.server.WSEndpoint;
import com.sun.xml.internal.ws.api.streaming.XMLStreamReaderFactory;
import com.sun.xml.internal.ws.api.wsdl.parser.WSDLParserExtension;
import com.sun.xml.internal.ws.api.wsdl.parser.XMLEntityResolver;
import com.sun.xml.internal.ws.api.wsdl.parser.XMLEntityResolver.Parser;
import com.sun.xml.internal.ws.api.wsdl.writer.WSDLGeneratorExtension;
import com.sun.xml.internal.ws.binding.BindingImpl;
import com.sun.xml.internal.ws.binding.SOAPBindingImpl;
import com.sun.xml.internal.ws.binding.WebServiceFeatureList;
import com.sun.xml.internal.ws.model.AbstractSEIModelImpl;
import com.sun.xml.internal.ws.model.ReflectAnnotationReader;
import com.sun.xml.internal.ws.model.RuntimeModeler;
import com.sun.xml.internal.ws.model.SOAPSEIModel;
import com.sun.xml.internal.ws.policy.PolicyMap;
import com.sun.xml.internal.ws.policy.jaxws.PolicyUtil;
import com.sun.xml.internal.ws.resources.ServerMessages;
import com.sun.xml.internal.ws.server.provider.ProviderInvokerTube;
import com.sun.xml.internal.ws.server.sei.SEIInvokerTube;
import com.sun.xml.internal.ws.util.HandlerAnnotationInfo;
import com.sun.xml.internal.ws.util.HandlerAnnotationProcessor;
import com.sun.xml.internal.ws.util.ServiceConfigurationError;
import com.sun.xml.internal.ws.util.ServiceFinder;
import com.sun.xml.internal.ws.util.xml.XmlUtil;
import com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.jws.WebService;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.ws.Provider;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;
import javax.xml.ws.WebServiceProvider;
import javax.xml.ws.soap.SOAPBinding;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
* Entry point to the JAX-WS RI server-side runtime.
*
* @author Kohsuke Kawaguchi
* @author Jitendra Kotamraju
*/
public class EndpointFactory {
private static final EndpointFactory instance = new EndpointFactory();
public static EndpointFactory getInstance() {
return instance;
}
/**
* Implements {@link WSEndpoint#create}.
*
* No need to take WebServiceContext implementation. When InvokerPipe is
* instantiated, it calls InstanceResolver to set up a WebServiceContext.
* We shall only take delegate to getUserPrincipal and isUserInRole from adapter.
*
* <p>
* Nobody else should be calling this method.
*/
public static <T> WSEndpoint<T> createEndpoint(
Class<T> implType, boolean processHandlerAnnotation, @Nullable Invoker invoker,
@Nullable QName serviceName, @Nullable QName portName,
@Nullable Container container, @Nullable WSBinding binding,
@Nullable SDDocumentSource primaryWsdl,
@Nullable Collection<? extends SDDocumentSource> metadata,
EntityResolver resolver, boolean isTransportSynchronous) {
return createEndpoint(implType, processHandlerAnnotation, invoker, serviceName,
portName, container, binding, primaryWsdl, metadata, resolver, isTransportSynchronous, true);
}
public static <T> WSEndpoint<T> createEndpoint(
Class<T> implType, boolean processHandlerAnnotation, @Nullable Invoker invoker,
@Nullable QName serviceName, @Nullable QName portName,
@Nullable Container container, @Nullable WSBinding binding,
@Nullable SDDocumentSource primaryWsdl,
@Nullable Collection<? extends SDDocumentSource> metadata,
EntityResolver resolver, boolean isTransportSynchronous, boolean isStandard) {
EndpointFactory factory = container != null ? container.getSPI(EndpointFactory.class) : null;
if (factory == null)
factory = EndpointFactory.getInstance();
return factory.create(
implType,processHandlerAnnotation, invoker,serviceName,portName,container,binding,primaryWsdl,metadata,resolver,isTransportSynchronous,isStandard);
}
/**
* Implements {@link WSEndpoint#create}.
*
* No need to take WebServiceContext implementation. When InvokerPipe is
* instantiated, it calls InstanceResolver to set up a WebServiceContext.
* We shall only take delegate to getUserPrincipal and isUserInRole from adapter.
*
* <p>
* Nobody else should be calling this method.
*/
public <T> WSEndpoint<T> create(
Class<T> implType, boolean processHandlerAnnotation, @Nullable Invoker invoker,
@Nullable QName serviceName, @Nullable QName portName,
@Nullable Container container, @Nullable WSBinding binding,
@Nullable SDDocumentSource primaryWsdl,
@Nullable Collection<? extends SDDocumentSource> metadata,
EntityResolver resolver, boolean isTransportSynchronous) {
return create(implType, processHandlerAnnotation, invoker, serviceName,
portName, container, binding, primaryWsdl, metadata, resolver, isTransportSynchronous,
true);
}
public <T> WSEndpoint<T> create(
Class<T> implType, boolean processHandlerAnnotation, @Nullable Invoker invoker,
@Nullable QName serviceName, @Nullable QName portName,
@Nullable Container container, @Nullable WSBinding binding,
@Nullable SDDocumentSource primaryWsdl,
@Nullable Collection<? extends SDDocumentSource> metadata,
EntityResolver resolver, boolean isTransportSynchronous, boolean isStandard) {
if(implType ==null)
throw new IllegalArgumentException();
MetadataReader metadataReader = getExternalMetadatReader(implType, binding);
if (isStandard) {
verifyImplementorClass(implType, metadataReader);
}
if (invoker == null) {
invoker = InstanceResolver.createDefault(implType).createInvoker();
}
List<SDDocumentSource> md = new ArrayList<SDDocumentSource>();
if(metadata!=null)
md.addAll(metadata);
if(primaryWsdl!=null && !md.contains(primaryWsdl))
md.add(primaryWsdl);
if(container==null)
container = ContainerResolver.getInstance().getContainer();
if(serviceName==null)
serviceName = getDefaultServiceName(implType, metadataReader);
if(portName==null)
portName = getDefaultPortName(serviceName,implType, metadataReader);
{// error check
String serviceNS = serviceName.getNamespaceURI();
String portNS = portName.getNamespaceURI();
if (!serviceNS.equals(portNS)) {
throw new ServerRtException("wrong.tns.for.port",portNS, serviceNS);
}
}
// setting a default binding
if (binding == null)
binding = BindingImpl.create(BindingID.parse(implType));
if ( isStandard && primaryWsdl != null) {
verifyPrimaryWSDL(primaryWsdl, serviceName);
}
QName portTypeName = null;
if (isStandard && implType.getAnnotation(WebServiceProvider.class)==null) {
portTypeName = RuntimeModeler.getPortTypeName(implType, metadataReader);
}
// Categorises the documents as WSDL, Schema etc
List<SDDocumentImpl> docList = categoriseMetadata(md, serviceName, portTypeName);
// Finds the primary WSDL and makes sure that metadata doesn't have
// two concrete or abstract WSDLs
SDDocumentImpl primaryDoc = primaryWsdl != null ? SDDocumentImpl.create(primaryWsdl,serviceName,portTypeName) : findPrimary(docList);
EndpointAwareTube terminal;
WSDLPort wsdlPort = null;
AbstractSEIModelImpl seiModel = null;
// create WSDL model
if (primaryDoc != null) {
wsdlPort = getWSDLPort(primaryDoc, docList, serviceName, portName, container, resolver);
}
WebServiceFeatureList features=((BindingImpl)binding).getFeatures();
if (isStandard) {
features.parseAnnotations(implType);
}
PolicyMap policyMap = null;
// create terminal pipe that invokes the application
if (isUseProviderTube(implType, isStandard)) {
//TODO incase of Provider, provide a way to User for complete control of the message processing by giving
// ability to turn off the WSDL/Policy based features and its associated tubes.
//Even in case of Provider, merge all features configured via WSDL/Policy or deployment configuration
Iterable<WebServiceFeature> configFtrs;
if(wsdlPort != null) {
policyMap = wsdlPort.getOwner().getParent().getPolicyMap();
//Merge features from WSDL and other policy configuration
configFtrs = wsdlPort.getFeatures();
} else {
//No WSDL, so try to merge features from Policy configuration
policyMap = PolicyResolverFactory.create().resolve(
new PolicyResolver.ServerContext(null, container, implType, false));
configFtrs = PolicyUtil.getPortScopedFeatures(policyMap,serviceName,portName);
}
features.mergeFeatures(configFtrs, true);
terminal = createProviderInvokerTube(implType, binding, invoker, container);
} else {
// Create runtime model for non Provider endpoints
seiModel = createSEIModel(wsdlPort, implType, serviceName, portName, binding, primaryDoc);
if(binding instanceof SOAPBindingImpl){
//set portKnownHeaders on Binding, so that they can be used for MU processing
((SOAPBindingImpl)binding).setPortKnownHeaders(
((SOAPSEIModel)seiModel).getKnownHeaders());
}
// Generate WSDL for SEI endpoints(not for Provider endpoints)
if (primaryDoc == null) {
primaryDoc = generateWSDL(binding, seiModel, docList, container, implType);
// create WSDL model
wsdlPort = getWSDLPort(primaryDoc, docList, serviceName, portName, container, resolver);
seiModel.freeze(wsdlPort);
}
policyMap = wsdlPort.getOwner().getParent().getPolicyMap();
// New Features might have been added in WSDL through Policy.
//Merge features from WSDL and other policy configuration
// This sets only the wsdl features that are not already set(enabled/disabled)
features.mergeFeatures(wsdlPort.getFeatures(), true);
terminal = createSEIInvokerTube(seiModel,invoker,binding);
}
// Process @HandlerChain, if handler-chain is not set via Deployment Descriptor
if (processHandlerAnnotation) {
processHandlerAnnotation(binding, implType, serviceName, portName);
}
// Selects only required metadata for this endpoint from the passed-in metadata
if (primaryDoc != null) {
docList = findMetadataClosure(primaryDoc, docList, resolver);
}
ServiceDefinitionImpl serviceDefiniton = (primaryDoc != null) ? new ServiceDefinitionImpl(docList, primaryDoc) : null;
return create(serviceName, portName, binding, container, seiModel, wsdlPort, implType, serviceDefiniton,
terminal, isTransportSynchronous, policyMap);
}
protected <T> WSEndpoint<T> create(QName serviceName, QName portName, WSBinding binding, Container container, SEIModel seiModel, WSDLPort wsdlPort, Class<T> implType, ServiceDefinitionImpl serviceDefinition, EndpointAwareTube terminal, boolean isTransportSynchronous, PolicyMap policyMap) {
return new WSEndpointImpl<T>(serviceName, portName, binding, container, seiModel,
wsdlPort, implType, serviceDefinition, terminal, isTransportSynchronous, policyMap);
}
protected boolean isUseProviderTube(Class<?> implType, boolean isStandard) {
return !isStandard || implType.getAnnotation(WebServiceProvider.class)!=null;
}
protected EndpointAwareTube createSEIInvokerTube(AbstractSEIModelImpl seiModel, Invoker invoker, WSBinding binding) {
return new SEIInvokerTube(seiModel,invoker,binding);
}
protected <T> EndpointAwareTube createProviderInvokerTube(final Class<T> implType, final WSBinding binding,
final Invoker invoker, final Container container) {
return ProviderInvokerTube.create(implType, binding, invoker, container);
}
/**
* Goes through the original metadata documents and collects the required ones.
* This done traversing from primary WSDL and its imports until it builds a
* complete set of documents(transitive closure) for the endpoint.
*
* @param primaryDoc primary WSDL doc
* @param docList complete metadata
* @return new metadata that doesn't contain extraneous documnets.
*/
private static List<SDDocumentImpl> findMetadataClosure(SDDocumentImpl primaryDoc, List<SDDocumentImpl> docList, EntityResolver resolver) {
// create a map for old metadata
Map<String, SDDocumentImpl> oldMap = new HashMap<String, SDDocumentImpl>();
for(SDDocumentImpl doc : docList) {
oldMap.put(doc.getSystemId().toString(), doc);
}
// create a map for new metadata
Map<String, SDDocumentImpl> newMap = new HashMap<String, SDDocumentImpl>();
newMap.put(primaryDoc.getSystemId().toString(), primaryDoc);
List<String> remaining = new ArrayList<String>();
remaining.addAll(primaryDoc.getImports());
while(!remaining.isEmpty()) {
String url = remaining.remove(0);
SDDocumentImpl doc = oldMap.get(url);
if (doc == null) {
// old metadata doesn't have this imported doc, may be external
if (resolver != null) {
try {
InputSource source = resolver.resolveEntity(null, url);
if (source != null) {
MutableXMLStreamBuffer xsb = new MutableXMLStreamBuffer();
XMLStreamReader reader = XmlUtil.newXMLInputFactory(true).createXMLStreamReader(source.getByteStream());
xsb.createFromXMLStreamReader(reader);
SDDocumentSource sdocSource = SDDocumentImpl.create(new URL(url), xsb);
doc = SDDocumentImpl.create(sdocSource, null, null);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
// Check if new metadata already contains this doc
if (doc != null && !newMap.containsKey(url)) {
newMap.put(url, doc);
remaining.addAll(doc.getImports());
}
}
List<SDDocumentImpl> newMetadata = new ArrayList<SDDocumentImpl>();
newMetadata.addAll(newMap.values());
return newMetadata;
}
private static <T> void processHandlerAnnotation(WSBinding binding, Class<T> implType, QName serviceName, QName portName) {
HandlerAnnotationInfo chainInfo =
HandlerAnnotationProcessor.buildHandlerInfo(
implType, serviceName, portName, binding);
if (chainInfo != null) {
binding.setHandlerChain(chainInfo.getHandlers());
if (binding instanceof SOAPBinding) {
((SOAPBinding) binding).setRoles(chainInfo.getRoles());
}
}
}
/**
* Verifies if the endpoint implementor class has @WebService or @WebServiceProvider
* annotation
*
* @return
* true if it is a Provider or AsyncProvider endpoint
* false otherwise
* @throws java.lang.IllegalArgumentException
* If it doesn't have any one of @WebService or @WebServiceProvider
* If it has both @WebService and @WebServiceProvider annotations
*/
public static boolean verifyImplementorClass(Class<?> clz) {
return verifyImplementorClass(clz, null);
}
/**
* Verifies if the endpoint implementor class has @WebService or @WebServiceProvider
* annotation; passing MetadataReader instance allows to read annotations from
* xml descriptor instead of class's annotations
*
* @return
* true if it is a Provider or AsyncProvider endpoint
* false otherwise
* @throws java.lang.IllegalArgumentException
* If it doesn't have any one of @WebService or @WebServiceProvider
* If it has both @WebService and @WebServiceProvider annotations
*/
public static boolean verifyImplementorClass(Class<?> clz, MetadataReader metadataReader) {
if (metadataReader == null) {
metadataReader = new ReflectAnnotationReader();
}
WebServiceProvider wsProvider = metadataReader.getAnnotation(WebServiceProvider.class, clz);
WebService ws = metadataReader.getAnnotation(WebService.class, clz);
if (wsProvider == null && ws == null) {
throw new IllegalArgumentException(clz +" has neither @WebService nor @WebServiceProvider annotation");
}
if (wsProvider != null && ws != null) {
throw new IllegalArgumentException(clz +" has both @WebService and @WebServiceProvider annotations");
}
if (wsProvider != null) {
if (Provider.class.isAssignableFrom(clz) || AsyncProvider.class.isAssignableFrom(clz)) {
return true;
}
throw new IllegalArgumentException(clz +" doesn't implement Provider or AsyncProvider interface");
}
return false;
}
private static AbstractSEIModelImpl createSEIModel(WSDLPort wsdlPort,
Class<?> implType, @NotNull QName serviceName, @NotNull QName portName, WSBinding binding,
SDDocumentSource primaryWsdl) {
DatabindingFactory fac = DatabindingFactory.newInstance();
DatabindingConfig config = new DatabindingConfig();
config.setEndpointClass(implType);
config.getMappingInfo().setServiceName(serviceName);
config.setWsdlPort(wsdlPort);
config.setWSBinding(binding);
config.setClassLoader(implType.getClassLoader());
config.getMappingInfo().setPortName(portName);
if (primaryWsdl != null) config.setWsdlURL(primaryWsdl.getSystemId());
config.setMetadataReader(getExternalMetadatReader(implType, binding));
com.sun.xml.internal.ws.db.DatabindingImpl rt = (com.sun.xml.internal.ws.db.DatabindingImpl)fac.createRuntime(config);
return (AbstractSEIModelImpl) rt.getModel();
}
public static MetadataReader getExternalMetadatReader(Class<?> implType, WSBinding binding) {
com.oracle.webservices.internal.api.databinding.ExternalMetadataFeature ef = binding.getFeature(
com.oracle.webservices.internal.api.databinding.ExternalMetadataFeature.class);
// TODO-Miran: would it be necessary to disable secure xml processing?
if (ef != null)
return ef.getMetadataReader(implType.getClassLoader(), false);
return null;
}
/**
*Set the mtom enable setting from wsdl model (mtom policy assertion) on to @link WSBinding} if DD has
* not already set it on BindingID. Also check conflicts.
*/
/*
private static void applyEffectiveMtomSetting(WSDLBoundPortType wsdlBinding, WSBinding binding){
if(wsdlBinding.isMTOMEnabled()){
BindingID bindingId = binding.getBindingId();
if(bindingId.isMTOMEnabled() == null){
binding.setMTOMEnabled(true);
}else if (bindingId.isMTOMEnabled() != null && bindingId.isMTOMEnabled() == Boolean.FALSE){
//TODO: i18N
throw new ServerRtException("Deployment failed! Mtom policy assertion in WSDL is enabled whereas the deplyment descriptor setting wants to disable it!");
}
}
}
*/
/**
* If service name is not already set via DD or programmatically, it uses
* annotations {@link WebServiceProvider}, {@link WebService} on implementorClass to get PortName.
*
* @return non-null service name
*/
public static @NotNull QName getDefaultServiceName(Class<?> implType) {
return getDefaultServiceName(implType, null);
}
public static @NotNull QName getDefaultServiceName(Class<?> implType, MetadataReader metadataReader) {
return getDefaultServiceName(implType, true, metadataReader);
}
public static @NotNull QName getDefaultServiceName(Class<?> implType, boolean isStandard) {
return getDefaultServiceName(implType, isStandard, null);
}
public static @NotNull QName getDefaultServiceName(Class<?> implType, boolean isStandard, MetadataReader metadataReader) {
if (metadataReader == null) {
metadataReader = new ReflectAnnotationReader();
}
QName serviceName;
WebServiceProvider wsProvider = metadataReader.getAnnotation(WebServiceProvider.class, implType);
if (wsProvider!=null) {
String tns = wsProvider.targetNamespace();
String local = wsProvider.serviceName();
serviceName = new QName(tns, local);
} else {
serviceName = RuntimeModeler.getServiceName(implType, metadataReader, isStandard);
}
assert serviceName != null;
return serviceName;
}
/**
* If portName is not already set via DD or programmatically, it uses
* annotations on implementorClass to get PortName.
*
* @return non-null port name
*/
public static @NotNull QName getDefaultPortName(QName serviceName, Class<?> implType) {
return getDefaultPortName(serviceName, implType, null);
}
public static @NotNull QName getDefaultPortName(QName serviceName, Class<?> implType, MetadataReader metadataReader) {
return getDefaultPortName(serviceName, implType, true, metadataReader);
}
public static @NotNull QName getDefaultPortName(QName serviceName, Class<?> implType, boolean isStandard) {
return getDefaultPortName(serviceName, implType, isStandard, null);
}
public static @NotNull QName getDefaultPortName(QName serviceName, Class<?> implType, boolean isStandard, MetadataReader metadataReader) {
if (metadataReader == null) {
metadataReader = new ReflectAnnotationReader();
}
QName portName;
WebServiceProvider wsProvider = metadataReader.getAnnotation(WebServiceProvider.class, implType);
if (wsProvider!=null) {
String tns = wsProvider.targetNamespace();
String local = wsProvider.portName();
portName = new QName(tns, local);
} else {
portName = RuntimeModeler.getPortName(implType, metadataReader, serviceName.getNamespaceURI(), isStandard);
}
assert portName != null;
return portName;
}
/**
* Returns the wsdl from @WebService, or @WebServiceProvider annotation using
* wsdlLocation element.
*
* @param implType
* endpoint implementation class
* make sure that you called {@link #verifyImplementorClass} on it.
* @return wsdl if there is wsdlLocation, else null
*/
public static @Nullable String getWsdlLocation(Class<?> implType) {
return getWsdlLocation(implType, new ReflectAnnotationReader());
}
/**
* Returns the wsdl from @WebService, or @WebServiceProvider annotation using
* wsdlLocation element.
*
* @param implType
* endpoint implementation class
* make sure that you called {@link #verifyImplementorClass} on it.
* @return wsdl if there is wsdlLocation, else null
*/
public static @Nullable String getWsdlLocation(Class<?> implType, MetadataReader metadataReader) {
if (metadataReader == null) {
metadataReader = new ReflectAnnotationReader();
}
WebService ws = metadataReader.getAnnotation(WebService.class, implType);
if (ws != null) {
return nullIfEmpty(ws.wsdlLocation());
} else {
WebServiceProvider wsProvider = implType.getAnnotation(WebServiceProvider.class);
assert wsProvider != null;
return nullIfEmpty(wsProvider.wsdlLocation());
}
}
private static String nullIfEmpty(String string) {
if (string.length() < 1) {
string = null;
}
return string;
}
/**
* Generates the WSDL and XML Schema for the endpoint if necessary
* It generates WSDL only for SOAP1.1, and for XSOAP1.2 bindings
*/
private static SDDocumentImpl generateWSDL(WSBinding binding, AbstractSEIModelImpl seiModel, List<SDDocumentImpl> docs,
Container container, Class implType) {
BindingID bindingId = binding.getBindingId();
if (!bindingId.canGenerateWSDL()) {
throw new ServerRtException("can.not.generate.wsdl", bindingId);
}
if (bindingId.toString().equals(SOAPBindingImpl.X_SOAP12HTTP_BINDING)) {
String msg = ServerMessages.GENERATE_NON_STANDARD_WSDL();
logger.warning(msg);
}
// Generate WSDL and schema documents using runtime model
WSDLGenResolver wsdlResolver = new WSDLGenResolver(docs,seiModel.getServiceQName(),seiModel.getPortTypeName());
WSDLGenInfo wsdlGenInfo = new WSDLGenInfo();
wsdlGenInfo.setWsdlResolver(wsdlResolver);
wsdlGenInfo.setContainer(container);
wsdlGenInfo.setExtensions(ServiceFinder.find(WSDLGeneratorExtension.class).toArray());
wsdlGenInfo.setInlineSchemas(false);
wsdlGenInfo.setSecureXmlProcessingDisabled(isSecureXmlProcessingDisabled(binding.getFeatures()));
seiModel.getDatabinding().generateWSDL(wsdlGenInfo);
// WSDLGenerator wsdlGen = new WSDLGenerator(seiModel, wsdlResolver, binding, container, implType, false,
// ServiceFinder.find(WSDLGeneratorExtension.class).toArray());
// wsdlGen.doGeneration();
return wsdlResolver.updateDocs();
}
private static boolean isSecureXmlProcessingDisabled(WSFeatureList featureList) {
// TODO-Miran: would it be necessary to disable secure xml processing?
return false;
}
/**
* Builds {@link SDDocumentImpl} from {@link SDDocumentSource}.
*/
private static List<SDDocumentImpl> categoriseMetadata(
List<SDDocumentSource> src, QName serviceName, QName portTypeName) {
List<SDDocumentImpl> r = new ArrayList<SDDocumentImpl>(src.size());
for (SDDocumentSource doc : src) {
r.add(SDDocumentImpl.create(doc,serviceName,portTypeName));
}
return r;
}
/**
* Verifies whether the given primaryWsdl contains the given serviceName.
* If the WSDL doesn't have the service, it throws an WebServiceException.
*/
private static void verifyPrimaryWSDL(@NotNull SDDocumentSource primaryWsdl, @NotNull QName serviceName) {
SDDocumentImpl primaryDoc = SDDocumentImpl.create(primaryWsdl,serviceName,null);
if (!(primaryDoc instanceof SDDocument.WSDL)) {
throw new WebServiceException(primaryWsdl.getSystemId()+
" is not a WSDL. But it is passed as a primary WSDL");
}
SDDocument.WSDL wsdlDoc = (SDDocument.WSDL)primaryDoc;
if (!wsdlDoc.hasService()) {
if(wsdlDoc.getAllServices().isEmpty())
throw new WebServiceException("Not a primary WSDL="+primaryWsdl.getSystemId()+
" since it doesn't have Service "+serviceName);
else
throw new WebServiceException("WSDL "+primaryDoc.getSystemId()
+" has the following services "+wsdlDoc.getAllServices()
+" but not "+serviceName+". Maybe you forgot to specify a serviceName and/or targetNamespace in @WebService/@WebServiceProvider?");
}
}
/**
* Finds the primary WSDL document from the list of metadata documents. If
* there are two metadata documents that qualify for primary, it throws an
* exception. If there are two metadata documents that qualify for porttype,
* it throws an exception.
*
* @return primay wsdl document, null if is not there in the docList
*
*/
private static @Nullable SDDocumentImpl findPrimary(@NotNull List<SDDocumentImpl> docList) {
SDDocumentImpl primaryDoc = null;
boolean foundConcrete = false;
boolean foundAbstract = false;
for(SDDocumentImpl doc : docList) {
if (doc instanceof SDDocument.WSDL) {
SDDocument.WSDL wsdlDoc = (SDDocument.WSDL)doc;
if (wsdlDoc.hasService()) {
primaryDoc = doc;
if (foundConcrete) {
throw new ServerRtException("duplicate.primary.wsdl", doc.getSystemId() );
}
foundConcrete = true;
}
if (wsdlDoc.hasPortType()) {
if (foundAbstract) {
throw new ServerRtException("duplicate.abstract.wsdl", doc.getSystemId());
}
foundAbstract = true;
}
}
}
return primaryDoc;
}
/**
* Parses the primary WSDL and returns the {@link WSDLPort} for the given service and port names
*
* @param primaryWsdl Primary WSDL
* @param metadata it may contain imported WSDL and schema documents
* @param serviceName service name in wsdl
* @param portName port name in WSDL
* @param container container in which this service is running
* @return non-null wsdl port object
*/
private static @NotNull WSDLPort getWSDLPort(SDDocumentSource primaryWsdl, List<? extends SDDocumentSource> metadata,
@NotNull QName serviceName, @NotNull QName portName, Container container,
EntityResolver resolver) {
URL wsdlUrl = primaryWsdl.getSystemId();
try {
// TODO: delegate to another entity resolver
WSDLModel wsdlDoc = RuntimeWSDLParser.parse(
new Parser(primaryWsdl), new EntityResolverImpl(metadata, resolver),
false, container, ServiceFinder.find(WSDLParserExtension.class).toArray());
if(wsdlDoc.getServices().size() == 0) {
throw new ServerRtException(ServerMessages.localizableRUNTIME_PARSER_WSDL_NOSERVICE_IN_WSDLMODEL(wsdlUrl));
}
WSDLService wsdlService = wsdlDoc.getService(serviceName);
if (wsdlService == null) {
throw new ServerRtException(ServerMessages.localizableRUNTIME_PARSER_WSDL_INCORRECTSERVICE(serviceName,wsdlUrl));
}
WSDLPort wsdlPort = wsdlService.get(portName);
if (wsdlPort == null) {
throw new ServerRtException(ServerMessages.localizableRUNTIME_PARSER_WSDL_INCORRECTSERVICEPORT(serviceName, portName, wsdlUrl));
}
return wsdlPort;
} catch (IOException e) {
throw new ServerRtException("runtime.parser.wsdl", wsdlUrl,e);
} catch (XMLStreamException e) {
throw new ServerRtException("runtime.saxparser.exception", e.getMessage(), e.getLocation(), e);
} catch (SAXException e) {
throw new ServerRtException("runtime.parser.wsdl", wsdlUrl,e);
} catch (ServiceConfigurationError e) {
throw new ServerRtException("runtime.parser.wsdl", wsdlUrl,e);
}
}
/**
* {@link XMLEntityResolver} that can resolve to {@link SDDocumentSource}s.
*/
private static final class EntityResolverImpl implements XMLEntityResolver {
private Map<String,SDDocumentSource> metadata = new HashMap<String,SDDocumentSource>();
private EntityResolver resolver;
public EntityResolverImpl(List<? extends SDDocumentSource> metadata, EntityResolver resolver) {
for (SDDocumentSource doc : metadata) {
this.metadata.put(doc.getSystemId().toExternalForm(),doc);
}
this.resolver = resolver;
}
public Parser resolveEntity (String publicId, String systemId) throws IOException, XMLStreamException {
if (systemId != null) {
SDDocumentSource doc = metadata.get(systemId);
if (doc != null)
return new Parser(doc);
}
if (resolver != null) {
try {
InputSource source = resolver.resolveEntity(publicId, systemId);
if (source != null) {
Parser p = new Parser(null, XMLStreamReaderFactory.create(source, true));
return p;
}
} catch (SAXException e) {
throw new XMLStreamException(e);
}
}
return null;
}
}
private static final Logger logger = Logger.getLogger(
com.sun.xml.internal.ws.util.Constants.LoggingDomain + ".server.endpoint");
}
|
googleapis/google-cloud-java | 36,405 | java-artifact-registry/proto-google-cloud-artifact-registry-v1/src/main/java/com/google/devtools/artifactregistry/v1/ListPackagesResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/devtools/artifactregistry/v1/package.proto
// Protobuf Java Version: 3.25.8
package com.google.devtools.artifactregistry.v1;
/**
*
*
* <pre>
* The response from listing packages.
* </pre>
*
* Protobuf type {@code google.devtools.artifactregistry.v1.ListPackagesResponse}
*/
public final class ListPackagesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.devtools.artifactregistry.v1.ListPackagesResponse)
ListPackagesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListPackagesResponse.newBuilder() to construct.
private ListPackagesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListPackagesResponse() {
packages_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListPackagesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.devtools.artifactregistry.v1.PackageProto
.internal_static_google_devtools_artifactregistry_v1_ListPackagesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.devtools.artifactregistry.v1.PackageProto
.internal_static_google_devtools_artifactregistry_v1_ListPackagesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.devtools.artifactregistry.v1.ListPackagesResponse.class,
com.google.devtools.artifactregistry.v1.ListPackagesResponse.Builder.class);
}
public static final int PACKAGES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.devtools.artifactregistry.v1.Package> packages_;
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.devtools.artifactregistry.v1.Package> getPackagesList() {
return packages_;
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.devtools.artifactregistry.v1.PackageOrBuilder>
getPackagesOrBuilderList() {
return packages_;
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
@java.lang.Override
public int getPackagesCount() {
return packages_.size();
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
@java.lang.Override
public com.google.devtools.artifactregistry.v1.Package getPackages(int index) {
return packages_.get(index);
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
@java.lang.Override
public com.google.devtools.artifactregistry.v1.PackageOrBuilder getPackagesOrBuilder(int index) {
return packages_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* The token to retrieve the next page of packages, or empty if there are no
* more packages to return.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* The token to retrieve the next page of packages, or empty if there are no
* more packages to return.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < packages_.size(); i++) {
output.writeMessage(1, packages_.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 < packages_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, packages_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.devtools.artifactregistry.v1.ListPackagesResponse)) {
return super.equals(obj);
}
com.google.devtools.artifactregistry.v1.ListPackagesResponse other =
(com.google.devtools.artifactregistry.v1.ListPackagesResponse) obj;
if (!getPackagesList().equals(other.getPackagesList())) 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 (getPackagesCount() > 0) {
hash = (37 * hash) + PACKAGES_FIELD_NUMBER;
hash = (53 * hash) + getPackagesList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.devtools.artifactregistry.v1.ListPackagesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.artifactregistry.v1.ListPackagesResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.devtools.artifactregistry.v1.ListPackagesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.artifactregistry.v1.ListPackagesResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.devtools.artifactregistry.v1.ListPackagesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.artifactregistry.v1.ListPackagesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.devtools.artifactregistry.v1.ListPackagesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.devtools.artifactregistry.v1.ListPackagesResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.devtools.artifactregistry.v1.ListPackagesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.devtools.artifactregistry.v1.ListPackagesResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.devtools.artifactregistry.v1.ListPackagesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.devtools.artifactregistry.v1.ListPackagesResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.devtools.artifactregistry.v1.ListPackagesResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The response from listing packages.
* </pre>
*
* Protobuf type {@code google.devtools.artifactregistry.v1.ListPackagesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.devtools.artifactregistry.v1.ListPackagesResponse)
com.google.devtools.artifactregistry.v1.ListPackagesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.devtools.artifactregistry.v1.PackageProto
.internal_static_google_devtools_artifactregistry_v1_ListPackagesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.devtools.artifactregistry.v1.PackageProto
.internal_static_google_devtools_artifactregistry_v1_ListPackagesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.devtools.artifactregistry.v1.ListPackagesResponse.class,
com.google.devtools.artifactregistry.v1.ListPackagesResponse.Builder.class);
}
// Construct using com.google.devtools.artifactregistry.v1.ListPackagesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (packagesBuilder_ == null) {
packages_ = java.util.Collections.emptyList();
} else {
packages_ = null;
packagesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.devtools.artifactregistry.v1.PackageProto
.internal_static_google_devtools_artifactregistry_v1_ListPackagesResponse_descriptor;
}
@java.lang.Override
public com.google.devtools.artifactregistry.v1.ListPackagesResponse
getDefaultInstanceForType() {
return com.google.devtools.artifactregistry.v1.ListPackagesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.devtools.artifactregistry.v1.ListPackagesResponse build() {
com.google.devtools.artifactregistry.v1.ListPackagesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.devtools.artifactregistry.v1.ListPackagesResponse buildPartial() {
com.google.devtools.artifactregistry.v1.ListPackagesResponse result =
new com.google.devtools.artifactregistry.v1.ListPackagesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.devtools.artifactregistry.v1.ListPackagesResponse result) {
if (packagesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
packages_ = java.util.Collections.unmodifiableList(packages_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.packages_ = packages_;
} else {
result.packages_ = packagesBuilder_.build();
}
}
private void buildPartial0(
com.google.devtools.artifactregistry.v1.ListPackagesResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.devtools.artifactregistry.v1.ListPackagesResponse) {
return mergeFrom((com.google.devtools.artifactregistry.v1.ListPackagesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.devtools.artifactregistry.v1.ListPackagesResponse other) {
if (other
== com.google.devtools.artifactregistry.v1.ListPackagesResponse.getDefaultInstance())
return this;
if (packagesBuilder_ == null) {
if (!other.packages_.isEmpty()) {
if (packages_.isEmpty()) {
packages_ = other.packages_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensurePackagesIsMutable();
packages_.addAll(other.packages_);
}
onChanged();
}
} else {
if (!other.packages_.isEmpty()) {
if (packagesBuilder_.isEmpty()) {
packagesBuilder_.dispose();
packagesBuilder_ = null;
packages_ = other.packages_;
bitField0_ = (bitField0_ & ~0x00000001);
packagesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getPackagesFieldBuilder()
: null;
} else {
packagesBuilder_.addAllMessages(other.packages_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.devtools.artifactregistry.v1.Package m =
input.readMessage(
com.google.devtools.artifactregistry.v1.Package.parser(),
extensionRegistry);
if (packagesBuilder_ == null) {
ensurePackagesIsMutable();
packages_.add(m);
} else {
packagesBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.devtools.artifactregistry.v1.Package> packages_ =
java.util.Collections.emptyList();
private void ensurePackagesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
packages_ =
new java.util.ArrayList<com.google.devtools.artifactregistry.v1.Package>(packages_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.devtools.artifactregistry.v1.Package,
com.google.devtools.artifactregistry.v1.Package.Builder,
com.google.devtools.artifactregistry.v1.PackageOrBuilder>
packagesBuilder_;
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public java.util.List<com.google.devtools.artifactregistry.v1.Package> getPackagesList() {
if (packagesBuilder_ == null) {
return java.util.Collections.unmodifiableList(packages_);
} else {
return packagesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public int getPackagesCount() {
if (packagesBuilder_ == null) {
return packages_.size();
} else {
return packagesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public com.google.devtools.artifactregistry.v1.Package getPackages(int index) {
if (packagesBuilder_ == null) {
return packages_.get(index);
} else {
return packagesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public Builder setPackages(int index, com.google.devtools.artifactregistry.v1.Package value) {
if (packagesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePackagesIsMutable();
packages_.set(index, value);
onChanged();
} else {
packagesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public Builder setPackages(
int index, com.google.devtools.artifactregistry.v1.Package.Builder builderForValue) {
if (packagesBuilder_ == null) {
ensurePackagesIsMutable();
packages_.set(index, builderForValue.build());
onChanged();
} else {
packagesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public Builder addPackages(com.google.devtools.artifactregistry.v1.Package value) {
if (packagesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePackagesIsMutable();
packages_.add(value);
onChanged();
} else {
packagesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public Builder addPackages(int index, com.google.devtools.artifactregistry.v1.Package value) {
if (packagesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePackagesIsMutable();
packages_.add(index, value);
onChanged();
} else {
packagesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public Builder addPackages(
com.google.devtools.artifactregistry.v1.Package.Builder builderForValue) {
if (packagesBuilder_ == null) {
ensurePackagesIsMutable();
packages_.add(builderForValue.build());
onChanged();
} else {
packagesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public Builder addPackages(
int index, com.google.devtools.artifactregistry.v1.Package.Builder builderForValue) {
if (packagesBuilder_ == null) {
ensurePackagesIsMutable();
packages_.add(index, builderForValue.build());
onChanged();
} else {
packagesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public Builder addAllPackages(
java.lang.Iterable<? extends com.google.devtools.artifactregistry.v1.Package> values) {
if (packagesBuilder_ == null) {
ensurePackagesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, packages_);
onChanged();
} else {
packagesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public Builder clearPackages() {
if (packagesBuilder_ == null) {
packages_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
packagesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public Builder removePackages(int index) {
if (packagesBuilder_ == null) {
ensurePackagesIsMutable();
packages_.remove(index);
onChanged();
} else {
packagesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public com.google.devtools.artifactregistry.v1.Package.Builder getPackagesBuilder(int index) {
return getPackagesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public com.google.devtools.artifactregistry.v1.PackageOrBuilder getPackagesOrBuilder(
int index) {
if (packagesBuilder_ == null) {
return packages_.get(index);
} else {
return packagesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public java.util.List<? extends com.google.devtools.artifactregistry.v1.PackageOrBuilder>
getPackagesOrBuilderList() {
if (packagesBuilder_ != null) {
return packagesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(packages_);
}
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public com.google.devtools.artifactregistry.v1.Package.Builder addPackagesBuilder() {
return getPackagesFieldBuilder()
.addBuilder(com.google.devtools.artifactregistry.v1.Package.getDefaultInstance());
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public com.google.devtools.artifactregistry.v1.Package.Builder addPackagesBuilder(int index) {
return getPackagesFieldBuilder()
.addBuilder(index, com.google.devtools.artifactregistry.v1.Package.getDefaultInstance());
}
/**
*
*
* <pre>
* The packages returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Package packages = 1;</code>
*/
public java.util.List<com.google.devtools.artifactregistry.v1.Package.Builder>
getPackagesBuilderList() {
return getPackagesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.devtools.artifactregistry.v1.Package,
com.google.devtools.artifactregistry.v1.Package.Builder,
com.google.devtools.artifactregistry.v1.PackageOrBuilder>
getPackagesFieldBuilder() {
if (packagesBuilder_ == null) {
packagesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.devtools.artifactregistry.v1.Package,
com.google.devtools.artifactregistry.v1.Package.Builder,
com.google.devtools.artifactregistry.v1.PackageOrBuilder>(
packages_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
packages_ = null;
}
return packagesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* The token to retrieve the next page of packages, or empty if there are no
* more packages to return.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The token to retrieve the next page of packages, or empty if there are no
* more packages to return.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The token to retrieve the next page of packages, or empty if there are no
* more packages to return.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The token to retrieve the next page of packages, or empty if there are no
* more packages to return.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The token to retrieve the next page of packages, or empty if there are no
* more packages to return.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.devtools.artifactregistry.v1.ListPackagesResponse)
}
// @@protoc_insertion_point(class_scope:google.devtools.artifactregistry.v1.ListPackagesResponse)
private static final com.google.devtools.artifactregistry.v1.ListPackagesResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.devtools.artifactregistry.v1.ListPackagesResponse();
}
public static com.google.devtools.artifactregistry.v1.ListPackagesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListPackagesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListPackagesResponse>() {
@java.lang.Override
public ListPackagesResponse 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<ListPackagesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListPackagesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.devtools.artifactregistry.v1.ListPackagesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,405 | java-artifact-registry/proto-google-cloud-artifact-registry-v1/src/main/java/com/google/devtools/artifactregistry/v1/ListVersionsResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/devtools/artifactregistry/v1/version.proto
// Protobuf Java Version: 3.25.8
package com.google.devtools.artifactregistry.v1;
/**
*
*
* <pre>
* The response from listing versions.
* </pre>
*
* Protobuf type {@code google.devtools.artifactregistry.v1.ListVersionsResponse}
*/
public final class ListVersionsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.devtools.artifactregistry.v1.ListVersionsResponse)
ListVersionsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListVersionsResponse.newBuilder() to construct.
private ListVersionsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListVersionsResponse() {
versions_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListVersionsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.devtools.artifactregistry.v1.VersionProto
.internal_static_google_devtools_artifactregistry_v1_ListVersionsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.devtools.artifactregistry.v1.VersionProto
.internal_static_google_devtools_artifactregistry_v1_ListVersionsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.devtools.artifactregistry.v1.ListVersionsResponse.class,
com.google.devtools.artifactregistry.v1.ListVersionsResponse.Builder.class);
}
public static final int VERSIONS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.devtools.artifactregistry.v1.Version> versions_;
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.devtools.artifactregistry.v1.Version> getVersionsList() {
return versions_;
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.devtools.artifactregistry.v1.VersionOrBuilder>
getVersionsOrBuilderList() {
return versions_;
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
@java.lang.Override
public int getVersionsCount() {
return versions_.size();
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
@java.lang.Override
public com.google.devtools.artifactregistry.v1.Version getVersions(int index) {
return versions_.get(index);
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
@java.lang.Override
public com.google.devtools.artifactregistry.v1.VersionOrBuilder getVersionsOrBuilder(int index) {
return versions_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* The token to retrieve the next page of versions, or empty if there are no
* more versions to return.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* The token to retrieve the next page of versions, or empty if there are no
* more versions to return.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < versions_.size(); i++) {
output.writeMessage(1, versions_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < versions_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, versions_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.devtools.artifactregistry.v1.ListVersionsResponse)) {
return super.equals(obj);
}
com.google.devtools.artifactregistry.v1.ListVersionsResponse other =
(com.google.devtools.artifactregistry.v1.ListVersionsResponse) obj;
if (!getVersionsList().equals(other.getVersionsList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getVersionsCount() > 0) {
hash = (37 * hash) + VERSIONS_FIELD_NUMBER;
hash = (53 * hash) + getVersionsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.devtools.artifactregistry.v1.ListVersionsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.artifactregistry.v1.ListVersionsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.devtools.artifactregistry.v1.ListVersionsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.artifactregistry.v1.ListVersionsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.devtools.artifactregistry.v1.ListVersionsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.artifactregistry.v1.ListVersionsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.devtools.artifactregistry.v1.ListVersionsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.devtools.artifactregistry.v1.ListVersionsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.devtools.artifactregistry.v1.ListVersionsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.devtools.artifactregistry.v1.ListVersionsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.devtools.artifactregistry.v1.ListVersionsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.devtools.artifactregistry.v1.ListVersionsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.devtools.artifactregistry.v1.ListVersionsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The response from listing versions.
* </pre>
*
* Protobuf type {@code google.devtools.artifactregistry.v1.ListVersionsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.devtools.artifactregistry.v1.ListVersionsResponse)
com.google.devtools.artifactregistry.v1.ListVersionsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.devtools.artifactregistry.v1.VersionProto
.internal_static_google_devtools_artifactregistry_v1_ListVersionsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.devtools.artifactregistry.v1.VersionProto
.internal_static_google_devtools_artifactregistry_v1_ListVersionsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.devtools.artifactregistry.v1.ListVersionsResponse.class,
com.google.devtools.artifactregistry.v1.ListVersionsResponse.Builder.class);
}
// Construct using com.google.devtools.artifactregistry.v1.ListVersionsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (versionsBuilder_ == null) {
versions_ = java.util.Collections.emptyList();
} else {
versions_ = null;
versionsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.devtools.artifactregistry.v1.VersionProto
.internal_static_google_devtools_artifactregistry_v1_ListVersionsResponse_descriptor;
}
@java.lang.Override
public com.google.devtools.artifactregistry.v1.ListVersionsResponse
getDefaultInstanceForType() {
return com.google.devtools.artifactregistry.v1.ListVersionsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.devtools.artifactregistry.v1.ListVersionsResponse build() {
com.google.devtools.artifactregistry.v1.ListVersionsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.devtools.artifactregistry.v1.ListVersionsResponse buildPartial() {
com.google.devtools.artifactregistry.v1.ListVersionsResponse result =
new com.google.devtools.artifactregistry.v1.ListVersionsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.devtools.artifactregistry.v1.ListVersionsResponse result) {
if (versionsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
versions_ = java.util.Collections.unmodifiableList(versions_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.versions_ = versions_;
} else {
result.versions_ = versionsBuilder_.build();
}
}
private void buildPartial0(
com.google.devtools.artifactregistry.v1.ListVersionsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.devtools.artifactregistry.v1.ListVersionsResponse) {
return mergeFrom((com.google.devtools.artifactregistry.v1.ListVersionsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.devtools.artifactregistry.v1.ListVersionsResponse other) {
if (other
== com.google.devtools.artifactregistry.v1.ListVersionsResponse.getDefaultInstance())
return this;
if (versionsBuilder_ == null) {
if (!other.versions_.isEmpty()) {
if (versions_.isEmpty()) {
versions_ = other.versions_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureVersionsIsMutable();
versions_.addAll(other.versions_);
}
onChanged();
}
} else {
if (!other.versions_.isEmpty()) {
if (versionsBuilder_.isEmpty()) {
versionsBuilder_.dispose();
versionsBuilder_ = null;
versions_ = other.versions_;
bitField0_ = (bitField0_ & ~0x00000001);
versionsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getVersionsFieldBuilder()
: null;
} else {
versionsBuilder_.addAllMessages(other.versions_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.devtools.artifactregistry.v1.Version m =
input.readMessage(
com.google.devtools.artifactregistry.v1.Version.parser(),
extensionRegistry);
if (versionsBuilder_ == null) {
ensureVersionsIsMutable();
versions_.add(m);
} else {
versionsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.devtools.artifactregistry.v1.Version> versions_ =
java.util.Collections.emptyList();
private void ensureVersionsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
versions_ =
new java.util.ArrayList<com.google.devtools.artifactregistry.v1.Version>(versions_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.devtools.artifactregistry.v1.Version,
com.google.devtools.artifactregistry.v1.Version.Builder,
com.google.devtools.artifactregistry.v1.VersionOrBuilder>
versionsBuilder_;
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public java.util.List<com.google.devtools.artifactregistry.v1.Version> getVersionsList() {
if (versionsBuilder_ == null) {
return java.util.Collections.unmodifiableList(versions_);
} else {
return versionsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public int getVersionsCount() {
if (versionsBuilder_ == null) {
return versions_.size();
} else {
return versionsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public com.google.devtools.artifactregistry.v1.Version getVersions(int index) {
if (versionsBuilder_ == null) {
return versions_.get(index);
} else {
return versionsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public Builder setVersions(int index, com.google.devtools.artifactregistry.v1.Version value) {
if (versionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureVersionsIsMutable();
versions_.set(index, value);
onChanged();
} else {
versionsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public Builder setVersions(
int index, com.google.devtools.artifactregistry.v1.Version.Builder builderForValue) {
if (versionsBuilder_ == null) {
ensureVersionsIsMutable();
versions_.set(index, builderForValue.build());
onChanged();
} else {
versionsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public Builder addVersions(com.google.devtools.artifactregistry.v1.Version value) {
if (versionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureVersionsIsMutable();
versions_.add(value);
onChanged();
} else {
versionsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public Builder addVersions(int index, com.google.devtools.artifactregistry.v1.Version value) {
if (versionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureVersionsIsMutable();
versions_.add(index, value);
onChanged();
} else {
versionsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public Builder addVersions(
com.google.devtools.artifactregistry.v1.Version.Builder builderForValue) {
if (versionsBuilder_ == null) {
ensureVersionsIsMutable();
versions_.add(builderForValue.build());
onChanged();
} else {
versionsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public Builder addVersions(
int index, com.google.devtools.artifactregistry.v1.Version.Builder builderForValue) {
if (versionsBuilder_ == null) {
ensureVersionsIsMutable();
versions_.add(index, builderForValue.build());
onChanged();
} else {
versionsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public Builder addAllVersions(
java.lang.Iterable<? extends com.google.devtools.artifactregistry.v1.Version> values) {
if (versionsBuilder_ == null) {
ensureVersionsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, versions_);
onChanged();
} else {
versionsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public Builder clearVersions() {
if (versionsBuilder_ == null) {
versions_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
versionsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public Builder removeVersions(int index) {
if (versionsBuilder_ == null) {
ensureVersionsIsMutable();
versions_.remove(index);
onChanged();
} else {
versionsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public com.google.devtools.artifactregistry.v1.Version.Builder getVersionsBuilder(int index) {
return getVersionsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public com.google.devtools.artifactregistry.v1.VersionOrBuilder getVersionsOrBuilder(
int index) {
if (versionsBuilder_ == null) {
return versions_.get(index);
} else {
return versionsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public java.util.List<? extends com.google.devtools.artifactregistry.v1.VersionOrBuilder>
getVersionsOrBuilderList() {
if (versionsBuilder_ != null) {
return versionsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(versions_);
}
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public com.google.devtools.artifactregistry.v1.Version.Builder addVersionsBuilder() {
return getVersionsFieldBuilder()
.addBuilder(com.google.devtools.artifactregistry.v1.Version.getDefaultInstance());
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public com.google.devtools.artifactregistry.v1.Version.Builder addVersionsBuilder(int index) {
return getVersionsFieldBuilder()
.addBuilder(index, com.google.devtools.artifactregistry.v1.Version.getDefaultInstance());
}
/**
*
*
* <pre>
* The versions returned.
* </pre>
*
* <code>repeated .google.devtools.artifactregistry.v1.Version versions = 1;</code>
*/
public java.util.List<com.google.devtools.artifactregistry.v1.Version.Builder>
getVersionsBuilderList() {
return getVersionsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.devtools.artifactregistry.v1.Version,
com.google.devtools.artifactregistry.v1.Version.Builder,
com.google.devtools.artifactregistry.v1.VersionOrBuilder>
getVersionsFieldBuilder() {
if (versionsBuilder_ == null) {
versionsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.devtools.artifactregistry.v1.Version,
com.google.devtools.artifactregistry.v1.Version.Builder,
com.google.devtools.artifactregistry.v1.VersionOrBuilder>(
versions_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
versions_ = null;
}
return versionsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* The token to retrieve the next page of versions, or empty if there are no
* more versions to return.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The token to retrieve the next page of versions, or empty if there are no
* more versions to return.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The token to retrieve the next page of versions, or empty if there are no
* more versions to return.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The token to retrieve the next page of versions, or empty if there are no
* more versions to return.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The token to retrieve the next page of versions, or empty if there are no
* more versions to return.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.devtools.artifactregistry.v1.ListVersionsResponse)
}
// @@protoc_insertion_point(class_scope:google.devtools.artifactregistry.v1.ListVersionsResponse)
private static final com.google.devtools.artifactregistry.v1.ListVersionsResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.devtools.artifactregistry.v1.ListVersionsResponse();
}
public static com.google.devtools.artifactregistry.v1.ListVersionsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListVersionsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListVersionsResponse>() {
@java.lang.Override
public ListVersionsResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListVersionsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListVersionsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.devtools.artifactregistry.v1.ListVersionsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,423 | java-dataform/proto-google-cloud-dataform-v1/src/main/java/com/google/cloud/dataform/v1/CreateWorkspaceRequest.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>
* `CreateWorkspace` request message.
* </pre>
*
* Protobuf type {@code google.cloud.dataform.v1.CreateWorkspaceRequest}
*/
public final class CreateWorkspaceRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dataform.v1.CreateWorkspaceRequest)
CreateWorkspaceRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateWorkspaceRequest.newBuilder() to construct.
private CreateWorkspaceRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateWorkspaceRequest() {
parent_ = "";
workspaceId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateWorkspaceRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dataform.v1.DataformProto
.internal_static_google_cloud_dataform_v1_CreateWorkspaceRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dataform.v1.DataformProto
.internal_static_google_cloud_dataform_v1_CreateWorkspaceRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dataform.v1.CreateWorkspaceRequest.class,
com.google.cloud.dataform.v1.CreateWorkspaceRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The repository in which to create the workspace. Must be in the
* format `projects/*/locations/*/repositories/*`.
* </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 repository in which to create the workspace. Must be in the
* format `projects/*/locations/*/repositories/*`.
* </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 WORKSPACE_FIELD_NUMBER = 2;
private com.google.cloud.dataform.v1.Workspace workspace_;
/**
*
*
* <pre>
* Required. The workspace to create.
* </pre>
*
* <code>
* .google.cloud.dataform.v1.Workspace workspace = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the workspace field is set.
*/
@java.lang.Override
public boolean hasWorkspace() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The workspace to create.
* </pre>
*
* <code>
* .google.cloud.dataform.v1.Workspace workspace = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The workspace.
*/
@java.lang.Override
public com.google.cloud.dataform.v1.Workspace getWorkspace() {
return workspace_ == null
? com.google.cloud.dataform.v1.Workspace.getDefaultInstance()
: workspace_;
}
/**
*
*
* <pre>
* Required. The workspace to create.
* </pre>
*
* <code>
* .google.cloud.dataform.v1.Workspace workspace = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.dataform.v1.WorkspaceOrBuilder getWorkspaceOrBuilder() {
return workspace_ == null
? com.google.cloud.dataform.v1.Workspace.getDefaultInstance()
: workspace_;
}
public static final int WORKSPACE_ID_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object workspaceId_ = "";
/**
*
*
* <pre>
* Required. The ID to use for the workspace, which will become the final
* component of the workspace's resource name.
* </pre>
*
* <code>string workspace_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The workspaceId.
*/
@java.lang.Override
public java.lang.String getWorkspaceId() {
java.lang.Object ref = workspaceId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
workspaceId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The ID to use for the workspace, which will become the final
* component of the workspace's resource name.
* </pre>
*
* <code>string workspace_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for workspaceId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getWorkspaceIdBytes() {
java.lang.Object ref = workspaceId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
workspaceId_ = 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, getWorkspace());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(workspaceId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, workspaceId_);
}
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, getWorkspace());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(workspaceId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, workspaceId_);
}
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.CreateWorkspaceRequest)) {
return super.equals(obj);
}
com.google.cloud.dataform.v1.CreateWorkspaceRequest other =
(com.google.cloud.dataform.v1.CreateWorkspaceRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (hasWorkspace() != other.hasWorkspace()) return false;
if (hasWorkspace()) {
if (!getWorkspace().equals(other.getWorkspace())) return false;
}
if (!getWorkspaceId().equals(other.getWorkspaceId())) 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 (hasWorkspace()) {
hash = (37 * hash) + WORKSPACE_FIELD_NUMBER;
hash = (53 * hash) + getWorkspace().hashCode();
}
hash = (37 * hash) + WORKSPACE_ID_FIELD_NUMBER;
hash = (53 * hash) + getWorkspaceId().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dataform.v1.CreateWorkspaceRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataform.v1.CreateWorkspaceRequest 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.CreateWorkspaceRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataform.v1.CreateWorkspaceRequest 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.CreateWorkspaceRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dataform.v1.CreateWorkspaceRequest 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.CreateWorkspaceRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dataform.v1.CreateWorkspaceRequest 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.CreateWorkspaceRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dataform.v1.CreateWorkspaceRequest 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.CreateWorkspaceRequest 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.CreateWorkspaceRequest 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.CreateWorkspaceRequest 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>
* `CreateWorkspace` request message.
* </pre>
*
* Protobuf type {@code google.cloud.dataform.v1.CreateWorkspaceRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dataform.v1.CreateWorkspaceRequest)
com.google.cloud.dataform.v1.CreateWorkspaceRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dataform.v1.DataformProto
.internal_static_google_cloud_dataform_v1_CreateWorkspaceRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dataform.v1.DataformProto
.internal_static_google_cloud_dataform_v1_CreateWorkspaceRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dataform.v1.CreateWorkspaceRequest.class,
com.google.cloud.dataform.v1.CreateWorkspaceRequest.Builder.class);
}
// Construct using com.google.cloud.dataform.v1.CreateWorkspaceRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getWorkspaceFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
workspace_ = null;
if (workspaceBuilder_ != null) {
workspaceBuilder_.dispose();
workspaceBuilder_ = null;
}
workspaceId_ = "";
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_CreateWorkspaceRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.dataform.v1.CreateWorkspaceRequest getDefaultInstanceForType() {
return com.google.cloud.dataform.v1.CreateWorkspaceRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dataform.v1.CreateWorkspaceRequest build() {
com.google.cloud.dataform.v1.CreateWorkspaceRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dataform.v1.CreateWorkspaceRequest buildPartial() {
com.google.cloud.dataform.v1.CreateWorkspaceRequest result =
new com.google.cloud.dataform.v1.CreateWorkspaceRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.dataform.v1.CreateWorkspaceRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.workspace_ = workspaceBuilder_ == null ? workspace_ : workspaceBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.workspaceId_ = workspaceId_;
}
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.dataform.v1.CreateWorkspaceRequest) {
return mergeFrom((com.google.cloud.dataform.v1.CreateWorkspaceRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dataform.v1.CreateWorkspaceRequest other) {
if (other == com.google.cloud.dataform.v1.CreateWorkspaceRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasWorkspace()) {
mergeWorkspace(other.getWorkspace());
}
if (!other.getWorkspaceId().isEmpty()) {
workspaceId_ = other.workspaceId_;
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(getWorkspaceFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
workspaceId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The repository in which to create the workspace. Must be in the
* format `projects/*/locations/*/repositories/*`.
* </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 repository in which to create the workspace. Must be in the
* format `projects/*/locations/*/repositories/*`.
* </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 repository in which to create the workspace. Must be in the
* format `projects/*/locations/*/repositories/*`.
* </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 repository in which to create the workspace. Must be in the
* format `projects/*/locations/*/repositories/*`.
* </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 repository in which to create the workspace. Must be in the
* format `projects/*/locations/*/repositories/*`.
* </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.dataform.v1.Workspace workspace_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dataform.v1.Workspace,
com.google.cloud.dataform.v1.Workspace.Builder,
com.google.cloud.dataform.v1.WorkspaceOrBuilder>
workspaceBuilder_;
/**
*
*
* <pre>
* Required. The workspace to create.
* </pre>
*
* <code>
* .google.cloud.dataform.v1.Workspace workspace = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the workspace field is set.
*/
public boolean hasWorkspace() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The workspace to create.
* </pre>
*
* <code>
* .google.cloud.dataform.v1.Workspace workspace = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The workspace.
*/
public com.google.cloud.dataform.v1.Workspace getWorkspace() {
if (workspaceBuilder_ == null) {
return workspace_ == null
? com.google.cloud.dataform.v1.Workspace.getDefaultInstance()
: workspace_;
} else {
return workspaceBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The workspace to create.
* </pre>
*
* <code>
* .google.cloud.dataform.v1.Workspace workspace = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setWorkspace(com.google.cloud.dataform.v1.Workspace value) {
if (workspaceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
workspace_ = value;
} else {
workspaceBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The workspace to create.
* </pre>
*
* <code>
* .google.cloud.dataform.v1.Workspace workspace = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setWorkspace(com.google.cloud.dataform.v1.Workspace.Builder builderForValue) {
if (workspaceBuilder_ == null) {
workspace_ = builderForValue.build();
} else {
workspaceBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The workspace to create.
* </pre>
*
* <code>
* .google.cloud.dataform.v1.Workspace workspace = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeWorkspace(com.google.cloud.dataform.v1.Workspace value) {
if (workspaceBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& workspace_ != null
&& workspace_ != com.google.cloud.dataform.v1.Workspace.getDefaultInstance()) {
getWorkspaceBuilder().mergeFrom(value);
} else {
workspace_ = value;
}
} else {
workspaceBuilder_.mergeFrom(value);
}
if (workspace_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The workspace to create.
* </pre>
*
* <code>
* .google.cloud.dataform.v1.Workspace workspace = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearWorkspace() {
bitField0_ = (bitField0_ & ~0x00000002);
workspace_ = null;
if (workspaceBuilder_ != null) {
workspaceBuilder_.dispose();
workspaceBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The workspace to create.
* </pre>
*
* <code>
* .google.cloud.dataform.v1.Workspace workspace = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.dataform.v1.Workspace.Builder getWorkspaceBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getWorkspaceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The workspace to create.
* </pre>
*
* <code>
* .google.cloud.dataform.v1.Workspace workspace = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.dataform.v1.WorkspaceOrBuilder getWorkspaceOrBuilder() {
if (workspaceBuilder_ != null) {
return workspaceBuilder_.getMessageOrBuilder();
} else {
return workspace_ == null
? com.google.cloud.dataform.v1.Workspace.getDefaultInstance()
: workspace_;
}
}
/**
*
*
* <pre>
* Required. The workspace to create.
* </pre>
*
* <code>
* .google.cloud.dataform.v1.Workspace workspace = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dataform.v1.Workspace,
com.google.cloud.dataform.v1.Workspace.Builder,
com.google.cloud.dataform.v1.WorkspaceOrBuilder>
getWorkspaceFieldBuilder() {
if (workspaceBuilder_ == null) {
workspaceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dataform.v1.Workspace,
com.google.cloud.dataform.v1.Workspace.Builder,
com.google.cloud.dataform.v1.WorkspaceOrBuilder>(
getWorkspace(), getParentForChildren(), isClean());
workspace_ = null;
}
return workspaceBuilder_;
}
private java.lang.Object workspaceId_ = "";
/**
*
*
* <pre>
* Required. The ID to use for the workspace, which will become the final
* component of the workspace's resource name.
* </pre>
*
* <code>string workspace_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The workspaceId.
*/
public java.lang.String getWorkspaceId() {
java.lang.Object ref = workspaceId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
workspaceId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The ID to use for the workspace, which will become the final
* component of the workspace's resource name.
* </pre>
*
* <code>string workspace_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for workspaceId.
*/
public com.google.protobuf.ByteString getWorkspaceIdBytes() {
java.lang.Object ref = workspaceId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
workspaceId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The ID to use for the workspace, which will become the final
* component of the workspace's resource name.
* </pre>
*
* <code>string workspace_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The workspaceId to set.
* @return This builder for chaining.
*/
public Builder setWorkspaceId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
workspaceId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ID to use for the workspace, which will become the final
* component of the workspace's resource name.
* </pre>
*
* <code>string workspace_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearWorkspaceId() {
workspaceId_ = getDefaultInstance().getWorkspaceId();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ID to use for the workspace, which will become the final
* component of the workspace's resource name.
* </pre>
*
* <code>string workspace_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for workspaceId to set.
* @return This builder for chaining.
*/
public Builder setWorkspaceIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
workspaceId_ = 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.dataform.v1.CreateWorkspaceRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.dataform.v1.CreateWorkspaceRequest)
private static final com.google.cloud.dataform.v1.CreateWorkspaceRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dataform.v1.CreateWorkspaceRequest();
}
public static com.google.cloud.dataform.v1.CreateWorkspaceRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateWorkspaceRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateWorkspaceRequest>() {
@java.lang.Override
public CreateWorkspaceRequest 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<CreateWorkspaceRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateWorkspaceRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dataform.v1.CreateWorkspaceRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,806 | java-telcoautomation/google-cloud-telcoautomation/src/main/java/com/google/cloud/telcoautomation/v1alpha1/TelcoAutomationSettings.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.telcoautomation.v1alpha1;
import static com.google.cloud.telcoautomation.v1alpha1.TelcoAutomationClient.ListBlueprintRevisionsPagedResponse;
import static com.google.cloud.telcoautomation.v1alpha1.TelcoAutomationClient.ListBlueprintsPagedResponse;
import static com.google.cloud.telcoautomation.v1alpha1.TelcoAutomationClient.ListDeploymentRevisionsPagedResponse;
import static com.google.cloud.telcoautomation.v1alpha1.TelcoAutomationClient.ListDeploymentsPagedResponse;
import static com.google.cloud.telcoautomation.v1alpha1.TelcoAutomationClient.ListEdgeSlmsPagedResponse;
import static com.google.cloud.telcoautomation.v1alpha1.TelcoAutomationClient.ListHydratedDeploymentsPagedResponse;
import static com.google.cloud.telcoautomation.v1alpha1.TelcoAutomationClient.ListLocationsPagedResponse;
import static com.google.cloud.telcoautomation.v1alpha1.TelcoAutomationClient.ListOrchestrationClustersPagedResponse;
import static com.google.cloud.telcoautomation.v1alpha1.TelcoAutomationClient.ListPublicBlueprintsPagedResponse;
import static com.google.cloud.telcoautomation.v1alpha1.TelcoAutomationClient.SearchBlueprintRevisionsPagedResponse;
import static com.google.cloud.telcoautomation.v1alpha1.TelcoAutomationClient.SearchDeploymentRevisionsPagedResponse;
import com.google.api.core.ApiFunction;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.ClientSettings;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.cloud.location.GetLocationRequest;
import com.google.cloud.location.ListLocationsRequest;
import com.google.cloud.location.ListLocationsResponse;
import com.google.cloud.location.Location;
import com.google.cloud.telcoautomation.v1alpha1.stub.TelcoAutomationStubSettings;
import com.google.longrunning.Operation;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.List;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Settings class to configure an instance of {@link TelcoAutomationClient}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (telcoautomation.googleapis.com) and default port (443) are
* used.
* <li>Credentials are acquired automatically through Application Default Credentials.
* <li>Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object.
*
* <p>For example, to set the
* [RetrySettings](https://cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.retrying.RetrySettings)
* of getOrchestrationCluster:
*
* <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
* TelcoAutomationSettings.Builder telcoAutomationSettingsBuilder =
* TelcoAutomationSettings.newBuilder();
* telcoAutomationSettingsBuilder
* .getOrchestrationClusterSettings()
* .setRetrySettings(
* telcoAutomationSettingsBuilder
* .getOrchestrationClusterSettings()
* .getRetrySettings()
* .toBuilder()
* .setInitialRetryDelayDuration(Duration.ofSeconds(1))
* .setInitialRpcTimeoutDuration(Duration.ofSeconds(5))
* .setMaxAttempts(5)
* .setMaxRetryDelayDuration(Duration.ofSeconds(30))
* .setMaxRpcTimeoutDuration(Duration.ofSeconds(60))
* .setRetryDelayMultiplier(1.3)
* .setRpcTimeoutMultiplier(1.5)
* .setTotalTimeoutDuration(Duration.ofSeconds(300))
* .build());
* TelcoAutomationSettings telcoAutomationSettings = telcoAutomationSettingsBuilder.build();
* }</pre>
*
* Please refer to the [Client Side Retry
* Guide](https://github.com/googleapis/google-cloud-java/blob/main/docs/client_retries.md) for
* additional support in setting retries.
*
* <p>To configure the RetrySettings of a Long Running Operation method, create an
* OperationTimedPollAlgorithm object and update the RPC's polling algorithm. For example, to
* configure the RetrySettings for createOrchestrationCluster:
*
* <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
* TelcoAutomationSettings.Builder telcoAutomationSettingsBuilder =
* TelcoAutomationSettings.newBuilder();
* TimedRetryAlgorithm timedRetryAlgorithm =
* OperationalTimedPollAlgorithm.create(
* RetrySettings.newBuilder()
* .setInitialRetryDelayDuration(Duration.ofMillis(500))
* .setRetryDelayMultiplier(1.5)
* .setMaxRetryDelayDuration(Duration.ofMillis(5000))
* .setTotalTimeoutDuration(Duration.ofHours(24))
* .build());
* telcoAutomationSettingsBuilder
* .createClusterOperationSettings()
* .setPollingAlgorithm(timedRetryAlgorithm)
* .build();
* }</pre>
*/
@BetaApi
@Generated("by gapic-generator-java")
public class TelcoAutomationSettings extends ClientSettings<TelcoAutomationSettings> {
/** Returns the object with the settings used for calls to listOrchestrationClusters. */
public PagedCallSettings<
ListOrchestrationClustersRequest,
ListOrchestrationClustersResponse,
ListOrchestrationClustersPagedResponse>
listOrchestrationClustersSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).listOrchestrationClustersSettings();
}
/** Returns the object with the settings used for calls to getOrchestrationCluster. */
public UnaryCallSettings<GetOrchestrationClusterRequest, OrchestrationCluster>
getOrchestrationClusterSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).getOrchestrationClusterSettings();
}
/** Returns the object with the settings used for calls to createOrchestrationCluster. */
public UnaryCallSettings<CreateOrchestrationClusterRequest, Operation>
createOrchestrationClusterSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).createOrchestrationClusterSettings();
}
/** Returns the object with the settings used for calls to createOrchestrationCluster. */
public OperationCallSettings<
CreateOrchestrationClusterRequest, OrchestrationCluster, OperationMetadata>
createOrchestrationClusterOperationSettings() {
return ((TelcoAutomationStubSettings) getStubSettings())
.createOrchestrationClusterOperationSettings();
}
/** Returns the object with the settings used for calls to deleteOrchestrationCluster. */
public UnaryCallSettings<DeleteOrchestrationClusterRequest, Operation>
deleteOrchestrationClusterSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).deleteOrchestrationClusterSettings();
}
/** Returns the object with the settings used for calls to deleteOrchestrationCluster. */
public OperationCallSettings<DeleteOrchestrationClusterRequest, Empty, OperationMetadata>
deleteOrchestrationClusterOperationSettings() {
return ((TelcoAutomationStubSettings) getStubSettings())
.deleteOrchestrationClusterOperationSettings();
}
/** Returns the object with the settings used for calls to listEdgeSlms. */
public PagedCallSettings<ListEdgeSlmsRequest, ListEdgeSlmsResponse, ListEdgeSlmsPagedResponse>
listEdgeSlmsSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).listEdgeSlmsSettings();
}
/** Returns the object with the settings used for calls to getEdgeSlm. */
public UnaryCallSettings<GetEdgeSlmRequest, EdgeSlm> getEdgeSlmSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).getEdgeSlmSettings();
}
/** Returns the object with the settings used for calls to createEdgeSlm. */
public UnaryCallSettings<CreateEdgeSlmRequest, Operation> createEdgeSlmSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).createEdgeSlmSettings();
}
/** Returns the object with the settings used for calls to createEdgeSlm. */
public OperationCallSettings<CreateEdgeSlmRequest, EdgeSlm, OperationMetadata>
createEdgeSlmOperationSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).createEdgeSlmOperationSettings();
}
/** Returns the object with the settings used for calls to deleteEdgeSlm. */
public UnaryCallSettings<DeleteEdgeSlmRequest, Operation> deleteEdgeSlmSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).deleteEdgeSlmSettings();
}
/** Returns the object with the settings used for calls to deleteEdgeSlm. */
public OperationCallSettings<DeleteEdgeSlmRequest, Empty, OperationMetadata>
deleteEdgeSlmOperationSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).deleteEdgeSlmOperationSettings();
}
/** Returns the object with the settings used for calls to createBlueprint. */
public UnaryCallSettings<CreateBlueprintRequest, Blueprint> createBlueprintSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).createBlueprintSettings();
}
/** Returns the object with the settings used for calls to updateBlueprint. */
public UnaryCallSettings<UpdateBlueprintRequest, Blueprint> updateBlueprintSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).updateBlueprintSettings();
}
/** Returns the object with the settings used for calls to getBlueprint. */
public UnaryCallSettings<GetBlueprintRequest, Blueprint> getBlueprintSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).getBlueprintSettings();
}
/** Returns the object with the settings used for calls to deleteBlueprint. */
public UnaryCallSettings<DeleteBlueprintRequest, Empty> deleteBlueprintSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).deleteBlueprintSettings();
}
/** Returns the object with the settings used for calls to listBlueprints. */
public PagedCallSettings<
ListBlueprintsRequest, ListBlueprintsResponse, ListBlueprintsPagedResponse>
listBlueprintsSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).listBlueprintsSettings();
}
/** Returns the object with the settings used for calls to approveBlueprint. */
public UnaryCallSettings<ApproveBlueprintRequest, Blueprint> approveBlueprintSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).approveBlueprintSettings();
}
/** Returns the object with the settings used for calls to proposeBlueprint. */
public UnaryCallSettings<ProposeBlueprintRequest, Blueprint> proposeBlueprintSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).proposeBlueprintSettings();
}
/** Returns the object with the settings used for calls to rejectBlueprint. */
public UnaryCallSettings<RejectBlueprintRequest, Blueprint> rejectBlueprintSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).rejectBlueprintSettings();
}
/** Returns the object with the settings used for calls to listBlueprintRevisions. */
public PagedCallSettings<
ListBlueprintRevisionsRequest,
ListBlueprintRevisionsResponse,
ListBlueprintRevisionsPagedResponse>
listBlueprintRevisionsSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).listBlueprintRevisionsSettings();
}
/** Returns the object with the settings used for calls to searchBlueprintRevisions. */
public PagedCallSettings<
SearchBlueprintRevisionsRequest,
SearchBlueprintRevisionsResponse,
SearchBlueprintRevisionsPagedResponse>
searchBlueprintRevisionsSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).searchBlueprintRevisionsSettings();
}
/** Returns the object with the settings used for calls to searchDeploymentRevisions. */
public PagedCallSettings<
SearchDeploymentRevisionsRequest,
SearchDeploymentRevisionsResponse,
SearchDeploymentRevisionsPagedResponse>
searchDeploymentRevisionsSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).searchDeploymentRevisionsSettings();
}
/** Returns the object with the settings used for calls to discardBlueprintChanges. */
public UnaryCallSettings<DiscardBlueprintChangesRequest, DiscardBlueprintChangesResponse>
discardBlueprintChangesSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).discardBlueprintChangesSettings();
}
/** Returns the object with the settings used for calls to listPublicBlueprints. */
public PagedCallSettings<
ListPublicBlueprintsRequest,
ListPublicBlueprintsResponse,
ListPublicBlueprintsPagedResponse>
listPublicBlueprintsSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).listPublicBlueprintsSettings();
}
/** Returns the object with the settings used for calls to getPublicBlueprint. */
public UnaryCallSettings<GetPublicBlueprintRequest, PublicBlueprint>
getPublicBlueprintSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).getPublicBlueprintSettings();
}
/** Returns the object with the settings used for calls to createDeployment. */
public UnaryCallSettings<CreateDeploymentRequest, Deployment> createDeploymentSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).createDeploymentSettings();
}
/** Returns the object with the settings used for calls to updateDeployment. */
public UnaryCallSettings<UpdateDeploymentRequest, Deployment> updateDeploymentSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).updateDeploymentSettings();
}
/** Returns the object with the settings used for calls to getDeployment. */
public UnaryCallSettings<GetDeploymentRequest, Deployment> getDeploymentSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).getDeploymentSettings();
}
/** Returns the object with the settings used for calls to removeDeployment. */
public UnaryCallSettings<RemoveDeploymentRequest, Empty> removeDeploymentSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).removeDeploymentSettings();
}
/** Returns the object with the settings used for calls to listDeployments. */
public PagedCallSettings<
ListDeploymentsRequest, ListDeploymentsResponse, ListDeploymentsPagedResponse>
listDeploymentsSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).listDeploymentsSettings();
}
/** Returns the object with the settings used for calls to listDeploymentRevisions. */
public PagedCallSettings<
ListDeploymentRevisionsRequest,
ListDeploymentRevisionsResponse,
ListDeploymentRevisionsPagedResponse>
listDeploymentRevisionsSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).listDeploymentRevisionsSettings();
}
/** Returns the object with the settings used for calls to discardDeploymentChanges. */
public UnaryCallSettings<DiscardDeploymentChangesRequest, DiscardDeploymentChangesResponse>
discardDeploymentChangesSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).discardDeploymentChangesSettings();
}
/** Returns the object with the settings used for calls to applyDeployment. */
public UnaryCallSettings<ApplyDeploymentRequest, Deployment> applyDeploymentSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).applyDeploymentSettings();
}
/** Returns the object with the settings used for calls to computeDeploymentStatus. */
public UnaryCallSettings<ComputeDeploymentStatusRequest, ComputeDeploymentStatusResponse>
computeDeploymentStatusSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).computeDeploymentStatusSettings();
}
/** Returns the object with the settings used for calls to rollbackDeployment. */
public UnaryCallSettings<RollbackDeploymentRequest, Deployment> rollbackDeploymentSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).rollbackDeploymentSettings();
}
/** Returns the object with the settings used for calls to getHydratedDeployment. */
public UnaryCallSettings<GetHydratedDeploymentRequest, HydratedDeployment>
getHydratedDeploymentSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).getHydratedDeploymentSettings();
}
/** Returns the object with the settings used for calls to listHydratedDeployments. */
public PagedCallSettings<
ListHydratedDeploymentsRequest,
ListHydratedDeploymentsResponse,
ListHydratedDeploymentsPagedResponse>
listHydratedDeploymentsSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).listHydratedDeploymentsSettings();
}
/** Returns the object with the settings used for calls to updateHydratedDeployment. */
public UnaryCallSettings<UpdateHydratedDeploymentRequest, HydratedDeployment>
updateHydratedDeploymentSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).updateHydratedDeploymentSettings();
}
/** Returns the object with the settings used for calls to applyHydratedDeployment. */
public UnaryCallSettings<ApplyHydratedDeploymentRequest, HydratedDeployment>
applyHydratedDeploymentSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).applyHydratedDeploymentSettings();
}
/** Returns the object with the settings used for calls to listLocations. */
public PagedCallSettings<ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse>
listLocationsSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).listLocationsSettings();
}
/** Returns the object with the settings used for calls to getLocation. */
public UnaryCallSettings<GetLocationRequest, Location> getLocationSettings() {
return ((TelcoAutomationStubSettings) getStubSettings()).getLocationSettings();
}
public static final TelcoAutomationSettings create(TelcoAutomationStubSettings stub)
throws IOException {
return new TelcoAutomationSettings.Builder(stub.toBuilder()).build();
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return TelcoAutomationStubSettings.defaultExecutorProviderBuilder();
}
/** Returns the default service endpoint. */
public static String getDefaultEndpoint() {
return TelcoAutomationStubSettings.getDefaultEndpoint();
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return TelcoAutomationStubSettings.getDefaultServiceScopes();
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return TelcoAutomationStubSettings.defaultCredentialsProviderBuilder();
}
/** Returns a builder for the default gRPC ChannelProvider for this service. */
public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() {
return TelcoAutomationStubSettings.defaultGrpcTransportProviderBuilder();
}
/** Returns a builder for the default REST ChannelProvider for this service. */
@BetaApi
public static InstantiatingHttpJsonChannelProvider.Builder
defaultHttpJsonTransportProviderBuilder() {
return TelcoAutomationStubSettings.defaultHttpJsonTransportProviderBuilder();
}
public static TransportChannelProvider defaultTransportChannelProvider() {
return TelcoAutomationStubSettings.defaultTransportChannelProvider();
}
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return TelcoAutomationStubSettings.defaultApiClientHeaderProviderBuilder();
}
/** Returns a new gRPC builder for this class. */
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Returns a new REST builder for this class. */
public static Builder newHttpJsonBuilder() {
return Builder.createHttpJsonDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder(ClientContext clientContext) {
return new Builder(clientContext);
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
protected TelcoAutomationSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
}
/** Builder for TelcoAutomationSettings. */
public static class Builder extends ClientSettings.Builder<TelcoAutomationSettings, Builder> {
protected Builder() throws IOException {
this(((ClientContext) null));
}
protected Builder(ClientContext clientContext) {
super(TelcoAutomationStubSettings.newBuilder(clientContext));
}
protected Builder(TelcoAutomationSettings settings) {
super(settings.getStubSettings().toBuilder());
}
protected Builder(TelcoAutomationStubSettings.Builder stubSettings) {
super(stubSettings);
}
private static Builder createDefault() {
return new Builder(TelcoAutomationStubSettings.newBuilder());
}
private static Builder createHttpJsonDefault() {
return new Builder(TelcoAutomationStubSettings.newHttpJsonBuilder());
}
public TelcoAutomationStubSettings.Builder getStubSettingsBuilder() {
return ((TelcoAutomationStubSettings.Builder) getStubSettings());
}
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
super.applyToAllUnaryMethods(
getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater);
return this;
}
/** Returns the builder for the settings used for calls to listOrchestrationClusters. */
public PagedCallSettings.Builder<
ListOrchestrationClustersRequest,
ListOrchestrationClustersResponse,
ListOrchestrationClustersPagedResponse>
listOrchestrationClustersSettings() {
return getStubSettingsBuilder().listOrchestrationClustersSettings();
}
/** Returns the builder for the settings used for calls to getOrchestrationCluster. */
public UnaryCallSettings.Builder<GetOrchestrationClusterRequest, OrchestrationCluster>
getOrchestrationClusterSettings() {
return getStubSettingsBuilder().getOrchestrationClusterSettings();
}
/** Returns the builder for the settings used for calls to createOrchestrationCluster. */
public UnaryCallSettings.Builder<CreateOrchestrationClusterRequest, Operation>
createOrchestrationClusterSettings() {
return getStubSettingsBuilder().createOrchestrationClusterSettings();
}
/** Returns the builder for the settings used for calls to createOrchestrationCluster. */
public OperationCallSettings.Builder<
CreateOrchestrationClusterRequest, OrchestrationCluster, OperationMetadata>
createOrchestrationClusterOperationSettings() {
return getStubSettingsBuilder().createOrchestrationClusterOperationSettings();
}
/** Returns the builder for the settings used for calls to deleteOrchestrationCluster. */
public UnaryCallSettings.Builder<DeleteOrchestrationClusterRequest, Operation>
deleteOrchestrationClusterSettings() {
return getStubSettingsBuilder().deleteOrchestrationClusterSettings();
}
/** Returns the builder for the settings used for calls to deleteOrchestrationCluster. */
public OperationCallSettings.Builder<
DeleteOrchestrationClusterRequest, Empty, OperationMetadata>
deleteOrchestrationClusterOperationSettings() {
return getStubSettingsBuilder().deleteOrchestrationClusterOperationSettings();
}
/** Returns the builder for the settings used for calls to listEdgeSlms. */
public PagedCallSettings.Builder<
ListEdgeSlmsRequest, ListEdgeSlmsResponse, ListEdgeSlmsPagedResponse>
listEdgeSlmsSettings() {
return getStubSettingsBuilder().listEdgeSlmsSettings();
}
/** Returns the builder for the settings used for calls to getEdgeSlm. */
public UnaryCallSettings.Builder<GetEdgeSlmRequest, EdgeSlm> getEdgeSlmSettings() {
return getStubSettingsBuilder().getEdgeSlmSettings();
}
/** Returns the builder for the settings used for calls to createEdgeSlm. */
public UnaryCallSettings.Builder<CreateEdgeSlmRequest, Operation> createEdgeSlmSettings() {
return getStubSettingsBuilder().createEdgeSlmSettings();
}
/** Returns the builder for the settings used for calls to createEdgeSlm. */
public OperationCallSettings.Builder<CreateEdgeSlmRequest, EdgeSlm, OperationMetadata>
createEdgeSlmOperationSettings() {
return getStubSettingsBuilder().createEdgeSlmOperationSettings();
}
/** Returns the builder for the settings used for calls to deleteEdgeSlm. */
public UnaryCallSettings.Builder<DeleteEdgeSlmRequest, Operation> deleteEdgeSlmSettings() {
return getStubSettingsBuilder().deleteEdgeSlmSettings();
}
/** Returns the builder for the settings used for calls to deleteEdgeSlm. */
public OperationCallSettings.Builder<DeleteEdgeSlmRequest, Empty, OperationMetadata>
deleteEdgeSlmOperationSettings() {
return getStubSettingsBuilder().deleteEdgeSlmOperationSettings();
}
/** Returns the builder for the settings used for calls to createBlueprint. */
public UnaryCallSettings.Builder<CreateBlueprintRequest, Blueprint> createBlueprintSettings() {
return getStubSettingsBuilder().createBlueprintSettings();
}
/** Returns the builder for the settings used for calls to updateBlueprint. */
public UnaryCallSettings.Builder<UpdateBlueprintRequest, Blueprint> updateBlueprintSettings() {
return getStubSettingsBuilder().updateBlueprintSettings();
}
/** Returns the builder for the settings used for calls to getBlueprint. */
public UnaryCallSettings.Builder<GetBlueprintRequest, Blueprint> getBlueprintSettings() {
return getStubSettingsBuilder().getBlueprintSettings();
}
/** Returns the builder for the settings used for calls to deleteBlueprint. */
public UnaryCallSettings.Builder<DeleteBlueprintRequest, Empty> deleteBlueprintSettings() {
return getStubSettingsBuilder().deleteBlueprintSettings();
}
/** Returns the builder for the settings used for calls to listBlueprints. */
public PagedCallSettings.Builder<
ListBlueprintsRequest, ListBlueprintsResponse, ListBlueprintsPagedResponse>
listBlueprintsSettings() {
return getStubSettingsBuilder().listBlueprintsSettings();
}
/** Returns the builder for the settings used for calls to approveBlueprint. */
public UnaryCallSettings.Builder<ApproveBlueprintRequest, Blueprint>
approveBlueprintSettings() {
return getStubSettingsBuilder().approveBlueprintSettings();
}
/** Returns the builder for the settings used for calls to proposeBlueprint. */
public UnaryCallSettings.Builder<ProposeBlueprintRequest, Blueprint>
proposeBlueprintSettings() {
return getStubSettingsBuilder().proposeBlueprintSettings();
}
/** Returns the builder for the settings used for calls to rejectBlueprint. */
public UnaryCallSettings.Builder<RejectBlueprintRequest, Blueprint> rejectBlueprintSettings() {
return getStubSettingsBuilder().rejectBlueprintSettings();
}
/** Returns the builder for the settings used for calls to listBlueprintRevisions. */
public PagedCallSettings.Builder<
ListBlueprintRevisionsRequest,
ListBlueprintRevisionsResponse,
ListBlueprintRevisionsPagedResponse>
listBlueprintRevisionsSettings() {
return getStubSettingsBuilder().listBlueprintRevisionsSettings();
}
/** Returns the builder for the settings used for calls to searchBlueprintRevisions. */
public PagedCallSettings.Builder<
SearchBlueprintRevisionsRequest,
SearchBlueprintRevisionsResponse,
SearchBlueprintRevisionsPagedResponse>
searchBlueprintRevisionsSettings() {
return getStubSettingsBuilder().searchBlueprintRevisionsSettings();
}
/** Returns the builder for the settings used for calls to searchDeploymentRevisions. */
public PagedCallSettings.Builder<
SearchDeploymentRevisionsRequest,
SearchDeploymentRevisionsResponse,
SearchDeploymentRevisionsPagedResponse>
searchDeploymentRevisionsSettings() {
return getStubSettingsBuilder().searchDeploymentRevisionsSettings();
}
/** Returns the builder for the settings used for calls to discardBlueprintChanges. */
public UnaryCallSettings.Builder<
DiscardBlueprintChangesRequest, DiscardBlueprintChangesResponse>
discardBlueprintChangesSettings() {
return getStubSettingsBuilder().discardBlueprintChangesSettings();
}
/** Returns the builder for the settings used for calls to listPublicBlueprints. */
public PagedCallSettings.Builder<
ListPublicBlueprintsRequest,
ListPublicBlueprintsResponse,
ListPublicBlueprintsPagedResponse>
listPublicBlueprintsSettings() {
return getStubSettingsBuilder().listPublicBlueprintsSettings();
}
/** Returns the builder for the settings used for calls to getPublicBlueprint. */
public UnaryCallSettings.Builder<GetPublicBlueprintRequest, PublicBlueprint>
getPublicBlueprintSettings() {
return getStubSettingsBuilder().getPublicBlueprintSettings();
}
/** Returns the builder for the settings used for calls to createDeployment. */
public UnaryCallSettings.Builder<CreateDeploymentRequest, Deployment>
createDeploymentSettings() {
return getStubSettingsBuilder().createDeploymentSettings();
}
/** Returns the builder for the settings used for calls to updateDeployment. */
public UnaryCallSettings.Builder<UpdateDeploymentRequest, Deployment>
updateDeploymentSettings() {
return getStubSettingsBuilder().updateDeploymentSettings();
}
/** Returns the builder for the settings used for calls to getDeployment. */
public UnaryCallSettings.Builder<GetDeploymentRequest, Deployment> getDeploymentSettings() {
return getStubSettingsBuilder().getDeploymentSettings();
}
/** Returns the builder for the settings used for calls to removeDeployment. */
public UnaryCallSettings.Builder<RemoveDeploymentRequest, Empty> removeDeploymentSettings() {
return getStubSettingsBuilder().removeDeploymentSettings();
}
/** Returns the builder for the settings used for calls to listDeployments. */
public PagedCallSettings.Builder<
ListDeploymentsRequest, ListDeploymentsResponse, ListDeploymentsPagedResponse>
listDeploymentsSettings() {
return getStubSettingsBuilder().listDeploymentsSettings();
}
/** Returns the builder for the settings used for calls to listDeploymentRevisions. */
public PagedCallSettings.Builder<
ListDeploymentRevisionsRequest,
ListDeploymentRevisionsResponse,
ListDeploymentRevisionsPagedResponse>
listDeploymentRevisionsSettings() {
return getStubSettingsBuilder().listDeploymentRevisionsSettings();
}
/** Returns the builder for the settings used for calls to discardDeploymentChanges. */
public UnaryCallSettings.Builder<
DiscardDeploymentChangesRequest, DiscardDeploymentChangesResponse>
discardDeploymentChangesSettings() {
return getStubSettingsBuilder().discardDeploymentChangesSettings();
}
/** Returns the builder for the settings used for calls to applyDeployment. */
public UnaryCallSettings.Builder<ApplyDeploymentRequest, Deployment> applyDeploymentSettings() {
return getStubSettingsBuilder().applyDeploymentSettings();
}
/** Returns the builder for the settings used for calls to computeDeploymentStatus. */
public UnaryCallSettings.Builder<
ComputeDeploymentStatusRequest, ComputeDeploymentStatusResponse>
computeDeploymentStatusSettings() {
return getStubSettingsBuilder().computeDeploymentStatusSettings();
}
/** Returns the builder for the settings used for calls to rollbackDeployment. */
public UnaryCallSettings.Builder<RollbackDeploymentRequest, Deployment>
rollbackDeploymentSettings() {
return getStubSettingsBuilder().rollbackDeploymentSettings();
}
/** Returns the builder for the settings used for calls to getHydratedDeployment. */
public UnaryCallSettings.Builder<GetHydratedDeploymentRequest, HydratedDeployment>
getHydratedDeploymentSettings() {
return getStubSettingsBuilder().getHydratedDeploymentSettings();
}
/** Returns the builder for the settings used for calls to listHydratedDeployments. */
public PagedCallSettings.Builder<
ListHydratedDeploymentsRequest,
ListHydratedDeploymentsResponse,
ListHydratedDeploymentsPagedResponse>
listHydratedDeploymentsSettings() {
return getStubSettingsBuilder().listHydratedDeploymentsSettings();
}
/** Returns the builder for the settings used for calls to updateHydratedDeployment. */
public UnaryCallSettings.Builder<UpdateHydratedDeploymentRequest, HydratedDeployment>
updateHydratedDeploymentSettings() {
return getStubSettingsBuilder().updateHydratedDeploymentSettings();
}
/** Returns the builder for the settings used for calls to applyHydratedDeployment. */
public UnaryCallSettings.Builder<ApplyHydratedDeploymentRequest, HydratedDeployment>
applyHydratedDeploymentSettings() {
return getStubSettingsBuilder().applyHydratedDeploymentSettings();
}
/** Returns the builder for the settings used for calls to listLocations. */
public PagedCallSettings.Builder<
ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse>
listLocationsSettings() {
return getStubSettingsBuilder().listLocationsSettings();
}
/** Returns the builder for the settings used for calls to getLocation. */
public UnaryCallSettings.Builder<GetLocationRequest, Location> getLocationSettings() {
return getStubSettingsBuilder().getLocationSettings();
}
@Override
public TelcoAutomationSettings build() throws IOException {
return new TelcoAutomationSettings(this);
}
}
}
|
googleapis/sdk-platform-java | 36,486 | test/integration/goldens/pubsub/src/com/google/cloud/pubsub/v1/TopicAdminClientTest.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.pubsub.v1;
import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicSnapshotsPagedResponse;
import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicSubscriptionsPagedResponse;
import static com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicsPagedResponse;
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.grpc.GaxGrpcProperties;
import com.google.api.gax.grpc.testing.LocalChannelProvider;
import com.google.api.gax.grpc.testing.MockGrpcService;
import com.google.api.gax.grpc.testing.MockServiceHelper;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.common.collect.Lists;
import com.google.iam.v1.AuditConfig;
import com.google.iam.v1.Binding;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.GetPolicyOptions;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.iam.v1.TestIamPermissionsRequest;
import com.google.iam.v1.TestIamPermissionsResponse;
import com.google.protobuf.AbstractMessage;
import com.google.protobuf.ByteString;
import com.google.protobuf.Duration;
import com.google.protobuf.Empty;
import com.google.protobuf.FieldMask;
import com.google.pubsub.v1.DeleteTopicRequest;
import com.google.pubsub.v1.DetachSubscriptionRequest;
import com.google.pubsub.v1.DetachSubscriptionResponse;
import com.google.pubsub.v1.GetTopicRequest;
import com.google.pubsub.v1.ListTopicSnapshotsRequest;
import com.google.pubsub.v1.ListTopicSnapshotsResponse;
import com.google.pubsub.v1.ListTopicSubscriptionsRequest;
import com.google.pubsub.v1.ListTopicSubscriptionsResponse;
import com.google.pubsub.v1.ListTopicsRequest;
import com.google.pubsub.v1.ListTopicsResponse;
import com.google.pubsub.v1.MessageStoragePolicy;
import com.google.pubsub.v1.ProjectName;
import com.google.pubsub.v1.PublishRequest;
import com.google.pubsub.v1.PublishResponse;
import com.google.pubsub.v1.PubsubMessage;
import com.google.pubsub.v1.SchemaSettings;
import com.google.pubsub.v1.SnapshotName;
import com.google.pubsub.v1.SubscriptionName;
import com.google.pubsub.v1.Topic;
import com.google.pubsub.v1.TopicName;
import com.google.pubsub.v1.UpdateTopicRequest;
import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import javax.annotation.Generated;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@Generated("by gapic-generator-java")
public class TopicAdminClientTest {
private static MockIAMPolicy mockIAMPolicy;
private static MockPublisher mockPublisher;
private static MockServiceHelper mockServiceHelper;
private LocalChannelProvider channelProvider;
private TopicAdminClient client;
@BeforeClass
public static void startStaticServer() {
mockPublisher = new MockPublisher();
mockIAMPolicy = new MockIAMPolicy();
mockServiceHelper =
new MockServiceHelper(
UUID.randomUUID().toString(),
Arrays.<MockGrpcService>asList(mockPublisher, mockIAMPolicy));
mockServiceHelper.start();
}
@AfterClass
public static void stopServer() {
mockServiceHelper.stop();
}
@Before
public void setUp() throws IOException {
mockServiceHelper.reset();
channelProvider = mockServiceHelper.createChannelProvider();
TopicAdminSettings settings =
TopicAdminSettings.newBuilder()
.setTransportChannelProvider(channelProvider)
.setCredentialsProvider(NoCredentialsProvider.create())
.build();
client = TopicAdminClient.create(settings);
}
@After
public void tearDown() throws Exception {
client.close();
}
@Test
public void createTopicTest() throws Exception {
Topic expectedResponse =
Topic.newBuilder()
.setName(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
.putAllLabels(new HashMap<String, String>())
.setMessageStoragePolicy(MessageStoragePolicy.newBuilder().build())
.setKmsKeyName("kmsKeyName412586233")
.setSchemaSettings(SchemaSettings.newBuilder().build())
.setSatisfiesPzs(true)
.setMessageRetentionDuration(Duration.newBuilder().build())
.build();
mockPublisher.addResponse(expectedResponse);
TopicName name = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
Topic actualResponse = client.createTopic(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockPublisher.getRequests();
Assert.assertEquals(1, actualRequests.size());
Topic actualRequest = ((Topic) actualRequests.get(0));
Assert.assertEquals(name.toString(), actualRequest.getName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void createTopicExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockPublisher.addException(exception);
try {
TopicName name = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
client.createTopic(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void createTopicTest2() throws Exception {
Topic expectedResponse =
Topic.newBuilder()
.setName(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
.putAllLabels(new HashMap<String, String>())
.setMessageStoragePolicy(MessageStoragePolicy.newBuilder().build())
.setKmsKeyName("kmsKeyName412586233")
.setSchemaSettings(SchemaSettings.newBuilder().build())
.setSatisfiesPzs(true)
.setMessageRetentionDuration(Duration.newBuilder().build())
.build();
mockPublisher.addResponse(expectedResponse);
String name = "name3373707";
Topic actualResponse = client.createTopic(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockPublisher.getRequests();
Assert.assertEquals(1, actualRequests.size());
Topic actualRequest = ((Topic) actualRequests.get(0));
Assert.assertEquals(name, actualRequest.getName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void createTopicExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockPublisher.addException(exception);
try {
String name = "name3373707";
client.createTopic(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void updateTopicTest() throws Exception {
Topic expectedResponse =
Topic.newBuilder()
.setName(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
.putAllLabels(new HashMap<String, String>())
.setMessageStoragePolicy(MessageStoragePolicy.newBuilder().build())
.setKmsKeyName("kmsKeyName412586233")
.setSchemaSettings(SchemaSettings.newBuilder().build())
.setSatisfiesPzs(true)
.setMessageRetentionDuration(Duration.newBuilder().build())
.build();
mockPublisher.addResponse(expectedResponse);
UpdateTopicRequest request =
UpdateTopicRequest.newBuilder()
.setTopic(Topic.newBuilder().build())
.setUpdateMask(FieldMask.newBuilder().build())
.build();
Topic actualResponse = client.updateTopic(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockPublisher.getRequests();
Assert.assertEquals(1, actualRequests.size());
UpdateTopicRequest actualRequest = ((UpdateTopicRequest) actualRequests.get(0));
Assert.assertEquals(request.getTopic(), actualRequest.getTopic());
Assert.assertEquals(request.getUpdateMask(), actualRequest.getUpdateMask());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void updateTopicExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockPublisher.addException(exception);
try {
UpdateTopicRequest request =
UpdateTopicRequest.newBuilder()
.setTopic(Topic.newBuilder().build())
.setUpdateMask(FieldMask.newBuilder().build())
.build();
client.updateTopic(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void publishTest() throws Exception {
PublishResponse expectedResponse =
PublishResponse.newBuilder().addAllMessageIds(new ArrayList<String>()).build();
mockPublisher.addResponse(expectedResponse);
TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
List<PubsubMessage> messages = new ArrayList<>();
PublishResponse actualResponse = client.publish(topic, messages);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockPublisher.getRequests();
Assert.assertEquals(1, actualRequests.size());
PublishRequest actualRequest = ((PublishRequest) actualRequests.get(0));
Assert.assertEquals(topic.toString(), actualRequest.getTopic());
Assert.assertEquals(messages, actualRequest.getMessagesList());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void publishExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockPublisher.addException(exception);
try {
TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
List<PubsubMessage> messages = new ArrayList<>();
client.publish(topic, messages);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void publishTest2() throws Exception {
PublishResponse expectedResponse =
PublishResponse.newBuilder().addAllMessageIds(new ArrayList<String>()).build();
mockPublisher.addResponse(expectedResponse);
String topic = "topic110546223";
List<PubsubMessage> messages = new ArrayList<>();
PublishResponse actualResponse = client.publish(topic, messages);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockPublisher.getRequests();
Assert.assertEquals(1, actualRequests.size());
PublishRequest actualRequest = ((PublishRequest) actualRequests.get(0));
Assert.assertEquals(topic, actualRequest.getTopic());
Assert.assertEquals(messages, actualRequest.getMessagesList());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void publishExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockPublisher.addException(exception);
try {
String topic = "topic110546223";
List<PubsubMessage> messages = new ArrayList<>();
client.publish(topic, messages);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getTopicTest() throws Exception {
Topic expectedResponse =
Topic.newBuilder()
.setName(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
.putAllLabels(new HashMap<String, String>())
.setMessageStoragePolicy(MessageStoragePolicy.newBuilder().build())
.setKmsKeyName("kmsKeyName412586233")
.setSchemaSettings(SchemaSettings.newBuilder().build())
.setSatisfiesPzs(true)
.setMessageRetentionDuration(Duration.newBuilder().build())
.build();
mockPublisher.addResponse(expectedResponse);
TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
Topic actualResponse = client.getTopic(topic);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockPublisher.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetTopicRequest actualRequest = ((GetTopicRequest) actualRequests.get(0));
Assert.assertEquals(topic.toString(), actualRequest.getTopic());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void getTopicExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockPublisher.addException(exception);
try {
TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
client.getTopic(topic);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getTopicTest2() throws Exception {
Topic expectedResponse =
Topic.newBuilder()
.setName(TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]").toString())
.putAllLabels(new HashMap<String, String>())
.setMessageStoragePolicy(MessageStoragePolicy.newBuilder().build())
.setKmsKeyName("kmsKeyName412586233")
.setSchemaSettings(SchemaSettings.newBuilder().build())
.setSatisfiesPzs(true)
.setMessageRetentionDuration(Duration.newBuilder().build())
.build();
mockPublisher.addResponse(expectedResponse);
String topic = "topic110546223";
Topic actualResponse = client.getTopic(topic);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockPublisher.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetTopicRequest actualRequest = ((GetTopicRequest) actualRequests.get(0));
Assert.assertEquals(topic, actualRequest.getTopic());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void getTopicExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockPublisher.addException(exception);
try {
String topic = "topic110546223";
client.getTopic(topic);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listTopicsTest() throws Exception {
Topic responsesElement = Topic.newBuilder().build();
ListTopicsResponse expectedResponse =
ListTopicsResponse.newBuilder()
.setNextPageToken("")
.addAllTopics(Arrays.asList(responsesElement))
.build();
mockPublisher.addResponse(expectedResponse);
ProjectName project = ProjectName.of("[PROJECT]");
ListTopicsPagedResponse pagedListResponse = client.listTopics(project);
List<Topic> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getTopicsList().get(0), resources.get(0));
List<AbstractMessage> actualRequests = mockPublisher.getRequests();
Assert.assertEquals(1, actualRequests.size());
ListTopicsRequest actualRequest = ((ListTopicsRequest) actualRequests.get(0));
Assert.assertEquals(project.toString(), actualRequest.getProject());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void listTopicsExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockPublisher.addException(exception);
try {
ProjectName project = ProjectName.of("[PROJECT]");
client.listTopics(project);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listTopicsTest2() throws Exception {
Topic responsesElement = Topic.newBuilder().build();
ListTopicsResponse expectedResponse =
ListTopicsResponse.newBuilder()
.setNextPageToken("")
.addAllTopics(Arrays.asList(responsesElement))
.build();
mockPublisher.addResponse(expectedResponse);
String project = "project-309310695";
ListTopicsPagedResponse pagedListResponse = client.listTopics(project);
List<Topic> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getTopicsList().get(0), resources.get(0));
List<AbstractMessage> actualRequests = mockPublisher.getRequests();
Assert.assertEquals(1, actualRequests.size());
ListTopicsRequest actualRequest = ((ListTopicsRequest) actualRequests.get(0));
Assert.assertEquals(project, actualRequest.getProject());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void listTopicsExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockPublisher.addException(exception);
try {
String project = "project-309310695";
client.listTopics(project);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listTopicSubscriptionsTest() throws Exception {
String responsesElement = "responsesElement-318365110";
ListTopicSubscriptionsResponse expectedResponse =
ListTopicSubscriptionsResponse.newBuilder()
.setNextPageToken("")
.addAllSubscriptions(Arrays.asList(responsesElement))
.build();
mockPublisher.addResponse(expectedResponse);
TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
ListTopicSubscriptionsPagedResponse pagedListResponse = client.listTopicSubscriptions(topic);
List<String> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getSubscriptionsList().get(0), resources.get(0));
List<AbstractMessage> actualRequests = mockPublisher.getRequests();
Assert.assertEquals(1, actualRequests.size());
ListTopicSubscriptionsRequest actualRequest =
((ListTopicSubscriptionsRequest) actualRequests.get(0));
Assert.assertEquals(topic.toString(), actualRequest.getTopic());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void listTopicSubscriptionsExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockPublisher.addException(exception);
try {
TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
client.listTopicSubscriptions(topic);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listTopicSubscriptionsTest2() throws Exception {
String responsesElement = "responsesElement-318365110";
ListTopicSubscriptionsResponse expectedResponse =
ListTopicSubscriptionsResponse.newBuilder()
.setNextPageToken("")
.addAllSubscriptions(Arrays.asList(responsesElement))
.build();
mockPublisher.addResponse(expectedResponse);
String topic = "topic110546223";
ListTopicSubscriptionsPagedResponse pagedListResponse = client.listTopicSubscriptions(topic);
List<String> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getSubscriptionsList().get(0), resources.get(0));
List<AbstractMessage> actualRequests = mockPublisher.getRequests();
Assert.assertEquals(1, actualRequests.size());
ListTopicSubscriptionsRequest actualRequest =
((ListTopicSubscriptionsRequest) actualRequests.get(0));
Assert.assertEquals(topic, actualRequest.getTopic());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void listTopicSubscriptionsExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockPublisher.addException(exception);
try {
String topic = "topic110546223";
client.listTopicSubscriptions(topic);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listTopicSnapshotsTest() throws Exception {
String responsesElement = "responsesElement-318365110";
ListTopicSnapshotsResponse expectedResponse =
ListTopicSnapshotsResponse.newBuilder()
.setNextPageToken("")
.addAllSnapshots(Arrays.asList(responsesElement))
.build();
mockPublisher.addResponse(expectedResponse);
TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
ListTopicSnapshotsPagedResponse pagedListResponse = client.listTopicSnapshots(topic);
List<String> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getSnapshotsList().get(0), resources.get(0));
List<AbstractMessage> actualRequests = mockPublisher.getRequests();
Assert.assertEquals(1, actualRequests.size());
ListTopicSnapshotsRequest actualRequest = ((ListTopicSnapshotsRequest) actualRequests.get(0));
Assert.assertEquals(topic.toString(), actualRequest.getTopic());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void listTopicSnapshotsExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockPublisher.addException(exception);
try {
TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
client.listTopicSnapshots(topic);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listTopicSnapshotsTest2() throws Exception {
String responsesElement = "responsesElement-318365110";
ListTopicSnapshotsResponse expectedResponse =
ListTopicSnapshotsResponse.newBuilder()
.setNextPageToken("")
.addAllSnapshots(Arrays.asList(responsesElement))
.build();
mockPublisher.addResponse(expectedResponse);
String topic = "topic110546223";
ListTopicSnapshotsPagedResponse pagedListResponse = client.listTopicSnapshots(topic);
List<String> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getSnapshotsList().get(0), resources.get(0));
List<AbstractMessage> actualRequests = mockPublisher.getRequests();
Assert.assertEquals(1, actualRequests.size());
ListTopicSnapshotsRequest actualRequest = ((ListTopicSnapshotsRequest) actualRequests.get(0));
Assert.assertEquals(topic, actualRequest.getTopic());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void listTopicSnapshotsExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockPublisher.addException(exception);
try {
String topic = "topic110546223";
client.listTopicSnapshots(topic);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void deleteTopicTest() throws Exception {
Empty expectedResponse = Empty.newBuilder().build();
mockPublisher.addResponse(expectedResponse);
TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
client.deleteTopic(topic);
List<AbstractMessage> actualRequests = mockPublisher.getRequests();
Assert.assertEquals(1, actualRequests.size());
DeleteTopicRequest actualRequest = ((DeleteTopicRequest) actualRequests.get(0));
Assert.assertEquals(topic.toString(), actualRequest.getTopic());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void deleteTopicExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockPublisher.addException(exception);
try {
TopicName topic = TopicName.ofProjectTopicName("[PROJECT]", "[TOPIC]");
client.deleteTopic(topic);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void deleteTopicTest2() throws Exception {
Empty expectedResponse = Empty.newBuilder().build();
mockPublisher.addResponse(expectedResponse);
String topic = "topic110546223";
client.deleteTopic(topic);
List<AbstractMessage> actualRequests = mockPublisher.getRequests();
Assert.assertEquals(1, actualRequests.size());
DeleteTopicRequest actualRequest = ((DeleteTopicRequest) actualRequests.get(0));
Assert.assertEquals(topic, actualRequest.getTopic());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void deleteTopicExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockPublisher.addException(exception);
try {
String topic = "topic110546223";
client.deleteTopic(topic);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void detachSubscriptionTest() throws Exception {
DetachSubscriptionResponse expectedResponse = DetachSubscriptionResponse.newBuilder().build();
mockPublisher.addResponse(expectedResponse);
DetachSubscriptionRequest request =
DetachSubscriptionRequest.newBuilder()
.setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
.build();
DetachSubscriptionResponse actualResponse = client.detachSubscription(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockPublisher.getRequests();
Assert.assertEquals(1, actualRequests.size());
DetachSubscriptionRequest actualRequest = ((DetachSubscriptionRequest) actualRequests.get(0));
Assert.assertEquals(request.getSubscription(), actualRequest.getSubscription());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void detachSubscriptionExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockPublisher.addException(exception);
try {
DetachSubscriptionRequest request =
DetachSubscriptionRequest.newBuilder()
.setSubscription(SubscriptionName.of("[PROJECT]", "[SUBSCRIPTION]").toString())
.build();
client.detachSubscription(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void setIamPolicyTest() throws Exception {
Policy expectedResponse =
Policy.newBuilder()
.setVersion(351608024)
.addAllBindings(new ArrayList<Binding>())
.addAllAuditConfigs(new ArrayList<AuditConfig>())
.setEtag(ByteString.EMPTY)
.build();
mockIAMPolicy.addResponse(expectedResponse);
SetIamPolicyRequest request =
SetIamPolicyRequest.newBuilder()
.setResource(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString())
.setPolicy(Policy.newBuilder().build())
.setUpdateMask(FieldMask.newBuilder().build())
.build();
Policy actualResponse = client.setIamPolicy(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockIAMPolicy.getRequests();
Assert.assertEquals(1, actualRequests.size());
SetIamPolicyRequest actualRequest = ((SetIamPolicyRequest) actualRequests.get(0));
Assert.assertEquals(request.getResource(), actualRequest.getResource());
Assert.assertEquals(request.getPolicy(), actualRequest.getPolicy());
Assert.assertEquals(request.getUpdateMask(), actualRequest.getUpdateMask());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void setIamPolicyExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockIAMPolicy.addException(exception);
try {
SetIamPolicyRequest request =
SetIamPolicyRequest.newBuilder()
.setResource(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString())
.setPolicy(Policy.newBuilder().build())
.setUpdateMask(FieldMask.newBuilder().build())
.build();
client.setIamPolicy(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getIamPolicyTest() throws Exception {
Policy expectedResponse =
Policy.newBuilder()
.setVersion(351608024)
.addAllBindings(new ArrayList<Binding>())
.addAllAuditConfigs(new ArrayList<AuditConfig>())
.setEtag(ByteString.EMPTY)
.build();
mockIAMPolicy.addResponse(expectedResponse);
GetIamPolicyRequest request =
GetIamPolicyRequest.newBuilder()
.setResource(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString())
.setOptions(GetPolicyOptions.newBuilder().build())
.build();
Policy actualResponse = client.getIamPolicy(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockIAMPolicy.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetIamPolicyRequest actualRequest = ((GetIamPolicyRequest) actualRequests.get(0));
Assert.assertEquals(request.getResource(), actualRequest.getResource());
Assert.assertEquals(request.getOptions(), actualRequest.getOptions());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void getIamPolicyExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockIAMPolicy.addException(exception);
try {
GetIamPolicyRequest request =
GetIamPolicyRequest.newBuilder()
.setResource(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString())
.setOptions(GetPolicyOptions.newBuilder().build())
.build();
client.getIamPolicy(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void testIamPermissionsTest() throws Exception {
TestIamPermissionsResponse expectedResponse =
TestIamPermissionsResponse.newBuilder().addAllPermissions(new ArrayList<String>()).build();
mockIAMPolicy.addResponse(expectedResponse);
TestIamPermissionsRequest request =
TestIamPermissionsRequest.newBuilder()
.setResource(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString())
.addAllPermissions(new ArrayList<String>())
.build();
TestIamPermissionsResponse actualResponse = client.testIamPermissions(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockIAMPolicy.getRequests();
Assert.assertEquals(1, actualRequests.size());
TestIamPermissionsRequest actualRequest = ((TestIamPermissionsRequest) actualRequests.get(0));
Assert.assertEquals(request.getResource(), actualRequest.getResource());
Assert.assertEquals(request.getPermissionsList(), actualRequest.getPermissionsList());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void testIamPermissionsExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockIAMPolicy.addException(exception);
try {
TestIamPermissionsRequest request =
TestIamPermissionsRequest.newBuilder()
.setResource(SnapshotName.of("[PROJECT]", "[SNAPSHOT]").toString())
.addAllPermissions(new ArrayList<String>())
.build();
client.testIamPermissions(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
}
|
googleapis/google-cloud-java | 36,422 | java-vision/proto-google-cloud-vision-v1/src/main/java/com/google/cloud/vision/v1/CreateProductRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/vision/v1/product_search_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.vision.v1;
/**
*
*
* <pre>
* Request message for the `CreateProduct` method.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1.CreateProductRequest}
*/
public final class CreateProductRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.vision.v1.CreateProductRequest)
CreateProductRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateProductRequest.newBuilder() to construct.
private CreateProductRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateProductRequest() {
parent_ = "";
productId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateProductRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vision.v1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1_CreateProductRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1_CreateProductRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1.CreateProductRequest.class,
com.google.cloud.vision.v1.CreateProductRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The project in which the Product should be created.
*
* Format is
* `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The project in which the Product should be created.
*
* Format is
* `projects/PROJECT_ID/locations/LOC_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 PRODUCT_FIELD_NUMBER = 2;
private com.google.cloud.vision.v1.Product product_;
/**
*
*
* <pre>
* Required. The product to create.
* </pre>
*
* <code>.google.cloud.vision.v1.Product product = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the product field is set.
*/
@java.lang.Override
public boolean hasProduct() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The product to create.
* </pre>
*
* <code>.google.cloud.vision.v1.Product product = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The product.
*/
@java.lang.Override
public com.google.cloud.vision.v1.Product getProduct() {
return product_ == null ? com.google.cloud.vision.v1.Product.getDefaultInstance() : product_;
}
/**
*
*
* <pre>
* Required. The product to create.
* </pre>
*
* <code>.google.cloud.vision.v1.Product product = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.vision.v1.ProductOrBuilder getProductOrBuilder() {
return product_ == null ? com.google.cloud.vision.v1.Product.getDefaultInstance() : product_;
}
public static final int PRODUCT_ID_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object productId_ = "";
/**
*
*
* <pre>
* A user-supplied resource id for this Product. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_id = 3;</code>
*
* @return The productId.
*/
@java.lang.Override
public java.lang.String getProductId() {
java.lang.Object ref = productId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
productId_ = s;
return s;
}
}
/**
*
*
* <pre>
* A user-supplied resource id for this Product. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_id = 3;</code>
*
* @return The bytes for productId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getProductIdBytes() {
java.lang.Object ref = productId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
productId_ = 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, getProduct());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(productId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, productId_);
}
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, getProduct());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(productId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, productId_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.vision.v1.CreateProductRequest)) {
return super.equals(obj);
}
com.google.cloud.vision.v1.CreateProductRequest other =
(com.google.cloud.vision.v1.CreateProductRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (hasProduct() != other.hasProduct()) return false;
if (hasProduct()) {
if (!getProduct().equals(other.getProduct())) return false;
}
if (!getProductId().equals(other.getProductId())) 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 (hasProduct()) {
hash = (37 * hash) + PRODUCT_FIELD_NUMBER;
hash = (53 * hash) + getProduct().hashCode();
}
hash = (37 * hash) + PRODUCT_ID_FIELD_NUMBER;
hash = (53 * hash) + getProductId().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.vision.v1.CreateProductRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1.CreateProductRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1.CreateProductRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1.CreateProductRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1.CreateProductRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1.CreateProductRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1.CreateProductRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1.CreateProductRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.vision.v1.CreateProductRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1.CreateProductRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.vision.v1.CreateProductRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1.CreateProductRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.vision.v1.CreateProductRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request message for the `CreateProduct` method.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1.CreateProductRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.vision.v1.CreateProductRequest)
com.google.cloud.vision.v1.CreateProductRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vision.v1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1_CreateProductRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1_CreateProductRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1.CreateProductRequest.class,
com.google.cloud.vision.v1.CreateProductRequest.Builder.class);
}
// Construct using com.google.cloud.vision.v1.CreateProductRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getProductFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
product_ = null;
if (productBuilder_ != null) {
productBuilder_.dispose();
productBuilder_ = null;
}
productId_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.vision.v1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1_CreateProductRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.vision.v1.CreateProductRequest getDefaultInstanceForType() {
return com.google.cloud.vision.v1.CreateProductRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.vision.v1.CreateProductRequest build() {
com.google.cloud.vision.v1.CreateProductRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.vision.v1.CreateProductRequest buildPartial() {
com.google.cloud.vision.v1.CreateProductRequest result =
new com.google.cloud.vision.v1.CreateProductRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.vision.v1.CreateProductRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.product_ = productBuilder_ == null ? product_ : productBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.productId_ = productId_;
}
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.vision.v1.CreateProductRequest) {
return mergeFrom((com.google.cloud.vision.v1.CreateProductRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.vision.v1.CreateProductRequest other) {
if (other == com.google.cloud.vision.v1.CreateProductRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasProduct()) {
mergeProduct(other.getProduct());
}
if (!other.getProductId().isEmpty()) {
productId_ = other.productId_;
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(getProductFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
productId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The project in which the Product should be created.
*
* Format is
* `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The project in which the Product should be created.
*
* Format is
* `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The project in which the Product should be created.
*
* Format is
* `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The project in which the Product should be created.
*
* Format is
* `projects/PROJECT_ID/locations/LOC_ID`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The project in which the Product should be created.
*
* Format is
* `projects/PROJECT_ID/locations/LOC_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.vision.v1.Product product_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.vision.v1.Product,
com.google.cloud.vision.v1.Product.Builder,
com.google.cloud.vision.v1.ProductOrBuilder>
productBuilder_;
/**
*
*
* <pre>
* Required. The product to create.
* </pre>
*
* <code>.google.cloud.vision.v1.Product product = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the product field is set.
*/
public boolean hasProduct() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The product to create.
* </pre>
*
* <code>.google.cloud.vision.v1.Product product = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The product.
*/
public com.google.cloud.vision.v1.Product getProduct() {
if (productBuilder_ == null) {
return product_ == null
? com.google.cloud.vision.v1.Product.getDefaultInstance()
: product_;
} else {
return productBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The product to create.
* </pre>
*
* <code>.google.cloud.vision.v1.Product product = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setProduct(com.google.cloud.vision.v1.Product value) {
if (productBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
product_ = value;
} else {
productBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The product to create.
* </pre>
*
* <code>.google.cloud.vision.v1.Product product = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setProduct(com.google.cloud.vision.v1.Product.Builder builderForValue) {
if (productBuilder_ == null) {
product_ = builderForValue.build();
} else {
productBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The product to create.
* </pre>
*
* <code>.google.cloud.vision.v1.Product product = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeProduct(com.google.cloud.vision.v1.Product value) {
if (productBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& product_ != null
&& product_ != com.google.cloud.vision.v1.Product.getDefaultInstance()) {
getProductBuilder().mergeFrom(value);
} else {
product_ = value;
}
} else {
productBuilder_.mergeFrom(value);
}
if (product_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The product to create.
* </pre>
*
* <code>.google.cloud.vision.v1.Product product = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearProduct() {
bitField0_ = (bitField0_ & ~0x00000002);
product_ = null;
if (productBuilder_ != null) {
productBuilder_.dispose();
productBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The product to create.
* </pre>
*
* <code>.google.cloud.vision.v1.Product product = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.vision.v1.Product.Builder getProductBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getProductFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The product to create.
* </pre>
*
* <code>.google.cloud.vision.v1.Product product = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.vision.v1.ProductOrBuilder getProductOrBuilder() {
if (productBuilder_ != null) {
return productBuilder_.getMessageOrBuilder();
} else {
return product_ == null
? com.google.cloud.vision.v1.Product.getDefaultInstance()
: product_;
}
}
/**
*
*
* <pre>
* Required. The product to create.
* </pre>
*
* <code>.google.cloud.vision.v1.Product product = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.vision.v1.Product,
com.google.cloud.vision.v1.Product.Builder,
com.google.cloud.vision.v1.ProductOrBuilder>
getProductFieldBuilder() {
if (productBuilder_ == null) {
productBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.vision.v1.Product,
com.google.cloud.vision.v1.Product.Builder,
com.google.cloud.vision.v1.ProductOrBuilder>(
getProduct(), getParentForChildren(), isClean());
product_ = null;
}
return productBuilder_;
}
private java.lang.Object productId_ = "";
/**
*
*
* <pre>
* A user-supplied resource id for this Product. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_id = 3;</code>
*
* @return The productId.
*/
public java.lang.String getProductId() {
java.lang.Object ref = productId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
productId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A user-supplied resource id for this Product. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_id = 3;</code>
*
* @return The bytes for productId.
*/
public com.google.protobuf.ByteString getProductIdBytes() {
java.lang.Object ref = productId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
productId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A user-supplied resource id for this Product. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_id = 3;</code>
*
* @param value The productId to set.
* @return This builder for chaining.
*/
public Builder setProductId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
productId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* A user-supplied resource id for this Product. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_id = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearProductId() {
productId_ = getDefaultInstance().getProductId();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* A user-supplied resource id for this Product. If set, the server will
* attempt to use this value as the resource id. If it is already in use, an
* error is returned with code ALREADY_EXISTS. Must be at most 128 characters
* long. It cannot contain the character `/`.
* </pre>
*
* <code>string product_id = 3;</code>
*
* @param value The bytes for productId to set.
* @return This builder for chaining.
*/
public Builder setProductIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
productId_ = 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.vision.v1.CreateProductRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.vision.v1.CreateProductRequest)
private static final com.google.cloud.vision.v1.CreateProductRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.vision.v1.CreateProductRequest();
}
public static com.google.cloud.vision.v1.CreateProductRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateProductRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateProductRequest>() {
@java.lang.Override
public CreateProductRequest 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<CreateProductRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateProductRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.vision.v1.CreateProductRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,461 | java-admanager/proto-ad-manager-v1/src/main/java/com/google/ads/admanager/v1/CustomTargetingLiteral.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/ads/admanager/v1/targeting.proto
// Protobuf Java Version: 3.25.8
package com.google.ads.admanager.v1;
/**
*
*
* <pre>
* Represents targeting for custom key/values. The values are ORed together.
* </pre>
*
* Protobuf type {@code google.ads.admanager.v1.CustomTargetingLiteral}
*/
public final class CustomTargetingLiteral extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.ads.admanager.v1.CustomTargetingLiteral)
CustomTargetingLiteralOrBuilder {
private static final long serialVersionUID = 0L;
// Use CustomTargetingLiteral.newBuilder() to construct.
private CustomTargetingLiteral(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CustomTargetingLiteral() {
customTargetingKey_ = "";
customTargetingValues_ = com.google.protobuf.LazyStringArrayList.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CustomTargetingLiteral();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.ads.admanager.v1.TargetingProto
.internal_static_google_ads_admanager_v1_CustomTargetingLiteral_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.admanager.v1.TargetingProto
.internal_static_google_ads_admanager_v1_CustomTargetingLiteral_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.admanager.v1.CustomTargetingLiteral.class,
com.google.ads.admanager.v1.CustomTargetingLiteral.Builder.class);
}
private int bitField0_;
public static final int NEGATIVE_FIELD_NUMBER = 1;
private boolean negative_ = false;
/**
*
*
* <pre>
* Whether this expression is negatively targeted, meaning it matches
* ad requests that exclude the below values.
* </pre>
*
* <code>optional bool negative = 1;</code>
*
* @return Whether the negative field is set.
*/
@java.lang.Override
public boolean hasNegative() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Whether this expression is negatively targeted, meaning it matches
* ad requests that exclude the below values.
* </pre>
*
* <code>optional bool negative = 1;</code>
*
* @return The negative.
*/
@java.lang.Override
public boolean getNegative() {
return negative_;
}
public static final int CUSTOM_TARGETING_KEY_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object customTargetingKey_ = "";
/**
*
*
* <pre>
* Optional. The resource name of the targeted CustomKey.
* </pre>
*
* <code>
* optional string custom_targeting_key = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return Whether the customTargetingKey field is set.
*/
@java.lang.Override
public boolean hasCustomTargetingKey() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Optional. The resource name of the targeted CustomKey.
* </pre>
*
* <code>
* optional string custom_targeting_key = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The customTargetingKey.
*/
@java.lang.Override
public java.lang.String getCustomTargetingKey() {
java.lang.Object ref = customTargetingKey_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
customTargetingKey_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. The resource name of the targeted CustomKey.
* </pre>
*
* <code>
* optional string custom_targeting_key = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for customTargetingKey.
*/
@java.lang.Override
public com.google.protobuf.ByteString getCustomTargetingKeyBytes() {
java.lang.Object ref = customTargetingKey_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
customTargetingKey_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CUSTOM_TARGETING_VALUES_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private com.google.protobuf.LazyStringArrayList customTargetingValues_ =
com.google.protobuf.LazyStringArrayList.emptyList();
/**
*
*
* <pre>
* Optional. The resource names of the targeted CustomValues.
* </pre>
*
* <code>
* repeated string custom_targeting_values = 5 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return A list containing the customTargetingValues.
*/
public com.google.protobuf.ProtocolStringList getCustomTargetingValuesList() {
return customTargetingValues_;
}
/**
*
*
* <pre>
* Optional. The resource names of the targeted CustomValues.
* </pre>
*
* <code>
* repeated string custom_targeting_values = 5 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The count of customTargetingValues.
*/
public int getCustomTargetingValuesCount() {
return customTargetingValues_.size();
}
/**
*
*
* <pre>
* Optional. The resource names of the targeted CustomValues.
* </pre>
*
* <code>
* repeated string custom_targeting_values = 5 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param index The index of the element to return.
* @return The customTargetingValues at the given index.
*/
public java.lang.String getCustomTargetingValues(int index) {
return customTargetingValues_.get(index);
}
/**
*
*
* <pre>
* Optional. The resource names of the targeted CustomValues.
* </pre>
*
* <code>
* repeated string custom_targeting_values = 5 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param index The index of the value to return.
* @return The bytes of the customTargetingValues at the given index.
*/
public com.google.protobuf.ByteString getCustomTargetingValuesBytes(int index) {
return customTargetingValues_.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 (((bitField0_ & 0x00000001) != 0)) {
output.writeBool(1, negative_);
}
if (((bitField0_ & 0x00000002) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, customTargetingKey_);
}
for (int i = 0; i < customTargetingValues_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(
output, 5, customTargetingValues_.getRaw(i));
}
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.computeBoolSize(1, negative_);
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, customTargetingKey_);
}
{
int dataSize = 0;
for (int i = 0; i < customTargetingValues_.size(); i++) {
dataSize += computeStringSizeNoTag(customTargetingValues_.getRaw(i));
}
size += dataSize;
size += 1 * getCustomTargetingValuesList().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.ads.admanager.v1.CustomTargetingLiteral)) {
return super.equals(obj);
}
com.google.ads.admanager.v1.CustomTargetingLiteral other =
(com.google.ads.admanager.v1.CustomTargetingLiteral) obj;
if (hasNegative() != other.hasNegative()) return false;
if (hasNegative()) {
if (getNegative() != other.getNegative()) return false;
}
if (hasCustomTargetingKey() != other.hasCustomTargetingKey()) return false;
if (hasCustomTargetingKey()) {
if (!getCustomTargetingKey().equals(other.getCustomTargetingKey())) return false;
}
if (!getCustomTargetingValuesList().equals(other.getCustomTargetingValuesList())) 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 (hasNegative()) {
hash = (37 * hash) + NEGATIVE_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getNegative());
}
if (hasCustomTargetingKey()) {
hash = (37 * hash) + CUSTOM_TARGETING_KEY_FIELD_NUMBER;
hash = (53 * hash) + getCustomTargetingKey().hashCode();
}
if (getCustomTargetingValuesCount() > 0) {
hash = (37 * hash) + CUSTOM_TARGETING_VALUES_FIELD_NUMBER;
hash = (53 * hash) + getCustomTargetingValuesList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.admanager.v1.CustomTargetingLiteral parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.admanager.v1.CustomTargetingLiteral 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.admanager.v1.CustomTargetingLiteral parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.admanager.v1.CustomTargetingLiteral 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.admanager.v1.CustomTargetingLiteral parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.admanager.v1.CustomTargetingLiteral parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.admanager.v1.CustomTargetingLiteral parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.ads.admanager.v1.CustomTargetingLiteral 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.admanager.v1.CustomTargetingLiteral parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.admanager.v1.CustomTargetingLiteral 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.admanager.v1.CustomTargetingLiteral parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.ads.admanager.v1.CustomTargetingLiteral 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.admanager.v1.CustomTargetingLiteral 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 targeting for custom key/values. The values are ORed together.
* </pre>
*
* Protobuf type {@code google.ads.admanager.v1.CustomTargetingLiteral}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.ads.admanager.v1.CustomTargetingLiteral)
com.google.ads.admanager.v1.CustomTargetingLiteralOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.ads.admanager.v1.TargetingProto
.internal_static_google_ads_admanager_v1_CustomTargetingLiteral_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.admanager.v1.TargetingProto
.internal_static_google_ads_admanager_v1_CustomTargetingLiteral_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.admanager.v1.CustomTargetingLiteral.class,
com.google.ads.admanager.v1.CustomTargetingLiteral.Builder.class);
}
// Construct using com.google.ads.admanager.v1.CustomTargetingLiteral.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
negative_ = false;
customTargetingKey_ = "";
customTargetingValues_ = com.google.protobuf.LazyStringArrayList.emptyList();
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.ads.admanager.v1.TargetingProto
.internal_static_google_ads_admanager_v1_CustomTargetingLiteral_descriptor;
}
@java.lang.Override
public com.google.ads.admanager.v1.CustomTargetingLiteral getDefaultInstanceForType() {
return com.google.ads.admanager.v1.CustomTargetingLiteral.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.admanager.v1.CustomTargetingLiteral build() {
com.google.ads.admanager.v1.CustomTargetingLiteral result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.admanager.v1.CustomTargetingLiteral buildPartial() {
com.google.ads.admanager.v1.CustomTargetingLiteral result =
new com.google.ads.admanager.v1.CustomTargetingLiteral(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.admanager.v1.CustomTargetingLiteral result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.negative_ = negative_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.customTargetingKey_ = customTargetingKey_;
to_bitField0_ |= 0x00000002;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
customTargetingValues_.makeImmutable();
result.customTargetingValues_ = customTargetingValues_;
}
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.admanager.v1.CustomTargetingLiteral) {
return mergeFrom((com.google.ads.admanager.v1.CustomTargetingLiteral) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.admanager.v1.CustomTargetingLiteral other) {
if (other == com.google.ads.admanager.v1.CustomTargetingLiteral.getDefaultInstance())
return this;
if (other.hasNegative()) {
setNegative(other.getNegative());
}
if (other.hasCustomTargetingKey()) {
customTargetingKey_ = other.customTargetingKey_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.customTargetingValues_.isEmpty()) {
if (customTargetingValues_.isEmpty()) {
customTargetingValues_ = other.customTargetingValues_;
bitField0_ |= 0x00000004;
} else {
ensureCustomTargetingValuesIsMutable();
customTargetingValues_.addAll(other.customTargetingValues_);
}
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:
{
negative_ = input.readBool();
bitField0_ |= 0x00000001;
break;
} // case 8
case 34:
{
customTargetingKey_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 34
case 42:
{
java.lang.String s = input.readStringRequireUtf8();
ensureCustomTargetingValuesIsMutable();
customTargetingValues_.add(s);
break;
} // case 42
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private boolean negative_;
/**
*
*
* <pre>
* Whether this expression is negatively targeted, meaning it matches
* ad requests that exclude the below values.
* </pre>
*
* <code>optional bool negative = 1;</code>
*
* @return Whether the negative field is set.
*/
@java.lang.Override
public boolean hasNegative() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Whether this expression is negatively targeted, meaning it matches
* ad requests that exclude the below values.
* </pre>
*
* <code>optional bool negative = 1;</code>
*
* @return The negative.
*/
@java.lang.Override
public boolean getNegative() {
return negative_;
}
/**
*
*
* <pre>
* Whether this expression is negatively targeted, meaning it matches
* ad requests that exclude the below values.
* </pre>
*
* <code>optional bool negative = 1;</code>
*
* @param value The negative to set.
* @return This builder for chaining.
*/
public Builder setNegative(boolean value) {
negative_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Whether this expression is negatively targeted, meaning it matches
* ad requests that exclude the below values.
* </pre>
*
* <code>optional bool negative = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearNegative() {
bitField0_ = (bitField0_ & ~0x00000001);
negative_ = false;
onChanged();
return this;
}
private java.lang.Object customTargetingKey_ = "";
/**
*
*
* <pre>
* Optional. The resource name of the targeted CustomKey.
* </pre>
*
* <code>
* optional string custom_targeting_key = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return Whether the customTargetingKey field is set.
*/
public boolean hasCustomTargetingKey() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Optional. The resource name of the targeted CustomKey.
* </pre>
*
* <code>
* optional string custom_targeting_key = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The customTargetingKey.
*/
public java.lang.String getCustomTargetingKey() {
java.lang.Object ref = customTargetingKey_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
customTargetingKey_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. The resource name of the targeted CustomKey.
* </pre>
*
* <code>
* optional string custom_targeting_key = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for customTargetingKey.
*/
public com.google.protobuf.ByteString getCustomTargetingKeyBytes() {
java.lang.Object ref = customTargetingKey_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
customTargetingKey_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. The resource name of the targeted CustomKey.
* </pre>
*
* <code>
* optional string custom_targeting_key = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The customTargetingKey to set.
* @return This builder for chaining.
*/
public Builder setCustomTargetingKey(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
customTargetingKey_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The resource name of the targeted CustomKey.
* </pre>
*
* <code>
* optional string custom_targeting_key = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearCustomTargetingKey() {
customTargetingKey_ = getDefaultInstance().getCustomTargetingKey();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The resource name of the targeted CustomKey.
* </pre>
*
* <code>
* optional string custom_targeting_key = 4 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for customTargetingKey to set.
* @return This builder for chaining.
*/
public Builder setCustomTargetingKeyBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
customTargetingKey_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.protobuf.LazyStringArrayList customTargetingValues_ =
com.google.protobuf.LazyStringArrayList.emptyList();
private void ensureCustomTargetingValuesIsMutable() {
if (!customTargetingValues_.isModifiable()) {
customTargetingValues_ =
new com.google.protobuf.LazyStringArrayList(customTargetingValues_);
}
bitField0_ |= 0x00000004;
}
/**
*
*
* <pre>
* Optional. The resource names of the targeted CustomValues.
* </pre>
*
* <code>
* repeated string custom_targeting_values = 5 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return A list containing the customTargetingValues.
*/
public com.google.protobuf.ProtocolStringList getCustomTargetingValuesList() {
customTargetingValues_.makeImmutable();
return customTargetingValues_;
}
/**
*
*
* <pre>
* Optional. The resource names of the targeted CustomValues.
* </pre>
*
* <code>
* repeated string custom_targeting_values = 5 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The count of customTargetingValues.
*/
public int getCustomTargetingValuesCount() {
return customTargetingValues_.size();
}
/**
*
*
* <pre>
* Optional. The resource names of the targeted CustomValues.
* </pre>
*
* <code>
* repeated string custom_targeting_values = 5 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param index The index of the element to return.
* @return The customTargetingValues at the given index.
*/
public java.lang.String getCustomTargetingValues(int index) {
return customTargetingValues_.get(index);
}
/**
*
*
* <pre>
* Optional. The resource names of the targeted CustomValues.
* </pre>
*
* <code>
* repeated string custom_targeting_values = 5 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param index The index of the value to return.
* @return The bytes of the customTargetingValues at the given index.
*/
public com.google.protobuf.ByteString getCustomTargetingValuesBytes(int index) {
return customTargetingValues_.getByteString(index);
}
/**
*
*
* <pre>
* Optional. The resource names of the targeted CustomValues.
* </pre>
*
* <code>
* repeated string custom_targeting_values = 5 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param index The index to set the value at.
* @param value The customTargetingValues to set.
* @return This builder for chaining.
*/
public Builder setCustomTargetingValues(int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureCustomTargetingValuesIsMutable();
customTargetingValues_.set(index, value);
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The resource names of the targeted CustomValues.
* </pre>
*
* <code>
* repeated string custom_targeting_values = 5 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The customTargetingValues to add.
* @return This builder for chaining.
*/
public Builder addCustomTargetingValues(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureCustomTargetingValuesIsMutable();
customTargetingValues_.add(value);
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The resource names of the targeted CustomValues.
* </pre>
*
* <code>
* repeated string custom_targeting_values = 5 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param values The customTargetingValues to add.
* @return This builder for chaining.
*/
public Builder addAllCustomTargetingValues(java.lang.Iterable<java.lang.String> values) {
ensureCustomTargetingValuesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, customTargetingValues_);
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The resource names of the targeted CustomValues.
* </pre>
*
* <code>
* repeated string custom_targeting_values = 5 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearCustomTargetingValues() {
customTargetingValues_ = com.google.protobuf.LazyStringArrayList.emptyList();
bitField0_ = (bitField0_ & ~0x00000004);
;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The resource names of the targeted CustomValues.
* </pre>
*
* <code>
* repeated string custom_targeting_values = 5 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes of the customTargetingValues to add.
* @return This builder for chaining.
*/
public Builder addCustomTargetingValuesBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ensureCustomTargetingValuesIsMutable();
customTargetingValues_.add(value);
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.admanager.v1.CustomTargetingLiteral)
}
// @@protoc_insertion_point(class_scope:google.ads.admanager.v1.CustomTargetingLiteral)
private static final com.google.ads.admanager.v1.CustomTargetingLiteral DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.admanager.v1.CustomTargetingLiteral();
}
public static com.google.ads.admanager.v1.CustomTargetingLiteral getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CustomTargetingLiteral> PARSER =
new com.google.protobuf.AbstractParser<CustomTargetingLiteral>() {
@java.lang.Override
public CustomTargetingLiteral 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<CustomTargetingLiteral> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CustomTargetingLiteral> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.admanager.v1.CustomTargetingLiteral getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/hadoop | 36,444 | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/util/resource/ResourceUtils.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.util.resource;
import org.apache.hadoop.classification.VisibleForTesting;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.protocolrecords.ResourceTypes;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.ResourceInformation;
import org.apache.hadoop.yarn.api.records.ResourceTypeInfo;
import org.apache.hadoop.yarn.api.records.impl.LightWeightResource;
import org.apache.hadoop.yarn.conf.ConfigurationProvider;
import org.apache.hadoop.yarn.conf.ConfigurationProviderFactory;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.ResourceNotFoundException;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.util.UnitsConversionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
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.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Helper class to read the resource-types to be supported by the system.
*/
public class ResourceUtils {
public static final String UNITS = ".units";
public static final String TYPE = ".type";
public static final String TAGS = ".tags";
public static final String MINIMUM_ALLOCATION = ".minimum-allocation";
public static final String MAXIMUM_ALLOCATION = ".maximum-allocation";
public static final String EXTERNAL_VOLUME_RESOURCE_TAG = "system:csi-volume";
private static final String MEMORY = ResourceInformation.MEMORY_MB.getName();
private static final String VCORES = ResourceInformation.VCORES.getName();
public static final Pattern RESOURCE_REQUEST_VALUE_PATTERN =
Pattern.compile("^([0-9]+) ?([a-zA-Z]*)$");
private static final Pattern RESOURCE_NAME_PATTERN = Pattern.compile(
"^(((\\p{Alnum}([\\p{Alnum}-]*\\p{Alnum})?\\.)*"
+ "\\p{Alnum}([\\p{Alnum}-]*\\p{Alnum})?)/)?\\p{Alpha}([\\w.-]*)$");
private final static String RES_PATTERN = "^[^=]+=\\d+\\s?\\w*$";
public static final String YARN_IO_OPTIONAL = "(yarn\\.io/)?";
private static volatile boolean initializedResources = false;
private static final Map<String, Integer> RESOURCE_NAME_TO_INDEX =
new ConcurrentHashMap<String, Integer>();
private static volatile Map<String, ResourceInformation> resourceTypes;
private static volatile Map<String, ResourceInformation> nonCountableResourceTypes;
private static volatile ResourceInformation[] resourceTypesArray;
private static volatile boolean initializedNodeResources = false;
private static volatile Map<String, ResourceInformation> readOnlyNodeResources;
private static volatile int numKnownResourceTypes = -1;
private static volatile int numNonCountableResourceTypes = -1;
static final Logger LOG = LoggerFactory.getLogger(ResourceUtils.class);
private ResourceUtils() {
}
/**
* Ensures that historical resource types (like {@link
* ResourceInformation#MEMORY_URI}, {@link ResourceInformation#VCORES_URI})
* are not getting overridden in the resourceInformationMap.
*
* Also checks whether {@link ResourceInformation#SPECIAL_RESOURCES} are not
* configured poorly: having their proper units and types.
*
* @param resourceInformationMap Map object having keys as resources names
* and {@link ResourceInformation} objects as
* values
* @throws YarnRuntimeException if either of the two above
* conditions do not hold
*/
private static void checkSpecialResources(
Map<String, ResourceInformation> resourceInformationMap)
throws YarnRuntimeException {
/*
* Supporting 'memory', 'memory-mb', 'vcores' also as invalid resource
* names, in addition to 'MEMORY' for historical reasons
*/
String[] keys = {"memory", ResourceInformation.MEMORY_URI, ResourceInformation.VCORES_URI};
for(String key : keys) {
if (resourceInformationMap.containsKey(key)) {
LOG.warn("Attempt to define resource '" + key + "', but it is not allowed.");
throw new YarnRuntimeException(
"Attempt to re-define mandatory resource '" + key + "'.");
}
}
for (Map.Entry<String, ResourceInformation> mandatoryResourceEntry :
ResourceInformation.SPECIAL_RESOURCES.entrySet()) {
String key = mandatoryResourceEntry.getKey();
ResourceInformation mandatoryRI = mandatoryResourceEntry.getValue();
ResourceInformation newDefinedRI = resourceInformationMap.get(key);
if (newDefinedRI != null) {
String expectedUnit = mandatoryRI.getUnits();
ResourceTypes expectedType = mandatoryRI.getResourceType();
String actualUnit = newDefinedRI.getUnits();
ResourceTypes actualType = newDefinedRI.getResourceType();
if (!expectedUnit.equals(actualUnit) || !expectedType.equals(
actualType)) {
throw new YarnRuntimeException("Defined mandatory resource type="
+ key + " inside resource-types.xml, however its type or "
+ "unit is conflict to mandatory resource types, expected type="
+ expectedType + ", unit=" + expectedUnit + "; actual type="
+ actualType + " actual unit=" + actualUnit);
}
}
}
}
/**
* Ensures that {@link ResourceUtils#MEMORY} and {@link ResourceUtils#VCORES}
* resources are contained in the map received as parameter.
*
* @param res Map object having keys as resources names
* and {@link ResourceInformation} objects as values
*/
private static void addMandatoryResources(
Map<String, ResourceInformation> res) {
ResourceInformation ri;
if (!res.containsKey(MEMORY)) {
LOG.debug("Adding resource type - name = {}, units = {}, type = {}",
MEMORY, ResourceInformation.MEMORY_MB.getUnits(),
ResourceTypes.COUNTABLE);
ri = ResourceInformation.newInstance(MEMORY,
ResourceInformation.MEMORY_MB.getUnits());
res.put(MEMORY, ri);
}
if (!res.containsKey(VCORES)) {
LOG.debug("Adding resource type - name = {}, units = {}, type = {}",
VCORES, ResourceInformation.VCORES.getUnits(),
ResourceTypes.COUNTABLE);
ri = ResourceInformation.newInstance(VCORES);
res.put(VCORES, ri);
}
}
private static void setAllocationForMandatoryResources(
Map<String, ResourceInformation> res, Configuration conf) {
ResourceInformation mem = res.get(ResourceInformation.MEMORY_MB.getName());
mem.setMinimumAllocation(getAllocation(conf,
YarnConfiguration.RESOURCE_TYPES + "." +
mem.getName() + MINIMUM_ALLOCATION,
YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB,
YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB));
mem.setMaximumAllocation(getAllocation(conf,
YarnConfiguration.RESOURCE_TYPES + "." +
mem.getName() + MAXIMUM_ALLOCATION,
YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB,
YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_MB));
ResourceInformation cpu = res.get(ResourceInformation.VCORES.getName());
cpu.setMinimumAllocation(getAllocation(conf,
YarnConfiguration.RESOURCE_TYPES + "." +
cpu.getName() + MINIMUM_ALLOCATION,
YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES,
YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES));
cpu.setMaximumAllocation(getAllocation(conf,
YarnConfiguration.RESOURCE_TYPES + "." +
cpu.getName() + MAXIMUM_ALLOCATION,
YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES,
YarnConfiguration.DEFAULT_RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES));
}
private static long getAllocation(Configuration conf,
String resourceTypesKey, String schedulerKey, long schedulerDefault) {
long value = conf.getLong(resourceTypesKey, -1L);
if (value == -1) {
LOG.debug("Mandatory Resource '{}' is not "
+ "configured in resource-types config file. Setting allocation "
+ "specified using '{}'", resourceTypesKey, schedulerKey);
value = conf.getLong(schedulerKey, schedulerDefault);
}
return value;
}
@VisibleForTesting
static void validateNameOfResourceNameAndThrowException(String resourceName)
throws YarnRuntimeException {
Matcher matcher = RESOURCE_NAME_PATTERN.matcher(resourceName);
if (!matcher.matches()) {
String message = String.format(
"'%s' is not a valid resource name. A valid resource name must"
+ " begin with a letter and contain only letters, numbers, "
+ "and any of: '.', '_', or '-'. A valid resource name may also"
+ " be optionally preceded by a name space followed by a slash."
+ " A valid name space consists of period-separated groups of"
+ " letters, numbers, and dashes.",
resourceName);
throw new YarnRuntimeException(message);
}
}
/**
* Get maximum allocation from config, *THIS WILL NOT UPDATE INTERNAL DATA.
*
* @param conf config
* @return maximum allocation
*/
public static Resource fetchMaximumAllocationFromConfig(Configuration conf) {
Map<String, ResourceInformation> resourceInformationMap =
getResourceInformationMapFromConfig(conf);
Resource ret = Resource.newInstance(0, 0);
for (ResourceInformation entry : resourceInformationMap.values()) {
ret.setResourceValue(entry.getName(), entry.getMaximumAllocation());
}
return ret;
}
private static Map<String, ResourceInformation> getResourceInformationMapFromConfig(
Configuration conf) {
Map<String, ResourceInformation> resourceInformationMap = new HashMap<>();
String[] resourceNames =
conf.getTrimmedStrings(YarnConfiguration.RESOURCE_TYPES);
if (resourceNames != null && resourceNames.length != 0) {
for (String resourceName : resourceNames) {
String resourceUnits = conf.get(
YarnConfiguration.RESOURCE_TYPES + "." + resourceName + UNITS, "");
String resourceTypeName = conf.get(
YarnConfiguration.RESOURCE_TYPES + "." + resourceName + TYPE,
ResourceTypes.COUNTABLE.toString());
Long minimumAllocation = conf.getLong(
YarnConfiguration.RESOURCE_TYPES + "." + resourceName
+ MINIMUM_ALLOCATION, 0L);
Long maximumAllocation = conf.getLong(
YarnConfiguration.RESOURCE_TYPES + "." + resourceName
+ MAXIMUM_ALLOCATION, Long.MAX_VALUE);
if (resourceName == null || resourceName.isEmpty()
|| resourceUnits == null || resourceTypeName == null) {
throw new YarnRuntimeException(
"Incomplete configuration for resource type '" + resourceName
+ "'. One of name, units or type is configured incorrectly.");
}
ResourceTypes resourceType = ResourceTypes.valueOf(resourceTypeName);
String[] resourceTags = conf.getTrimmedStrings(
YarnConfiguration.RESOURCE_TYPES + "." + resourceName + TAGS);
Set<String> resourceTagSet = new HashSet<>();
Collections.addAll(resourceTagSet, resourceTags);
LOG.info("Adding resource type - name = " + resourceName + ", units = "
+ resourceUnits + ", type = " + resourceTypeName);
if (resourceInformationMap.containsKey(resourceName)) {
throw new YarnRuntimeException(
"Error in config, key '" + resourceName + "' specified twice");
}
resourceInformationMap.put(resourceName, ResourceInformation
.newInstance(resourceName, resourceUnits, 0L, resourceType,
minimumAllocation, maximumAllocation, resourceTagSet, null));
}
}
// Validate names of resource information map.
for (String name : resourceInformationMap.keySet()) {
validateNameOfResourceNameAndThrowException(name);
}
checkSpecialResources(resourceInformationMap);
addMandatoryResources(resourceInformationMap);
setAllocationForMandatoryResources(resourceInformationMap, conf);
return resourceInformationMap;
}
@VisibleForTesting
static void initializeResourcesMap(Configuration conf) {
Map<String, ResourceInformation> resourceInformationMap =
getResourceInformationMapFromConfig(conf);
initializeResourcesFromResourceInformationMap(resourceInformationMap);
}
/**
* This method is visible for testing, unit test can construct a
* resourceInformationMap and pass it to this method to initialize multiple resources.
* @param resourceInformationMap constructed resource information map.
*/
@VisibleForTesting
public static void initializeResourcesFromResourceInformationMap(
Map<String, ResourceInformation> resourceInformationMap) {
resourceTypes = Collections.unmodifiableMap(resourceInformationMap);
nonCountableResourceTypes = new HashMap<>();
updateKnownResources();
updateResourceTypeIndex();
initializedResources = true;
numKnownResourceTypes = resourceTypes.size();
numNonCountableResourceTypes = nonCountableResourceTypes.size();
}
private static void updateKnownResources() {
// Update resource names.
resourceTypesArray = new ResourceInformation[resourceTypes.size()];
List<ResourceInformation> nonCountableResources = new ArrayList<>();
int index = 2;
for (ResourceInformation resInfo : resourceTypes.values()) {
if (resInfo.getName().equals(MEMORY)) {
resourceTypesArray[0] = ResourceInformation
.newInstance(resourceTypes.get(MEMORY));
} else if (resInfo.getName().equals(VCORES)) {
resourceTypesArray[1] = ResourceInformation
.newInstance(resourceTypes.get(VCORES));
} else {
if (resInfo.getTags() != null && resInfo.getTags()
.contains(EXTERNAL_VOLUME_RESOURCE_TAG)) {
nonCountableResources.add(resInfo);
continue;
}
resourceTypesArray[index] = ResourceInformation.newInstance(resInfo);
index++;
}
}
// Add all non-countable resource types to the end of the resource array.
for(ResourceInformation resInfo: nonCountableResources) {
resourceTypesArray[index] = ResourceInformation.newInstance(resInfo);
nonCountableResourceTypes.put(resInfo.getName(), resInfo);
index++;
}
}
private static void updateResourceTypeIndex() {
RESOURCE_NAME_TO_INDEX.clear();
for (int index = 0; index < resourceTypesArray.length; index++) {
ResourceInformation resInfo = resourceTypesArray[index];
RESOURCE_NAME_TO_INDEX.put(resInfo.getName(), index);
}
}
/**
* Get associate index of resource types such memory, cpu etc.
* This could help to access each resource types in a resource faster.
* @return Index map for all Resource Types.
*/
public static Map<String, Integer> getResourceTypeIndex() {
return RESOURCE_NAME_TO_INDEX;
}
/**
* Get the resource types to be supported by the system.
* @return A map of the resource name to a ResourceInformation object
* which contains details such as the unit.
*/
public static Map<String, ResourceInformation> getResourceTypes() {
return getResourceTypes(null,
YarnConfiguration.RESOURCE_TYPES_CONFIGURATION_FILE);
}
public static ResourceInformation[] getResourceTypesArray() {
initializeResourceTypesIfNeeded();
return resourceTypesArray;
}
public static int getNumberOfKnownResourceTypes() {
if (numKnownResourceTypes < 0) {
initializeResourceTypesIfNeeded();
}
return numKnownResourceTypes;
}
public static int getNumberOfCountableResourceTypes() {
if (numKnownResourceTypes < 0) {
initializeResourceTypesIfNeeded();
}
return numKnownResourceTypes - numNonCountableResourceTypes;
}
private static Map<String, ResourceInformation> getResourceTypes(
Configuration conf) {
return getResourceTypes(conf,
YarnConfiguration.RESOURCE_TYPES_CONFIGURATION_FILE);
}
private static void initializeResourceTypesIfNeeded() {
initializeResourceTypesIfNeeded(null,
YarnConfiguration.RESOURCE_TYPES_CONFIGURATION_FILE);
}
private static void initializeResourceTypesIfNeeded(Configuration conf,
String resourceFile) {
if (!initializedResources) {
synchronized (ResourceUtils.class) {
if (!initializedResources) {
Configuration resConf = conf;
if (resConf == null) {
resConf = new YarnConfiguration();
}
addResourcesFileToConf(resourceFile, resConf);
initializeResourcesMap(resConf);
}
}
}
numKnownResourceTypes = resourceTypes.size();
numNonCountableResourceTypes = nonCountableResourceTypes.size();
}
private static Map<String, ResourceInformation> getResourceTypes(
Configuration conf, String resourceFile) {
initializeResourceTypesIfNeeded(conf, resourceFile);
return resourceTypes;
}
private static InputStream getConfInputStream(String resourceFile,
Configuration conf) throws IOException, YarnException {
ConfigurationProvider provider =
ConfigurationProviderFactory.getConfigurationProvider(conf);
try {
provider.init(conf);
} catch (Exception e) {
throw new IOException(e);
}
InputStream ris = provider.getConfigurationInputStream(conf, resourceFile);
if (ris == null) {
if (conf.getResource(resourceFile) == null) {
throw new FileNotFoundException("Unable to find " + resourceFile);
}
throw new IOException(
"Unable to open resource types file '" + resourceFile
+ "'. Using provider " + provider);
}
return ris;
}
private static void addResourcesFileToConf(String resourceFile,
Configuration conf) {
try {
InputStream ris = getConfInputStream(resourceFile, conf);
LOG.debug("Found {}, adding to configuration", resourceFile);
conf.addResource(ris);
} catch (FileNotFoundException fe) {
LOG.info("Unable to find '{}'.", resourceFile);
} catch (IOException | YarnException ex) {
LOG.error("Exception trying to read resource types configuration '{}'.",
resourceFile, ex);
throw new YarnRuntimeException(ex);
}
}
@VisibleForTesting
public synchronized static void resetResourceTypes() {
initializedResources = false;
}
@VisibleForTesting
public static Map<String, ResourceInformation>
resetResourceTypes(Configuration conf) {
synchronized (ResourceUtils.class) {
initializedResources = false;
}
return getResourceTypes(conf);
}
public static String getUnits(String resourceValue) {
return parseResourceValue(resourceValue)[0];
}
/**
* Extract unit and actual value from resource value.
* @param resourceValue Value of the resource
* @return Array containing unit and value. [0]=unit, [1]=value
* @throws IllegalArgumentException if units contain non alpha characters
*/
public static String[] parseResourceValue(String resourceValue) {
String[] resource = new String[2];
int i = 0;
for (; i < resourceValue.length(); i++) {
if (Character.isAlphabetic(resourceValue.charAt(i))) {
break;
}
}
String units = resourceValue.substring(i);
if (StringUtils.isAlpha(units) || units.equals("")) {
resource[0] = units;
resource[1] = resourceValue.substring(0, i);
return resource;
} else {
throw new IllegalArgumentException("Units '" + units + "'"
+ " contains non alphabet characters, which is not allowed.");
}
}
public static long getValue(String resourceValue) {
return Long.parseLong(parseResourceValue(resourceValue)[1]);
}
/**
* Function to get the resources for a node. This function will look at the
* file {@link YarnConfiguration#NODE_RESOURCES_CONFIGURATION_FILE} to
* determine the node resources.
*
* @param conf configuration file
* @return a map to resource name to the ResourceInformation object. The map
* is guaranteed to have entries for memory and vcores
*/
public static Map<String, ResourceInformation> getNodeResourceInformation(
Configuration conf) {
if (!initializedNodeResources) {
synchronized (ResourceUtils.class) {
if (!initializedNodeResources) {
Map<String, ResourceInformation> nodeResources = initializeNodeResourceInformation(
conf);
checkSpecialResources(nodeResources);
addMandatoryResources(nodeResources);
setAllocationForMandatoryResources(nodeResources, conf);
readOnlyNodeResources = Collections.unmodifiableMap(nodeResources);
initializedNodeResources = true;
}
}
}
return readOnlyNodeResources;
}
private static Map<String, ResourceInformation> initializeNodeResourceInformation(
Configuration conf) {
Map<String, ResourceInformation> nodeResources = new HashMap<>();
addResourcesFileToConf(YarnConfiguration.NODE_RESOURCES_CONFIGURATION_FILE,
conf);
for (Map.Entry<String, String> entry : conf) {
String key = entry.getKey();
String value = entry.getValue();
addResourceTypeInformation(key, value, nodeResources);
}
return nodeResources;
}
private static void addResourceTypeInformation(String prop, String value,
Map<String, ResourceInformation> nodeResources) {
if (prop.startsWith(YarnConfiguration.NM_RESOURCES_PREFIX)) {
LOG.info("Found resource entry " + prop);
String resourceType = prop.substring(
YarnConfiguration.NM_RESOURCES_PREFIX.length());
if (!nodeResources.containsKey(resourceType)) {
nodeResources
.put(resourceType, ResourceInformation.newInstance(resourceType));
}
String units = getUnits(value);
Long resourceValue =
Long.valueOf(value.substring(0, value.length() - units.length()));
String destUnit = getDefaultUnit(resourceType);
if(!units.equals(destUnit)) {
resourceValue = UnitsConversionUtil.convert(
units, destUnit, resourceValue);
units = destUnit;
}
nodeResources.get(resourceType).setValue(resourceValue);
nodeResources.get(resourceType).setUnits(units);
LOG.debug("Setting value for resource type {} to {} with units {}",
resourceType, resourceValue, units);
}
}
@VisibleForTesting
synchronized public static void resetNodeResources() {
initializedNodeResources = false;
}
public static Resource getResourceTypesMinimumAllocation() {
Resource ret = Resource.newInstance(0, 0);
for (ResourceInformation entry : resourceTypesArray) {
String name = entry.getName();
if (name.equals(ResourceInformation.MEMORY_MB.getName())) {
ret.setMemorySize(entry.getMinimumAllocation());
} else if (name.equals(ResourceInformation.VCORES.getName())) {
Long tmp = entry.getMinimumAllocation();
if (tmp > Integer.MAX_VALUE) {
tmp = (long) Integer.MAX_VALUE;
}
ret.setVirtualCores(tmp.intValue());
} else {
ret.setResourceValue(name, entry.getMinimumAllocation());
}
}
return ret;
}
/**
* Get a Resource object with for the maximum allocation possible.
* @return a Resource object with the maximum allocation for the scheduler
*/
public static Resource getResourceTypesMaximumAllocation() {
Resource ret = Resource.newInstance(0, 0);
for (ResourceInformation entry : resourceTypesArray) {
ret.setResourceValue(entry.getName(),
entry.getMaximumAllocation());
}
return ret;
}
/**
* Get default unit by given resource type.
* @param resourceType resourceType
* @return default unit
*/
public static String getDefaultUnit(String resourceType) {
ResourceInformation ri = getResourceTypes().get(resourceType);
if (ri != null) {
return ri.getUnits();
}
return "";
}
/**
* Get all resource types information from known resource types.
* @return List of ResourceTypeInfo
*/
public static List<ResourceTypeInfo> getResourcesTypeInfo() {
List<ResourceTypeInfo> array = new ArrayList<>();
// Add all resource types
Collection<ResourceInformation> resourcesInfo =
ResourceUtils.getResourceTypes().values();
for (ResourceInformation resourceInfo : resourcesInfo) {
array.add(ResourceTypeInfo
.newInstance(resourceInfo.getName(), resourceInfo.getUnits(),
resourceInfo.getResourceType()));
}
return array;
}
/**
* Reinitialize all resource types from external source (in case of client,
* server will send the updated list and local resourceutils cache will be
* updated as per server's list of resources).
*
* @param resourceTypeInfo
* List of resource types
*/
public static void reinitializeResources(
List<ResourceTypeInfo> resourceTypeInfo) {
Map<String, ResourceInformation> resourceInformationMap = new HashMap<>();
for (ResourceTypeInfo resourceType : resourceTypeInfo) {
resourceInformationMap.put(resourceType.getName(),
ResourceInformation.newInstance(resourceType.getName(),
resourceType.getDefaultUnit(), resourceType.getResourceType()));
}
ResourceUtils
.initializeResourcesFromResourceInformationMap(resourceInformationMap);
}
/**
* From a given configuration get all entries representing requested
* resources: entries that match the {prefix}{resourceName}={value}[{units}]
* pattern.
* @param configuration The configuration
* @param prefix Keys with this prefix are considered from the configuration
* @return The list of requested resources as described by the configuration
*/
public static List<ResourceInformation> getRequestedResourcesFromConfig(
Configuration configuration, String prefix) {
List<ResourceInformation> result = new ArrayList<>();
Map<String, String> customResourcesMap = configuration
.getValByRegex("^" + Pattern.quote(prefix) + YARN_IO_OPTIONAL + "[^.]+$");
for (Entry<String, String> resource : customResourcesMap.entrySet()) {
String resourceName = resource.getKey().substring(prefix.length());
Matcher matcher =
RESOURCE_REQUEST_VALUE_PATTERN.matcher(resource.getValue());
if (!matcher.matches()) {
String errorMsg = "Invalid resource request specified for property "
+ resource.getKey() + ": \"" + resource.getValue()
+ "\", expected format is: value[ ][units]";
LOG.error(errorMsg);
throw new IllegalArgumentException(errorMsg);
}
long value = Long.parseLong(matcher.group(1));
String unit = matcher.group(2);
if (unit.isEmpty()) {
unit = ResourceUtils.getDefaultUnit(resourceName);
}
ResourceInformation resourceInformation = new ResourceInformation();
resourceInformation.setName(resourceName);
resourceInformation.setValue(value);
resourceInformation.setUnits(unit);
result.add(resourceInformation);
}
return result;
}
/**
* Are mandatory resources like memory-mb, vcores available?
* If not, throw exceptions. On availability, ensure those values are
* within boundary.
* @param res resource
* @throws IllegalArgumentException if mandatory resource is not available or
* value is not within boundary
*/
public static void areMandatoryResourcesAvailable(Resource res) {
ResourceInformation memoryResourceInformation =
res.getResourceInformation(MEMORY);
if (memoryResourceInformation != null) {
long value = memoryResourceInformation.getValue();
if (value > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Value '" + value + "' for "
+ "resource memory is more than the maximum for an integer.");
}
if (value == 0) {
throw new IllegalArgumentException("Invalid value for resource '" +
MEMORY + "'. Value cannot be 0(zero).");
}
} else {
throw new IllegalArgumentException("Mandatory resource 'memory-mb' "
+ "is missing.");
}
ResourceInformation vcoresResourceInformation =
res.getResourceInformation(VCORES);
if (vcoresResourceInformation != null) {
long value = vcoresResourceInformation.getValue();
if (value > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Value '" + value + "' for resource"
+ " vcores is more than the maximum for an integer.");
}
if (value == 0) {
throw new IllegalArgumentException("Invalid value for resource '" +
VCORES + "'. Value cannot be 0(zero).");
}
} else {
throw new IllegalArgumentException("Mandatory resource 'vcores' "
+ "is missing.");
}
}
/**
* Create an array of {@link ResourceInformation} objects corresponding to
* the passed in map of names to values. The array will be ordered according
* to the order returned by {@link #getResourceTypesArray()}. The value of
* each resource type in the returned array will either be the value given for
* that resource in the {@code res} parameter or, if none is given, 0.
*
* @param res the map of resource type values
* @return an array of {@link ResourceInformation} instances
*/
public static ResourceInformation[] createResourceTypesArray(Map<String,
Long> res) {
initializeResourceTypesIfNeeded();
ResourceInformation[] info = new ResourceInformation[resourceTypes.size()];
for (Entry<String, Integer> entry : RESOURCE_NAME_TO_INDEX.entrySet()) {
int index = entry.getValue();
Long value = res.get(entry.getKey());
if (value == null) {
value = 0L;
}
info[index] = new ResourceInformation();
ResourceInformation.copy(resourceTypesArray[index], info[index]);
info[index].setValue(value);
}
return info;
}
/**
* Return a new {@link Resource} instance with all resource values
* initialized to {@code value}.
* @param value the value to use for all resources
* @return a new {@link Resource} instance
*/
@InterfaceAudience.Private
@InterfaceStability.Unstable
public static Resource createResourceWithSameValue(long value) {
LightWeightResource res = new LightWeightResource(value,
Long.valueOf(value).intValue());
int numberOfResources = getNumberOfKnownResourceTypes();
for (int i = 2; i < numberOfResources; i++) {
res.setResourceValue(i, value);
}
return res;
}
public static Resource multiplyFloor(Resource resource, double multiplier) {
Resource newResource = Resource.newInstance(0, 0);
for (ResourceInformation resourceInformation : resource.getResources()) {
newResource.setResourceValue(resourceInformation.getName(),
(long) Math.floor(resourceInformation.getValue() * multiplier));
}
return newResource;
}
public static Resource multiplyRound(Resource resource, double multiplier) {
Resource newResource = Resource.newInstance(0, 0);
for (ResourceInformation resourceInformation : resource.getResources()) {
newResource.setResourceValue(resourceInformation.getName(),
Math.round(resourceInformation.getValue() * multiplier));
}
return newResource;
}
@InterfaceAudience.Private
@InterfaceStability.Unstable
public static Resource createResourceFromString(
String resourceStr,
List<ResourceTypeInfo> resourceTypeInfos) {
Map<String, Long> typeToValue = parseResourcesString(resourceStr);
validateResourceTypes(typeToValue.keySet(), resourceTypeInfos);
Resource resource = Resource.newInstance(0, 0);
for (Entry<String, Long> entry : typeToValue.entrySet()) {
resource.setResourceValue(entry.getKey(), entry.getValue());
}
return resource;
}
private static Map<String, Long> parseResourcesString(String resourcesStr) {
Map<String, Long> resources = new HashMap<>();
String[] pairs = resourcesStr.trim().split(",");
for (String resource : pairs) {
resource = resource.trim();
if (!resource.matches(RES_PATTERN)) {
throw new IllegalArgumentException("\"" + resource + "\" is not a "
+ "valid resource type/amount pair. "
+ "Please provide key=amount pairs separated by commas.");
}
String[] splits = resource.split("=");
String key = splits[0], value = splits[1];
String units = getUnits(value);
String valueWithoutUnit = value.substring(0,
value.length()- units.length()).trim();
long resourceValue = Long.parseLong(valueWithoutUnit);
// Convert commandline unit to standard YARN unit.
if (units.equals("M") || units.equals("m")) {
units = "Mi";
} else if (units.equals("G") || units.equals("g")) {
units = "Gi";
} else if (units.isEmpty()) {
// do nothing;
LOG.debug("units is empty.");
} else {
throw new IllegalArgumentException("Acceptable units are M/G or empty");
}
// special handle memory-mb and memory
if (key.equals(ResourceInformation.MEMORY_URI)) {
if (!units.isEmpty()) {
resourceValue = UnitsConversionUtil.convert(units, "Mi",
resourceValue);
}
}
if (key.equals("memory")) {
key = ResourceInformation.MEMORY_URI;
resourceValue = UnitsConversionUtil.convert(units, "Mi",
resourceValue);
}
// special handle gpu
if (key.equals("gpu")) {
key = ResourceInformation.GPU_URI;
}
// special handle fpga
if (key.equals("fpga")) {
key = ResourceInformation.FPGA_URI;
}
resources.put(key, resourceValue);
}
return resources;
}
private static void validateResourceTypes(
Iterable<String> resourceNames,
List<ResourceTypeInfo> resourceTypeInfos)
throws ResourceNotFoundException {
for (String resourceName : resourceNames) {
if (!resourceTypeInfos.stream().anyMatch(
e -> e.getName().equals(resourceName))) {
throw new ResourceNotFoundException(
"Unknown resource: " + resourceName);
}
}
}
public static StringBuilder
getCustomResourcesStrings(Resource resource) {
StringBuilder res = new StringBuilder();
if (ResourceUtils.getNumberOfKnownResourceTypes() > 2) {
ResourceInformation[] resources =
resource.getResources();
for (int i = 2; i < resources.length; i++) {
ResourceInformation resInfo = resources[i];
res.append(","
+ resInfo.getName() + "=" + resInfo.getValue());
}
}
return res;
}
}
|
apache/usergrid | 36,326 | stack/core/src/main/java/org/apache/usergrid/persistence/Results.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.usergrid.persistence;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.Map.Entry;
import javax.xml.bind.annotation.XmlRootElement;
import com.google.common.base.Optional;
import com.netflix.astyanax.serializers.IntegerSerializer;
import org.apache.usergrid.corepersistence.results.QueryExecutor;
import org.apache.usergrid.persistence.Query.Level;
import org.apache.usergrid.utils.MapUtils;
import org.apache.usergrid.utils.StringUtils;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion;
import static org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString;
import static org.apache.usergrid.persistence.SimpleEntityRef.ref;
import static org.apache.usergrid.utils.ClassUtils.cast;
import static org.apache.usergrid.utils.ConversionUtils.bytes;
@XmlRootElement
public class Results implements Iterable<Entity> {
private static final IntegerSerializer INTEGER_SERIALIZER = IntegerSerializer.get();
Level level = Level.IDS;
UUID id;
List<UUID> ids;
Set<UUID> idSet;
EntityRef ref;
List<EntityRef> refs;
Map<UUID, EntityRef> refsMap;
Map<String, List<EntityRef>> refsByType;
Entity entity;
List<Entity> entities;
Map<UUID, Entity> entitiesMap;
Map<String, List<Entity>> entitiesByType;
List<ConnectionRef> connections;
boolean forwardConnections = true;
List<AggregateCounterSet> counters;
Set<String> types;
Map<UUID, Map<String, Object>> metadata;
boolean metadataMerged = true;
UUID nextResult;
String cursor;
Query query;
Object data;
String dataName;
private QueryExecutor queryExecutor;
public Results() {
}
public Results( Results r ) {
if ( r != null ) {
level = r.level;
id = r.id;
ids = r.ids;
idSet = r.idSet;
ref = r.ref;
refs = r.refs;
refsMap = r.refsMap;
refsByType = r.refsByType;
entity = r.entity;
entities = r.entities;
entitiesMap = r.entitiesMap;
entitiesByType = r.entitiesByType;
connections = r.connections;
forwardConnections = r.forwardConnections;
counters = r.counters;
types = r.types;
metadata = r.metadata;
metadataMerged = r.metadataMerged;
nextResult = r.nextResult;
cursor = r.cursor;
query = r.query;
data = r.data;
dataName = r.dataName;
}
}
public void init() {
level = Level.IDS;
id = null;
ids = null;
idSet = null;
ref = null;
refs = null;
refsMap = null;
refsByType = null;
entity = null;
entities = null;
entitiesMap = null;
entitiesByType = null;
connections = null;
forwardConnections = true;
counters = null;
types = null;
// metadata = null;
metadataMerged = false;
query = null;
data = null;
dataName = null;
}
public static Results fromIdList( List<UUID> l ) {
Results r = new Results();
r.setIds( l );
return r;
}
public static Results fromIdList( List<UUID> l, String type ) {
if ( type == null ) {
return fromIdList( l );
}
List<EntityRef> refs = new ArrayList<EntityRef>();
for ( UUID u : l ) {
refs.add( ref( type, u ) );
}
Results r = new Results();
r.setRefs(refs);
return r;
}
public static Results fromId( UUID id ) {
Results r = new Results();
if ( id != null ) {
List<UUID> l = new ArrayList<UUID>();
l.add( id );
r.setIds( l );
}
return r;
}
public static Results fromRefList( List<EntityRef> l ) {
Results r = new Results();
r.setRefs( l );
return r;
}
public static Results fromEntities( List<? extends Entity> l ) {
Results r = new Results();
r.setEntities(l);
return r;
}
public static Results fromEntity( Entity e ) {
Results r = new Results();
r.setEntity(e);
return r;
}
public static Results fromRef( EntityRef ref ) {
if ( ref instanceof Entity ) {
return fromEntity( ( Entity ) ref );
}
Results r = new Results();
r.setRef(ref);
return r;
}
public static Results fromData( Object obj ) {
Results r = new Results();
r.setData(obj);
return r;
}
public static Results fromCounters( AggregateCounterSet counters ) {
Results r = new Results();
List<AggregateCounterSet> l = new ArrayList<AggregateCounterSet>();
l.add( counters );
r.setCounters(l);
return r;
}
public static Results fromCounters( List<AggregateCounterSet> counters ) {
Results r = new Results();
r.setCounters(counters);
return r;
}
@SuppressWarnings("unchecked")
public static Results fromConnections( List<? extends ConnectionRef> connections ) {
Results r = new Results();
r.setConnections((List<ConnectionRef>) connections, true);
return r;
}
@SuppressWarnings("unchecked")
public static Results fromConnections( List<? extends ConnectionRef> connections, boolean forward ) {
Results r = new Results();
r.setConnections((List<ConnectionRef>) connections, forward);
return r;
}
public Level getLevel() {
return level;
}
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public Query getQuery() {
return query;
}
public void setQuery( Query query ) {
this.query = query;
}
public Results withQuery( Query query ) {
this.query = query;
return this;
}
@JsonSerialize(include = Inclusion.NON_NULL)
public UUID getId() {
if ( id != null ) {
return id;
}
if ( entity != null ) {
id = entity.getUuid();
return id;
}
if ( ( ids != null ) && ( ids.size() > 0 ) ) {
id = ids.get( 0 );
return id;
}
if ( ( entities != null ) && ( entities.size() > 0 ) ) {
entity = entities.get( 0 );
id = entity.getUuid();
return id;
}
if ( ( refs != null ) && ( refs.size() > 0 ) ) {
EntityRef ref = refs.get( 0 );
id = ref.getUuid();
}
return id;
}
@JsonSerialize(include = Inclusion.NON_NULL)
public List<UUID> getIds() {
if ( ids != null ) {
return ids;
}
/*
* if (connectionTypeAndEntityTypeToEntityIdMap != null) { ids = new
* ArrayList<UUID>(); Set<UUID> entitySet = new LinkedHashSet<UUID>();
* for (String ctype : connectionTypeAndEntityTypeToEntityIdMap
* .keySet()) { Map<String, List<UUID>> m =
* connectionTypeAndEntityTypeToEntityIdMap .get(ctype); for (String
* etype : m.keySet()) { List<UUID> l = m.get(etype); for (UUID id : l)
* { if (!entitySet.contains(id)) { ids.add(id); } } } } return ids; }
*/
if ( connections != null ) {
ids = new ArrayList<UUID>();
for ( ConnectionRef connection : connections ) {
if ( forwardConnections ) {
ConnectedEntityRef c = connection.getTargetRefs();
if ( c != null ) {
ids.add( c.getUuid() );
}
}
else {
EntityRef c = connection.getSourceRefs();
if ( c != null ) {
ids.add( c.getUuid() );
}
}
}
return ids;
}
if ( ( entities != null )
/* || (connectionTypeAndEntityTypeToEntityMap != null) */ ) {
// getEntities();
ids = new ArrayList<UUID>();
for ( Entity entity : entities ) {
ids.add( entity.getUuid() );
}
return ids;
}
if ( refs != null ) {
ids = new ArrayList<UUID>();
for ( EntityRef ref : refs ) {
ids.add( ref.getUuid() );
}
return ids;
}
if ( id != null ) {
ids = new ArrayList<UUID>();
ids.add( id );
return ids;
}
if ( entity != null ) {
ids = new ArrayList<UUID>();
ids.add( entity.getUuid() );
return ids;
}
return new ArrayList<UUID>();
}
public void setIds( List<UUID> resultsIds ) {
init();
ids = resultsIds;
level = Level.IDS;
}
public Results withIds( List<UUID> resultsIds ) {
setIds( resultsIds );
return this;
}
@JsonSerialize(include = Inclusion.NON_NULL)
public Set<UUID> getIdSet() {
if ( idSet != null ) {
return idSet;
}
getIds();
if ( ids != null ) {
idSet = new LinkedHashSet<UUID>();
idSet.addAll( ids );
return idSet;
}
return new LinkedHashSet<UUID>();
}
@JsonSerialize(include = Inclusion.NON_NULL)
@SuppressWarnings("unchecked")
public List<EntityRef> getRefs() {
if ( refs != null ) {
return refs;
}
List<?> l = getEntities();
if ( ( l != null ) && ( l.size() > 0 ) ) {
return ( List<EntityRef> ) l;
}
if ( connections != null ) {
refs = new ArrayList<EntityRef>();
for ( ConnectionRef connection : connections ) {
if ( forwardConnections ) {
ConnectedEntityRef c = connection.getTargetRefs();
if ( c != null ) {
refs.add( c );
}
}
else {
EntityRef c = connection.getSourceRefs();
if ( c != null ) {
refs.add( c );
}
}
}
return refs;
}
if ( ref != null ) {
refs = new ArrayList<EntityRef>();
refs.add(ref);
return refs;
}
return new ArrayList<EntityRef>();
}
public void setRefs( List<EntityRef> resultsRefs ) {
init();
refs = resultsRefs;
level = Level.REFS;
}
public void setRefsOnly( List<EntityRef> resultsRefs ) {
refs = resultsRefs;
}
public Results withRefs( List<EntityRef> resultsRefs ) {
setRefs( resultsRefs );
return this;
}
public void setRef( EntityRef ref ) {
init();
this.ref = ref;
level = Level.REFS;
}
public Results withRef( EntityRef ref ) {
setRef( ref );
return this;
}
@JsonSerialize(include = Inclusion.NON_NULL)
public EntityRef getRef() {
if ( ref != null ) {
return ref;
}
ref = getEntity();
if ( ref != null ) {
return ref;
}
UUID u = getId();
if ( u != null ) {
String type= null;
if(refs!=null && refs.size()>0){
type = refs.get(0).getType();
}
return ref( type,u );
}
return null;
}
@JsonSerialize(include = Inclusion.NON_NULL)
public Map<UUID, EntityRef> getRefsMap() {
if ( refsMap != null ) {
return refsMap;
}
getEntitiesMap();
if ( entitiesMap != null ) {
refsMap = cast( entitiesMap );
return refsMap;
}
getRefs();
if ( refs != null ) {
refsMap = new LinkedHashMap<UUID, EntityRef>();
for ( EntityRef ref : refs ) {
refsMap.put( ref.getUuid(), ref );
}
}
return refsMap;
}
@JsonSerialize(include = Inclusion.NON_NULL)
public Entity getEntity() {
mergeEntitiesWithMetadata();
if ( entity != null ) {
return entity;
}
if ( ( entities != null ) && ( entities.size() > 0 ) ) {
entity = entities.get( 0 );
return entity;
}
return null;
}
public void setEntity( Entity resultEntity ) {
init();
entity = resultEntity;
level = Level.CORE_PROPERTIES;
}
public void setEntity( final int index, final Entity entity){
this.entities.set( index, entity );
}
public Results withEntity( Entity resultEntity ) {
setEntity( resultEntity );
return this;
}
public Iterator<UUID> idIterator() {
List<UUID> l = getIds();
if ( l != null ) {
return l.iterator();
}
return ( new ArrayList<UUID>( 0 ) ).iterator();
}
@JsonSerialize(include = Inclusion.NON_NULL)
public List<Entity> getEntities() {
mergeEntitiesWithMetadata();
if ( entities != null ) {
return entities;
}
/*
* if (connectionTypeAndEntityTypeToEntityMap != null) { entities = new
* ArrayList<Entity>(); Map<UUID, Entity> eMap = new LinkedHashMap<UUID,
* Entity>(); for (String ctype :
* connectionTypeAndEntityTypeToEntityMap.keySet()) { Map<String,
* List<Entity>> m = connectionTypeAndEntityTypeToEntityMap .get(ctype);
* for (String etype : m.keySet()) { List<Entity> l = m.get(etype); for
* (Entity e : l) { if (!eMap.containsKey(e.getUuid())) { entities.add(e);
* eMap.put(e.getUuid(), e); } } } } return entities; }
*/
if ( entity != null ) {
entities = new ArrayList<Entity>();
entities.add( entity );
return entities;
}
return new ArrayList<Entity>();
}
@JsonSerialize(include = Inclusion.NON_NULL)
public Map<UUID, Entity> getEntitiesMap() {
if ( entitiesMap != null ) {
return entitiesMap;
}
if ( getEntities() != null ) {
entitiesMap = new LinkedHashMap<UUID, Entity>();
for ( Entity entity : getEntities() ) {
entitiesMap.put( entity.getUuid(), entity );
}
}
return entitiesMap;
}
public List<EntityRef> getEntityRefsByType( String type ) {
if ( entitiesByType != null ) {
return refsByType.get( type );
}
List<EntityRef> l = cast( getEntitiesByType( type ) );
if ( l != null ) {
return l;
}
getRefs();
if ( refs == null ) {
return null;
}
refsByType = new LinkedHashMap<String, List<EntityRef>>();
for ( Entity entity : entities ) {
l = refsByType.get( entity.getType() );
if ( l == null ) {
l = new ArrayList<EntityRef>();
refsByType.put( entity.getType(), l );
}
l.add( entity );
}
return l;
}
public List<Entity> getEntitiesByType( String type ) {
if ( entitiesByType != null ) {
return entitiesByType.get( type );
}
getEntities();
if ( entities == null ) {
return null;
}
List<Entity> l = null;
entitiesByType = new LinkedHashMap<String, List<Entity>>();
for ( Entity entity : entities ) {
l = entitiesByType.get( entity.getType() );
if ( l == null ) {
l = new ArrayList<Entity>();
entitiesByType.put( entity.getType(), l );
}
l.add( entity );
}
return l;
}
@JsonSerialize(include = Inclusion.NON_NULL)
public Set<String> getTypes() {
if ( types != null ) {
return types;
}
getEntityRefsByType("entity");
if ( entitiesByType != null ) {
types = entitiesByType.keySet();
}
else if ( refsByType != null ) {
types = refsByType.keySet();
}
return types;
}
public void merge( Results results ) {
getEntitiesMap();
results.getEntitiesMap();
if ( entitiesMap != null || results.entitiesMap != null ) {
level = Level.ALL_PROPERTIES;
// do nothing, nothing to union
if ( entitiesMap != null && results.entitiesMap == null ) {
return;
// other side has the results, assign and return
}
else if ( entitiesMap == null && results.entitiesMap != null ) {
entities = results.entities;
return;
}
entitiesMap.putAll( results.entitiesMap );
entities = new ArrayList<Entity>( entitiesMap.values() );
return;
}
getRefsMap();
results.getRefsMap();
if ( ( refsMap != null ) || ( results.refsMap != null ) ) {
level = Level.REFS;
// do nothing, nothing to union
if ( refsMap != null && results.refsMap == null ) {
return;
// other side has the results, assign and return
}
else if ( refsMap == null && results.refsMap != null ) {
refs = results.refs;
return;
}
refsMap.putAll( results.refsMap );
refs = new ArrayList<EntityRef>( refsMap.values() );
return;
}
getIdSet();
results.getIdSet();
if ( ( idSet != null ) && ( results.idSet != null ) ) {
level = Level.IDS;
// do nothing, nothing to union
if ( idSet != null && results.idSet == null ) {
return;
// other side has the results, assign and return
}
else if ( idSet == null && results.idSet != null ) {
ids = results.ids;
return;
}
idSet.addAll( results.idSet );
ids = new ArrayList<UUID>( idSet );
}
}
public void addEntities( Results results){
if(entities == null){
//init();
entities = new ArrayList<>();
level = Level.CORE_PROPERTIES;
}
if( results.getEntities().size() > 0){
entities.addAll(results.getEntities());
}
}
/** Remove the passed in results from the current results */
public void subtract( Results results ) {
getEntitiesMap();
results.getEntitiesMap();
if ( ( entitiesMap != null ) && ( results.entitiesMap != null ) ) {
Map<UUID, Entity> newMap = new LinkedHashMap<UUID, Entity>();
for ( Map.Entry<UUID, Entity> e : entitiesMap.entrySet() ) {
if ( !results.entitiesMap.containsKey( e.getKey() ) ) {
newMap.put( e.getKey(), e.getValue() );
}
}
entitiesMap = newMap;
entities = new ArrayList<Entity>( entitiesMap.values() );
level = Level.ALL_PROPERTIES;
return;
}
getRefsMap();
results.getRefsMap();
if ( ( refsMap != null ) && ( results.refsMap != null ) ) {
Map<UUID, EntityRef> newMap = new LinkedHashMap<UUID, EntityRef>();
for ( Map.Entry<UUID, EntityRef> e : refsMap.entrySet() ) {
if ( !results.refsMap.containsKey( e.getKey() ) ) {
newMap.put( e.getKey(), e.getValue() );
}
}
refsMap = newMap;
refs = new ArrayList<EntityRef>( refsMap.values() );
level = Level.REFS;
return;
}
getIdSet();
results.getIdSet();
if ( ( idSet != null ) && ( results.idSet != null ) ) {
Set<UUID> newSet = new LinkedHashSet<UUID>();
for ( UUID uuid : idSet ) {
if ( !results.idSet.contains( uuid ) ) {
newSet.add( uuid );
}
}
idSet = newSet;
ids = new ArrayList<UUID>( idSet );
level = Level.IDS;
}
}
/** Perform an intersection of the 2 results */
public void and( Results results ) {
getEntitiesMap();
results.getEntitiesMap();
if ( ( entitiesMap != null ) && ( results.entitiesMap != null ) ) {
Map<UUID, Entity> newMap = new LinkedHashMap<UUID, Entity>();
for ( Map.Entry<UUID, Entity> e : entitiesMap.entrySet() ) {
if ( results.entitiesMap.containsKey( e.getKey() ) ) {
newMap.put( e.getKey(), e.getValue() );
}
}
entitiesMap = newMap;
entities = new ArrayList<Entity>( entitiesMap.values() );
level = Level.ALL_PROPERTIES;
return;
}
getRefsMap();
results.getRefsMap();
if ( ( refsMap != null ) && ( results.refsMap != null ) ) {
Map<UUID, EntityRef> newMap = new LinkedHashMap<UUID, EntityRef>();
for ( Map.Entry<UUID, EntityRef> e : refsMap.entrySet() ) {
if ( results.refsMap.containsKey( e.getKey() ) ) {
newMap.put( e.getKey(), e.getValue() );
}
}
refsMap = newMap;
refs = new ArrayList<EntityRef>( refsMap.values() );
level = Level.REFS;
ids = null;
return;
}
getIdSet();
results.getIdSet();
if ( ( idSet != null ) && ( results.idSet != null ) ) {
Set<UUID> newSet = new LinkedHashSet<UUID>();
for ( UUID uuid : idSet ) {
if ( results.idSet.contains( uuid ) ) {
newSet.add( uuid );
}
}
idSet = newSet;
ids = new ArrayList<UUID>( idSet );
level = Level.IDS;
return;
}
// should be empty
init();
}
public void replace( Entity entity ) {
entitiesMap = null;
if ( ( this.entity != null ) && ( this.entity.getUuid().equals( entity.getUuid() ) ) ) {
this.entity = entity;
}
if ( entities != null ) {
ListIterator<Entity> i = entities.listIterator();
while ( i.hasNext() ) {
Entity e = i.next();
if ( e.getUuid().equals( entity.getUuid() ) ) {
i.set( entity );
}
}
}
}
public Results startingFrom( UUID entityId ) {
if ( entities != null ) {
for ( int i = 0; i < entities.size(); i++ ) {
Entity entity = entities.get( i );
if ( entityId.equals( entity.getUuid() ) ) {
if ( i == 0 ) {
return this;
}
return Results.fromEntities( entities.subList( i, entities.size() ) );
}
}
}
if ( refs != null ) {
for ( int i = 0; i < refs.size(); i++ ) {
EntityRef entityRef = refs.get( i );
if ( entityId.equals( entityRef.getUuid() ) ) {
if ( i == 0 ) {
return this;
}
return Results.fromRefList( refs.subList( i, refs.size() ) );
}
}
}
if ( ids != null ) {
for ( int i = 0; i < ids.size(); i++ ) {
UUID uuid = ids.get( i );
if ( entityId.equals( uuid ) ) {
if ( i == 0 ) {
return this;
}
return Results.fromIdList( ids.subList( i, ids.size() ) );
}
}
}
return this;
}
@SuppressWarnings("unchecked")
@JsonSerialize(include = Inclusion.NON_NULL)
public <E extends Entity> List<E> getList() {
List<Entity> l = getEntities();
return ( List<E> ) l;
}
public <E extends Entity> Iterator<E> iterator( Class<E> cls ) {
List<E> l = getList();
if ( l != null ) {
return l.iterator();
}
return ( new ArrayList<E>( 0 ) ).iterator();
}
@Override
public Iterator<Entity> iterator() {
List<Entity> l = getEntities();
if ( l != null ) {
return l.iterator();
}
return ( new ArrayList<Entity>( 0 ) ).iterator();
}
public Results findForProperty( String propertyName, Object propertyValue ) {
return findForProperty(propertyName, propertyValue, 1);
}
public Results findForProperty( String propertyName, Object propertyValue, int count ) {
if ( propertyValue == null ) {
return new Results();
}
List<Entity> l = getEntities();
if ( l == null ) {
return new Results();
}
List<Entity> found = new ArrayList<Entity>();
for ( Entity e : l ) {
if ( propertyValue.equals( e.getProperty( propertyName ) ) ) {
found.add( e );
if ( ( count > 0 ) && ( found.size() == count ) ) {
break;
}
}
}
return Results.fromEntities(found);
}
@SuppressWarnings("unchecked")
public void setEntities( List<? extends Entity> resultsEntities ) {
init();
entities = ( List<Entity> ) resultsEntities;
level = Level.CORE_PROPERTIES;
}
public Results withEntities( List<? extends Entity> resultsEntities ) {
setEntities( resultsEntities );
return this;
}
public boolean hasConnections() {
return connections != null;
}
@JsonSerialize(include = Inclusion.NON_NULL)
public List<ConnectionRef> getConnections() {
return connections;
}
private void setConnections( List<ConnectionRef> connections, boolean forwardConnections ) {
init();
this.connections = connections;
this.forwardConnections = forwardConnections;
level = Level.REFS;
for ( ConnectionRef connection : connections ) {
if ( forwardConnections ) {
this.setMetadata( connection.getTargetRefs().getUuid(), "connection",
connection.getConnectionType() );
}
else {
this.setMetadata( connection.getSourceRefs().getUuid(), "connection",
connection.getConnectionType() );
}
}
}
@JsonSerialize(include = Inclusion.NON_NULL)
public Object getObject() {
if ( data != null ) {
return data;
}
if ( entities != null ) {
return entities;
}
if ( ids != null ) {
return ids;
}
if ( entity != null ) {
return entity;
}
if ( id != null ) {
return id;
}
if ( counters != null ) {
return counters;
}
return null;
}
@JsonSerialize(include = Inclusion.NON_NULL)
public String getObjectName() {
if ( dataName != null ) {
return dataName;
}
if ( entities != null ) {
return "entities";
}
if ( ids != null ) {
return "ids";
}
if ( entity != null ) {
return "entity";
}
if ( id != null ) {
return "id";
}
return null;
}
public void setDataName( String dataName ) {
this.dataName = dataName;
}
public Results withDataName( String dataName ) {
this.dataName = dataName;
return this;
}
public boolean hasData() {
return data != null;
}
public void setData( Object data ) {
this.data = data;
}
public Results withData( Object data ) {
this.data = data;
return this;
}
@JsonSerialize(include = Inclusion.NON_NULL)
public Object getData() {
return data;
}
@JsonSerialize(include = Inclusion.NON_NULL)
public List<AggregateCounterSet> getCounters() {
return counters;
}
public void setCounters( List<AggregateCounterSet> counters ) {
this.counters = counters;
}
public Results withCounters( List<AggregateCounterSet> counters ) {
this.counters = counters;
return this;
}
public int size() {
if ( entities != null ) {
return entities.size();
}
if ( refs != null ) {
return refs.size();
}
if ( ids != null ) {
return ids.size();
}
if ( entity != null ) {
return 1;
}
if ( connections != null ) {
return connections.size();
}
if ( ref != null ) {
return 1;
}
if ( id != null ) {
return 1;
}
return 0;
}
public boolean isEmpty() {
return size() == 0;
}
@JsonSerialize(include = Inclusion.NON_NULL)
public UUID getNextResult() {
return nextResult;
}
public Results excludeCursorMetadataAttribute() {
if ( metadata != null ) {
for ( Entry<UUID, Map<String, Object>> entry : metadata.entrySet() ) {
Map<String, Object> map = entry.getValue();
if ( map != null ) {
map.remove( Schema.PROPERTY_CURSOR );
}
}
}
return new Results( this );
}
public Results trim( int count ) {
if ( count == 0 ) {
return this;
}
int size = size();
if ( size <= count ) {
return this;
}
List<UUID> ids = getIds();
UUID nextResult = null;
String cursor = null;
if ( ids.size() > count ) {
nextResult = ids.get( count );
ids = ids.subList( 0, count );
if ( metadata != null ) {
cursor = StringUtils.toString( MapUtils.getMapMap( metadata, nextResult, "cursor" ) );
}
if ( cursor == null ) {
cursor = encodeBase64URLSafeString( bytes( nextResult ) );
}
}
Results r = new Results( this );
if ( r.entities != null ) {
r.entities = r.entities.subList( 0, count );
}
if ( r.refs != null ) {
r.refs = r.refs.subList( 0, count );
}
if ( r.ids != null ) {
r.ids = r.ids.subList( 0, count );
}
r.setNextResult( nextResult );
r.setCursor( cursor );
return r;
}
public boolean hasMoreResults() {
return nextResult != null;
}
public void setNextResult( UUID nextResult ) {
this.nextResult = nextResult;
}
public Results withNextResult( UUID nextResult ) {
this.nextResult = nextResult;
return this;
}
@JsonSerialize(include = Inclusion.NON_NULL)
public String getCursor() {
return cursor;
}
public Optional<Integer> getOffsetFromCursor() {
Optional<Integer> offset = Optional.absent();
if(cursor != null && cursor.length() > 0){
byte[] bytes = org.apache.commons.codec.binary.Base64.decodeBase64(cursor);
ByteBuffer buffer = ByteBuffer.wrap(bytes);
Integer number = INTEGER_SERIALIZER.fromByteBuffer(buffer);
offset = Optional.of(number);
}
return offset;
}
public void setCursorFromOffset(Optional<Integer> offset) {
if(offset.isPresent()){
ByteBuffer buffer = INTEGER_SERIALIZER.toByteBuffer(offset.get());
cursor = org.apache.commons.codec.binary.Base64.encodeBase64String(buffer.array());
}else{
cursor = null;
}
}
public boolean hasCursor() {
return cursor != null && cursor.length() > 0;
}
public void setCursor( String cursor ) {
this.cursor = cursor;
}
public Results withCursor( String cursor ) {
this.cursor = cursor;
return this;
}
public void setMetadata( UUID id, String name, Object value ) {
if ( metadata == null ) {
metadata = new LinkedHashMap<UUID, Map<String, Object>>();
}
Map<String, Object> entityMetadata = metadata.get( id );
if ( entityMetadata == null ) {
entityMetadata = new LinkedHashMap<String, Object>();
metadata.put( id, entityMetadata );
}
entityMetadata.put( name, value );
metadataMerged = false;
// updateIndex(id, name, value);
}
public Results withMetadata( UUID id, String name, Object value ) {
setMetadata( id, name, value );
return this;
}
public void setMetadata( UUID id, Map<String, Object> data ) {
if ( metadata == null ) {
metadata = new LinkedHashMap<UUID, Map<String, Object>>();
}
Map<String, Object> entityMetadata = metadata.get( id );
if ( entityMetadata == null ) {
entityMetadata = new LinkedHashMap<String, Object>();
metadata.put( id, entityMetadata );
}
entityMetadata.putAll( data );
metadataMerged = false;
/*
* for (Entry<String, Object> m : data.entrySet()) { updateIndex(id,
* m.getKey(), m.getValue()); }
*/
}
public Results withMetadata( UUID id, Map<String, Object> data ) {
setMetadata( id, data );
return this;
}
public void setMetadata( Map<UUID, Map<String, Object>> metadata ) {
this.metadata = metadata;
}
public Results withMetadata( Map<UUID, Map<String, Object>> metadata ) {
this.metadata = metadata;
return this;
}
public void mergeEntitiesWithMetadata() {
if ( metadataMerged ) {
return;
}
if ( metadata == null ) {
return;
}
metadataMerged = true;
getEntities();
if ( entities != null ) {
for ( Entity entity : entities ) {
entity.clearMetadata();
Map<String, Object> entityMetadata = metadata.get( entity.getUuid() );
if ( entityMetadata != null ) {
entity.mergeMetadata( entityMetadata );
}
}
}
}
public void setQueryExecutor(final QueryExecutor queryExecutor){
this.queryExecutor = queryExecutor;
}
/** uses cursor to get next batch of Results (returns null if no cursor) */
public Results getNextPageResults() throws Exception {
if ( queryExecutor == null || !queryExecutor.hasNext() ) {
return new Results();
}
return queryExecutor.next();
}
}
|
google/copybara | 36,321 | javatests/com/google/copybara/git/gitlab/api/GitLabApiTest.java | /*
* Copyright (C) 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.copybara.git.gitlab.api;
import static com.google.api.client.http.HttpStatusCodes.STATUS_CODE_NO_CONTENT;
import static com.google.api.client.http.HttpStatusCodes.STATUS_CODE_SERVER_ERROR;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertThrows;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.LowLevelHttpRequest;
import com.google.api.client.http.LowLevelHttpResponse;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.testing.http.MockHttpTransport;
import com.google.api.client.testing.http.MockLowLevelHttpRequest;
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import com.google.api.client.util.Key;
import com.google.common.base.Splitter;
import com.google.common.base.VerifyException;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.copybara.credentials.ConstantCredentialIssuer;
import com.google.copybara.credentials.CredentialIssuer;
import com.google.copybara.git.gitlab.api.entities.Commit;
import com.google.copybara.git.gitlab.api.entities.CreateMergeRequestParams;
import com.google.copybara.git.gitlab.api.entities.GitLabApiEntity;
import com.google.copybara.git.gitlab.api.entities.GitLabApiParams;
import com.google.copybara.git.gitlab.api.entities.GitLabApiParams.Param;
import com.google.copybara.git.gitlab.api.entities.ListProjectMergeRequestParams;
import com.google.copybara.git.gitlab.api.entities.ListUsersParams;
import com.google.copybara.git.gitlab.api.entities.MergeRequest;
import com.google.copybara.git.gitlab.api.entities.Project;
import com.google.copybara.git.gitlab.api.entities.SetExternalStatusCheckParams;
import com.google.copybara.git.gitlab.api.entities.SetExternalStatusCheckResponse;
import com.google.copybara.git.gitlab.api.entities.UpdateMergeRequestParams;
import com.google.copybara.git.gitlab.api.entities.User;
import com.google.copybara.http.auth.AuthInterceptor;
import com.google.copybara.http.auth.BearerInterceptor;
import com.google.copybara.json.GsonParserUtil;
import com.google.copybara.util.console.testing.TestingConsole;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class GitLabApiTest {
public static final GsonFactory GSON_FACTORY = new GsonFactory();
private static final ImmutableList<ImmutableList<TestResponse>> SAMPLE_PAGES =
ImmutableList.of(
ImmutableList.of(new TestResponse(1), new TestResponse(2)),
ImmutableList.of(new TestResponse(3), new TestResponse(4)),
ImmutableList.of(new TestResponse(5), new TestResponse(6)));
private final TestingConsole console = new TestingConsole();
@Test
public void testPaginatedGet_singlePage() throws Exception {
MockHttpTransport httpTransport =
new PaginatedMockHttpTransport<>(
"https://gitlab.copybara.io/api/v4",
"/projects/12345/test_requests",
ImmutableList.of(SAMPLE_PAGES.getFirst()));
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
ImmutableList<TestResponse> fullResponse =
underTest.paginatedGet(
"/projects/12345/test_requests",
TestResponse.class,
ImmutableListMultimap.of(),
Integer.MAX_VALUE);
assertThat(fullResponse).containsExactlyElementsIn(SAMPLE_PAGES.getFirst());
}
@Test
public void paginatedGet_gitLabApiParams_addedToUrlCorrectly() throws Exception {
PaginatedMockHttpTransport<TestResponse> httpTransport =
new PaginatedMockHttpTransport<>(
"https://gitlab.copybara.io/api/v4",
"/projects/12345/test_requests",
ImmutableList.of(SAMPLE_PAGES.getFirst()));
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
GitLabApiParams gitLabApiParams = () -> ImmutableList.of(new Param("param", "value"));
ImmutableList<TestResponse> fullResponse =
underTest.paginatedGet(
"/projects/12345/test_requests",
TestResponse.class,
ImmutableListMultimap.of(),
Integer.MAX_VALUE,
gitLabApiParams);
assertThat(fullResponse).containsExactlyElementsIn(SAMPLE_PAGES.getFirst());
assertThat(httpTransport.getCapturedUrls())
.containsExactly(
"https://gitlab.copybara.io/api/v4/projects/12345/test_requests?"
+ gitLabApiParams.getQueryString()
+ "&per_page="
+ Integer.MAX_VALUE);
}
@Test
public void paginatedGet_gitLabApiParams_existingQueryStringHandledCorrectly() throws Exception {
PaginatedMockHttpTransport<TestResponse> httpTransport =
new PaginatedMockHttpTransport<>(
"https://gitlab.copybara.io/api/v4",
"/projects/12345/test_requests",
ImmutableList.of(SAMPLE_PAGES.getFirst()));
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
GitLabApiParams gitLabApiParams = () -> ImmutableList.of(new Param("param", "value"));
ImmutableList<TestResponse> fullResponse =
underTest.paginatedGet(
"/projects/12345/test_requests?foo=bar&baz=bat",
TestResponse.class,
ImmutableListMultimap.of(),
Integer.MAX_VALUE,
gitLabApiParams);
assertThat(fullResponse).containsExactlyElementsIn(SAMPLE_PAGES.getFirst());
assertThat(httpTransport.getCapturedUrls())
.containsExactly(
"https://gitlab.copybara.io/api/v4/projects/12345/test_requests?foo=bar&baz=bat&"
+ gitLabApiParams.getQueryString()
+ "&per_page="
+ Integer.MAX_VALUE);
}
@Test
public void testPaginatedGet_multiplePages() throws Exception {
MockHttpTransport httpTransport =
new PaginatedMockHttpTransport<>(
"https://gitlab.copybara.io/api/v4", "/projects/12345/test_requests", SAMPLE_PAGES);
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
ImmutableList<TestResponse> fullResponse =
underTest.paginatedGet(
"/projects/12345/test_requests",
TestResponse.class,
ImmutableListMultimap.of(),
Integer.MAX_VALUE);
assertThat(fullResponse)
.containsExactlyElementsIn(
SAMPLE_PAGES.stream().flatMap(List::stream).collect(toImmutableList()));
}
@Test
public void testPaginatedGet_exceptionIfNextUrlDoesNotMatch() {
MockHttpTransport httpTransport =
new PaginatedMockHttpTransport<>(
"https://bad-gitlab-instance.io/api/v4", "/projects/12345/test_requests", SAMPLE_PAGES);
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
VerifyException e =
assertThrows(
VerifyException.class,
() ->
underTest.paginatedGet(
"/projects/12345/test_requests",
TestResponse.class,
ImmutableListMultimap.of(),
2));
assertThat(e)
.hasMessageThat()
.contains(
"https://bad-gitlab-instance.io/api/v4/projects/12345/test_requests?per_page=2&page=2"
+ " doesn't start with https://gitlab.copybara.io/api/v4");
}
@Test
public void testPaginatedGet_paramHandling() throws Exception {
PaginatedMockHttpTransport<TestResponse> httpTransport =
new PaginatedMockHttpTransport<>(
"https://gitlab.copybara.io/api/v4", "/projects/12345/test_requests", SAMPLE_PAGES);
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
// Add some extra params in the requested path, to make sure they're preserved.
String path = "/projects/12345/test_requests?capy=bara&foo=bar";
ImmutableList<TestResponse> unused =
underTest.paginatedGet(path, TestResponse.class, ImmutableListMultimap.of(), 10);
assertThat(httpTransport.getCapturedUrls())
.containsExactly(
"https://gitlab.copybara.io/api/v4/projects/12345/test_requests?capy=bara&foo=bar&per_page=10",
"https://gitlab.copybara.io/api/v4/projects/12345/test_requests?capy=bara&foo=bar&per_page=10&page=2",
"https://gitlab.copybara.io/api/v4/projects/12345/test_requests?capy=bara&foo=bar&per_page=10&page=3");
}
@Test
public void paginatedGet_handleUrlQueryParamsCorrectly() throws Exception {
String path = "/projects/12345/test_requests";
PaginatedMockHttpTransport<TestResponse> httpTransport =
new PaginatedMockHttpTransport<>(
"https://gitlab.copybara.io/api/v4",
path,
ImmutableList.of(ImmutableList.of(new TestResponse(1))));
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
GitLabApiParams gitLabApiParams =
() -> ImmutableList.of(new Param("param1", "value1"), new Param("param2", "value2"));
ImmutableList<TestResponse> unused =
underTest.paginatedGet(
path, TestResponse.class, ImmutableListMultimap.of(), 10, gitLabApiParams);
assertThat(httpTransport.getCapturedUrls())
.containsExactly(
"https://gitlab.copybara.io/api/v4/projects/12345/test_requests?param1=value1¶m2=value2&per_page=10");
}
@Test
public void testGetMergeRequest() throws Exception {
String json =
"""
{
"id": 12345
}
""";
MockHttpTransportWithCapture httpTransport = new MockHttpTransportWithCapture(json);
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
Optional<MergeRequest> response = underTest.getMergeRequest(12345, 456123);
assertThat(response).isPresent();
assertThat(response.get().getId()).isEqualTo(12345);
assertThat(httpTransport.getCapturedUrls())
.containsExactly("https://gitlab.copybara.io/api/v4/projects/12345/merge_requests/456123");
}
@Test
public void testGetMergeRequest_badHttpResponse() throws Exception {
GitLabApi underTest = setupApiWithMockedStatusCodeResponse(STATUS_CODE_SERVER_ERROR);
GitLabApiException e =
assertThrows(GitLabApiException.class, () -> underTest.getMergeRequest(12345, 456123));
assertThat(e)
.hasMessageThat()
.contains(
"Error calling GET on"
+ " https://gitlab.copybara.io/api/v4/projects/12345/merge_requests/456123");
}
private GitLabApi setupApiWithMockedStatusCodeResponse(int statusCode) {
MockHttpTransport httpTransport =
new MockHttpTransport.Builder()
.setLowLevelHttpResponse(new MockLowLevelHttpResponse().setStatusCode(statusCode))
.build();
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
return underTest;
}
@Test
public void testGetMergeRequest_emptyResponse() throws Exception {
GitLabApi underTest = setupApiWithMockedStatusCodeResponse(STATUS_CODE_NO_CONTENT);
Optional<MergeRequest> mergeRequest = underTest.getMergeRequest(12345, 456123);
assertThat(mergeRequest).isEmpty();
}
@Test
public void getProjectMergeRequests_apiError_throwsException() throws Exception {
MockHttpTransport httpTransport =
new MockHttpTransport.Builder()
.setLowLevelHttpResponse(
new MockLowLevelHttpResponse().setStatusCode(STATUS_CODE_SERVER_ERROR))
.build();
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
GitLabApiException e =
assertThrows(
GitLabApiException.class,
() ->
underTest.getProjectMergeRequests(
12345, ListProjectMergeRequestParams.getDefaultInstance()));
assertThat(e)
.hasMessageThat()
.contains(
"Error calling GET on"
+ " https://gitlab.copybara.io/api/v4/projects/12345/merge_requests?per_page=50");
}
@Test
public void getProjectMergeRequests_noParams_singlePageResponseWorksSuccessfully()
throws Exception {
ArrayList<MergeRequest> mergeRequests =
GsonParserUtil.parseString(
"[{\"id\": 1}, {\"id\": 2}]",
TypeToken.getParameterized(ArrayList.class, MergeRequest.class).getType(),
false);
PaginatedMockHttpTransport<MergeRequest> httpTransport =
new PaginatedMockHttpTransport<>(
"https://gitlab.copybara.io/api/v4",
"/projects/12345/merge_requests",
ImmutableList.of(ImmutableList.copyOf(mergeRequests)));
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
ImmutableList<MergeRequest> fullResponse =
underTest.getProjectMergeRequests(
12345, ListProjectMergeRequestParams.getDefaultInstance());
assertThat(fullResponse.stream().map(MergeRequest::getId)).containsExactly(1, 2).inOrder();
assertThat(httpTransport.getCapturedUrls())
.containsExactly(
"https://gitlab.copybara.io/api/v4/projects/12345/merge_requests?per_page=50");
}
@Test
public void getProjectMergeRequests_withParams_singlePageResponseWorksSuccessfully()
throws Exception {
ArrayList<MergeRequest> mergeRequests =
GsonParserUtil.parseString(
"[{\"id\": 1}, {\"id\": 2}]",
TypeToken.getParameterized(ArrayList.class, MergeRequest.class).getType(),
false);
PaginatedMockHttpTransport<MergeRequest> httpTransport =
new PaginatedMockHttpTransport<>(
"https://gitlab.copybara.io/api/v4",
"/projects/12345/merge_requests",
ImmutableList.of(ImmutableList.copyOf(mergeRequests)));
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
ImmutableList<MergeRequest> fullResponse =
underTest.getProjectMergeRequests(
12345, new ListProjectMergeRequestParams(Optional.of("my_branch")));
assertThat(fullResponse.stream().map(MergeRequest::getId)).containsExactly(1, 2).inOrder();
assertThat(httpTransport.getCapturedUrls())
.containsExactly(
"https://gitlab.copybara.io/api/v4/projects/12345/merge_requests?source_branch=my_branch&per_page=50");
}
@Test
public void getProjectMergeRequests_noParams_multiPageResponseWorksSuccessfully()
throws Exception {
ArrayList<MergeRequest> page1 =
GsonParserUtil.parseString(
"[{\"id\": 1}, {\"id\": 2}]",
TypeToken.getParameterized(ArrayList.class, MergeRequest.class).getType(),
false);
ArrayList<MergeRequest> page2 =
GsonParserUtil.parseString(
"[{\"id\": 3}, {\"id\": 4}]",
TypeToken.getParameterized(ArrayList.class, MergeRequest.class).getType(),
false);
PaginatedMockHttpTransport<MergeRequest> httpTransport =
new PaginatedMockHttpTransport<>(
"https://gitlab.copybara.io/api/v4",
"/projects/12345/merge_requests",
ImmutableList.of(ImmutableList.copyOf(page1), ImmutableList.copyOf(page2)));
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
ImmutableList<MergeRequest> fullResponse =
underTest.getProjectMergeRequests(
12345, ListProjectMergeRequestParams.getDefaultInstance());
assertThat(fullResponse.stream().map(MergeRequest::getId))
.containsExactly(1, 2, 3, 4)
.inOrder();
assertThat(httpTransport.getCapturedUrls())
.containsExactly(
"https://gitlab.copybara.io/api/v4/projects/12345/merge_requests?per_page=50",
"https://gitlab.copybara.io/api/v4/projects/12345/merge_requests?per_page=50&page=2");
}
@Test
public void getProjectMergeRequests_withParams_multiPageResponseWorksSuccessfully()
throws Exception {
ArrayList<MergeRequest> page1 =
GsonParserUtil.parseString(
"[{\"id\": 1}, {\"id\": 2}]",
TypeToken.getParameterized(ArrayList.class, MergeRequest.class).getType(),
false);
ArrayList<MergeRequest> page2 =
GsonParserUtil.parseString(
"[{\"id\": 3}, {\"id\": 4}]",
TypeToken.getParameterized(ArrayList.class, MergeRequest.class).getType(),
false);
PaginatedMockHttpTransport<MergeRequest> httpTransport =
new PaginatedMockHttpTransport<>(
"https://gitlab.copybara.io/api/v4",
"/projects/12345/merge_requests",
ImmutableList.of(ImmutableList.copyOf(page1), ImmutableList.copyOf(page2)));
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
ImmutableList<MergeRequest> fullResponse =
underTest.getProjectMergeRequests(
12345, new ListProjectMergeRequestParams(Optional.of("my_branch")));
assertThat(fullResponse.stream().map(MergeRequest::getId))
.containsExactly(1, 2, 3, 4)
.inOrder();
assertThat(httpTransport.getCapturedUrls())
.containsExactly(
"https://gitlab.copybara.io/api/v4/projects/12345/merge_requests?source_branch=my_branch&per_page=50",
"https://gitlab.copybara.io/api/v4/projects/12345/merge_requests?source_branch=my_branch&per_page=50&page=2");
}
@Test
public void testGetProject() throws Exception {
String json =
"""
{
"id": 12345
}
""";
String urlEncodedPath = URLEncoder.encode("capybara/project", UTF_8);
MockHttpTransportWithCapture httpTransport = new MockHttpTransportWithCapture(json);
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
Optional<Project> response = underTest.getProject(urlEncodedPath);
assertThat(response).isPresent();
assertThat(response.get().getId()).isEqualTo(12345);
assertThat(httpTransport.getCapturedUrls())
.containsExactly("https://gitlab.copybara.io/api/v4/projects/" + urlEncodedPath);
}
@Test
public void testGetProject_badHttpResponse() {
String urlEncodedPath = URLEncoder.encode("capybara/project", UTF_8);
GitLabApi underTest = setupApiWithMockedStatusCodeResponse(STATUS_CODE_SERVER_ERROR);
GitLabApiException e =
assertThrows(GitLabApiException.class, () -> underTest.getProject(urlEncodedPath));
assertThat(e)
.hasMessageThat()
.contains(
"Error calling GET on https://gitlab.copybara.io/api/v4/projects/" + urlEncodedPath);
assertThat(e).hasCauseThat().isInstanceOf(HttpResponseException.class);
}
@Test
public void testGetProject_emptyResponse() throws Exception {
String urlEncodedPath = URLEncoder.encode("capybara/project", UTF_8);
GitLabApi underTest = setupApiWithMockedStatusCodeResponse(STATUS_CODE_NO_CONTENT);
Optional<Project> project = underTest.getProject(urlEncodedPath);
assertThat(project).isEmpty();
}
@Test
public void testGetCommit() throws Exception {
String json =
"""
{
"id": 12345
}
""";
MockHttpTransportWithCapture httpTransport = new MockHttpTransportWithCapture(json);
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
Optional<Commit> response = underTest.getCommit(12345, "refs/heads/cl_12345");
assertThat(response).isPresent();
assertThat(response.get().getId()).isEqualTo(12345);
}
@Test
public void testGetCommit_badHttpResponse() {
GitLabApi underTest = setupApiWithMockedStatusCodeResponse(STATUS_CODE_SERVER_ERROR);
GitLabApiException e =
assertThrows(
GitLabApiException.class, () -> underTest.getCommit(12345, "refs/heads/cl_12345"));
assertThat(e)
.hasMessageThat()
.contains(
"Error calling GET on"
+ " https://gitlab.copybara.io/api/v4/projects/12345/repository/commits/refs/heads/cl_12345");
assertThat(e).hasCauseThat().isInstanceOf(HttpResponseException.class);
}
@Test
public void testGetCommit_emptyResponse() throws Exception {
GitLabApi underTest = setupApiWithMockedStatusCodeResponse(STATUS_CODE_NO_CONTENT);
Optional<Commit> project = underTest.getCommit(12345, "refs/heads/cl_12345");
assertThat(project).isEmpty();
}
@Test
public void getListUsers() throws Exception {
String json =
"""
[{"id": 12345}, {"id": 6789}]
""";
MockHttpTransportWithCapture httpTransport = new MockHttpTransportWithCapture(json);
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
ImmutableList<User> response = underTest.getListUsers(new ListUsersParams("capybara"));
assertThat(response.stream().map(User::getId)).containsExactly(12345, 6789).inOrder();
assertThat(httpTransport.getCapturedUrls())
.containsExactly("https://gitlab.copybara.io/api/v4/users?username=capybara&per_page=50");
}
@Test
public void getListUsers_emptyResponse() throws Exception {
GitLabApi underTest = setupApiWithMockedStatusCodeResponse(STATUS_CODE_NO_CONTENT);
ImmutableList<User> response = underTest.getListUsers(new ListUsersParams("capybara"));
assertThat(response).isEmpty();
}
@Test
public void getListUsers_badHttpResponse() {
GitLabApi underTest = setupApiWithMockedStatusCodeResponse(STATUS_CODE_SERVER_ERROR);
GitLabApiException e =
assertThrows(
GitLabApiException.class,
() -> underTest.getListUsers(new ListUsersParams("capybara")));
assertThat(e)
.hasMessageThat()
.contains(
"Error calling GET on"
+ " https://gitlab.copybara.io/api/v4/users?username=capybara&per_page=50");
assertThat(e).hasCauseThat().isInstanceOf(HttpResponseException.class);
}
@Test
public void setExternalStatusCheck() throws Exception {
String json =
"""
{"id": 12345, "merge_request": {"iid": 99999}, "external_status_check": {"id": 12345}}
""";
MockHttpTransportWithCapture httpTransport = new MockHttpTransportWithCapture(json);
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
SetExternalStatusCheckParams params =
new SetExternalStatusCheckParams(12345, 99999, "shaValue", 12345, "passed");
Optional<SetExternalStatusCheckResponse> response = underTest.setExternalStatusCheck(params);
assertThat(response).isPresent();
assertThat(response.get().getMergeRequest().getIid()).isEqualTo(99999);
assertThat(response.get().getExternalStatusCheck().getStatusCheckId()).isEqualTo(12345);
}
@Test
public void setExternalStatusCheck_emptyResponse() throws Exception {
GitLabApi underTest = setupApiWithMockedStatusCodeResponse(STATUS_CODE_NO_CONTENT);
SetExternalStatusCheckParams params =
new SetExternalStatusCheckParams(12345, 99999, "shaValue", 12345, "passed");
Optional<SetExternalStatusCheckResponse> response = underTest.setExternalStatusCheck(params);
assertThat(response).isEmpty();
}
@Test
public void setExternalStatusCheck_badHttpResponse() {
GitLabApi underTest = setupApiWithMockedStatusCodeResponse(STATUS_CODE_SERVER_ERROR);
SetExternalStatusCheckParams params =
new SetExternalStatusCheckParams(12345, 99999, "shaValue", 12345, "passed");
GitLabApiException e =
assertThrows(GitLabApiException.class, () -> underTest.setExternalStatusCheck(params));
assertThat(e)
.hasMessageThat()
.contains(
"Error calling POST on"
+ " https://gitlab.copybara.io/api/v4/projects/12345/merge_requests/99999/status_check_responses");
assertThat(e).hasCauseThat().isInstanceOf(HttpResponseException.class);
}
@Test
public void createMergeRequest() throws Exception {
String json =
"""
{"iid": 1234}
""";
MockHttpTransportWithCapture httpTransport = new MockHttpTransportWithCapture(json);
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
CreateMergeRequestParams params =
new CreateMergeRequestParams(
12345,
"capys_source_branch",
"capys_target_branch",
"capys_title",
"capys_description",
ImmutableList.of(1, 2, 3, 4, 5));
Optional<MergeRequest> response = underTest.createMergeRequest(params);
assertThat(response).isPresent();
assertThat(response.get().getIid()).isEqualTo(1234);
}
@Test
public void createMergeRequest_emptyResponse() throws Exception {
GitLabApi underTest = setupApiWithMockedStatusCodeResponse(STATUS_CODE_NO_CONTENT);
CreateMergeRequestParams params =
new CreateMergeRequestParams(
12345,
"capys_source_branch",
"capys_target_branch",
"capys_title",
"capys_description",
ImmutableList.of(1, 2, 3, 4, 5));
Optional<MergeRequest> response = underTest.createMergeRequest(params);
assertThat(response).isEmpty();
}
@Test
public void createMergeRequest_badHttpResponse() {
GitLabApi underTest = setupApiWithMockedStatusCodeResponse(STATUS_CODE_SERVER_ERROR);
CreateMergeRequestParams params =
new CreateMergeRequestParams(
12345,
"capys_source_branch",
"capys_target_branch",
"capys_title",
"capys_description",
ImmutableList.of(1, 2, 3, 4, 5));
GitLabApiException e =
assertThrows(GitLabApiException.class, () -> underTest.createMergeRequest(params));
assertThat(e)
.hasMessageThat()
.contains(
"Error calling POST on"
+ " https://gitlab.copybara.io/api/v4/projects/12345/merge_requests");
assertThat(e).hasCauseThat().isInstanceOf(HttpResponseException.class);
}
@Test
public void updateMergeRequest() throws Exception {
String json =
"""
{"iid": 1234}
""";
MockHttpTransportWithCapture httpTransport = new MockHttpTransportWithCapture(json);
GitLabApi underTest =
new GitLabApi(
getApiTransport(
httpTransport,
"https://gitlab.copybara.io/capybara/project",
Optional.of(getBearerInterceptor())));
UpdateMergeRequestParams params =
new UpdateMergeRequestParams(
12345, 99999, "capys_title", "capys_description", ImmutableList.of(1, 2, 3, 4, 5),
null);
Optional<MergeRequest> response = underTest.updateMergeRequest(params);
assertThat(response).isPresent();
assertThat(response.get().getIid()).isEqualTo(1234);
}
@Test
public void updateMergeRequest_emptyResponse() throws Exception {
GitLabApi underTest = setupApiWithMockedStatusCodeResponse(STATUS_CODE_NO_CONTENT);
UpdateMergeRequestParams params =
new UpdateMergeRequestParams(
12345, 99999, "capys_title", "capys_description", ImmutableList.of(1, 2, 3, 4, 5),
null);
Optional<MergeRequest> response = underTest.updateMergeRequest(params);
assertThat(response).isEmpty();
}
@Test
public void updateMergeRequest_badHttpResponse() {
GitLabApi underTest = setupApiWithMockedStatusCodeResponse(STATUS_CODE_SERVER_ERROR);
UpdateMergeRequestParams params =
new UpdateMergeRequestParams(
12345, 99999, "capys_title", "capys_description", ImmutableList.of(1, 2, 3, 4, 5),
null);
GitLabApiException e =
assertThrows(GitLabApiException.class, () -> underTest.updateMergeRequest(params));
assertThat(e)
.hasMessageThat()
.contains(
"Error calling PUT on"
+ " https://gitlab.copybara.io/api/v4/projects/12345/merge_requests/99999");
assertThat(e).hasCauseThat().isInstanceOf(HttpResponseException.class);
}
private static BearerInterceptor getBearerInterceptor() {
CredentialIssuer credentialIssuer =
ConstantCredentialIssuer.createConstantSecret("test", "example-access-token");
return new BearerInterceptor(credentialIssuer);
}
private GitLabApiTransport getApiTransport(
HttpTransport httpTransport, String url, Optional<AuthInterceptor> authInterceptor) {
return new GitLabApiTransportImpl(url, httpTransport, console, authInterceptor);
}
private static class MockHttpTransportWithCapture extends MockHttpTransport {
private final ImmutableList.Builder<String> capturedUrls = ImmutableList.builder();
private final String response;
public MockHttpTransportWithCapture(String response) {
super();
this.response = response;
}
/**
* Returns the URLs requested from this transport.
*
* @return a list of URLs.
*/
public ImmutableList<String> getCapturedUrls() {
return capturedUrls.build();
}
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
capturedUrls.add(url);
return new MockLowLevelHttpRequest()
.setResponse(new MockLowLevelHttpResponse().setContent(response));
}
}
private static class PaginatedMockHttpTransport<T extends GitLabApiEntity>
extends MockHttpTransport {
private final String apiUrl;
private final String path;
private final ImmutableList<ImmutableList<T>> pages;
private final ImmutableList.Builder<String> capturedUrls = ImmutableList.builder();
public PaginatedMockHttpTransport(
String apiUrl, String path, ImmutableList<ImmutableList<T>> pages) {
this.apiUrl = apiUrl;
this.path = path;
this.pages = pages;
}
/**
* Returns the URLs requested from this transport.
*
* @return a list of URLs.
*/
public ImmutableList<String> getCapturedUrls() {
return capturedUrls.build();
}
@Override
public LowLevelHttpRequest buildRequest(String method, String url) {
capturedUrls.add(url);
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
LinkedHashMap<String, String> urlParamsMap = getUrlParamsMap(url);
int page = Integer.parseInt(urlParamsMap.getOrDefault("page", "1"));
// GitLab's page parameter starts at 1, not 0.
int index = page - 1;
if (index < pages.size()) {
response.setContent(GSON_FACTORY.toString(pages.get(index)));
if (index != pages.size() - 1) {
// Add a link header if we're not at the last index of the page list.
response.setHeaderNames(ImmutableList.of("link"));
urlParamsMap.put("page", String.valueOf(++page));
String nextUrl = apiUrl + path + constructUrlParam(urlParamsMap);
response.setHeaderValues(ImmutableList.of("<" + nextUrl + ">; rel=\"next\""));
}
}
return response;
}
};
}
private static LinkedHashMap<String, String> getUrlParamsMap(String url) {
return Splitter.on(',')
.trimResults()
.splitToStream(URI.create(url).getQuery())
.flatMap(query -> Splitter.on('&').splitToStream(query))
.map(s -> Splitter.on('=').splitToList(s))
.collect(
Collectors.toMap(List::getFirst, List::getLast, (o, n) -> n, LinkedHashMap::new));
}
private static String constructUrlParam(LinkedHashMap<String, String> params) {
StringBuilder sb = new StringBuilder();
for (Entry<String, String> param : params.sequencedEntrySet()) {
if (sb.isEmpty()) {
sb.append('?');
} else {
sb.append('&');
}
sb.append(param.getKey()).append("=").append(param.getValue());
}
return sb.toString();
}
}
/**
* A response class used for GitLab API related tests. This is only intended for testing purposes,
* and public visibility is required for GSON support.
*/
public static class TestResponse implements GitLabApiEntity {
@Key public int id;
@SuppressWarnings("unused")
public TestResponse() {}
public TestResponse(int id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof TestResponse)) {
return false;
}
return this.id == ((TestResponse) obj).id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
}
|
googleapis/google-cloud-java | 36,534 | java-monitoring/proto-google-cloud-monitoring-v3/src/main/java/com/google/monitoring/v3/Point.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/monitoring/v3/metric.proto
// Protobuf Java Version: 3.25.8
package com.google.monitoring.v3;
/**
*
*
* <pre>
* A single data point in a time series.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.Point}
*/
public final class Point extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.monitoring.v3.Point)
PointOrBuilder {
private static final long serialVersionUID = 0L;
// Use Point.newBuilder() to construct.
private Point(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Point() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new Point();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.monitoring.v3.MetricProto
.internal_static_google_monitoring_v3_Point_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.MetricProto
.internal_static_google_monitoring_v3_Point_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.Point.class, com.google.monitoring.v3.Point.Builder.class);
}
private int bitField0_;
public static final int INTERVAL_FIELD_NUMBER = 1;
private com.google.monitoring.v3.TimeInterval interval_;
/**
*
*
* <pre>
* The time interval to which the data point applies. For `GAUGE` metrics,
* the start time is optional, but if it is supplied, it must equal the
* end time. For `DELTA` metrics, the start
* and end time should specify a non-zero interval, with subsequent points
* specifying contiguous and non-overlapping intervals. For `CUMULATIVE`
* metrics, the start and end time should specify a non-zero interval, with
* subsequent points specifying the same start time and increasing end times,
* until an event resets the cumulative value to zero and sets a new start
* time for the following points.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval interval = 1;</code>
*
* @return Whether the interval field is set.
*/
@java.lang.Override
public boolean hasInterval() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The time interval to which the data point applies. For `GAUGE` metrics,
* the start time is optional, but if it is supplied, it must equal the
* end time. For `DELTA` metrics, the start
* and end time should specify a non-zero interval, with subsequent points
* specifying contiguous and non-overlapping intervals. For `CUMULATIVE`
* metrics, the start and end time should specify a non-zero interval, with
* subsequent points specifying the same start time and increasing end times,
* until an event resets the cumulative value to zero and sets a new start
* time for the following points.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval interval = 1;</code>
*
* @return The interval.
*/
@java.lang.Override
public com.google.monitoring.v3.TimeInterval getInterval() {
return interval_ == null
? com.google.monitoring.v3.TimeInterval.getDefaultInstance()
: interval_;
}
/**
*
*
* <pre>
* The time interval to which the data point applies. For `GAUGE` metrics,
* the start time is optional, but if it is supplied, it must equal the
* end time. For `DELTA` metrics, the start
* and end time should specify a non-zero interval, with subsequent points
* specifying contiguous and non-overlapping intervals. For `CUMULATIVE`
* metrics, the start and end time should specify a non-zero interval, with
* subsequent points specifying the same start time and increasing end times,
* until an event resets the cumulative value to zero and sets a new start
* time for the following points.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval interval = 1;</code>
*/
@java.lang.Override
public com.google.monitoring.v3.TimeIntervalOrBuilder getIntervalOrBuilder() {
return interval_ == null
? com.google.monitoring.v3.TimeInterval.getDefaultInstance()
: interval_;
}
public static final int VALUE_FIELD_NUMBER = 2;
private com.google.monitoring.v3.TypedValue value_;
/**
*
*
* <pre>
* The value of the data point.
* </pre>
*
* <code>.google.monitoring.v3.TypedValue value = 2;</code>
*
* @return Whether the value field is set.
*/
@java.lang.Override
public boolean hasValue() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The value of the data point.
* </pre>
*
* <code>.google.monitoring.v3.TypedValue value = 2;</code>
*
* @return The value.
*/
@java.lang.Override
public com.google.monitoring.v3.TypedValue getValue() {
return value_ == null ? com.google.monitoring.v3.TypedValue.getDefaultInstance() : value_;
}
/**
*
*
* <pre>
* The value of the data point.
* </pre>
*
* <code>.google.monitoring.v3.TypedValue value = 2;</code>
*/
@java.lang.Override
public com.google.monitoring.v3.TypedValueOrBuilder getValueOrBuilder() {
return value_ == null ? com.google.monitoring.v3.TypedValue.getDefaultInstance() : value_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getInterval());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getValue());
}
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, getInterval());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getValue());
}
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.monitoring.v3.Point)) {
return super.equals(obj);
}
com.google.monitoring.v3.Point other = (com.google.monitoring.v3.Point) obj;
if (hasInterval() != other.hasInterval()) return false;
if (hasInterval()) {
if (!getInterval().equals(other.getInterval())) return false;
}
if (hasValue() != other.hasValue()) return false;
if (hasValue()) {
if (!getValue().equals(other.getValue())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasInterval()) {
hash = (37 * hash) + INTERVAL_FIELD_NUMBER;
hash = (53 * hash) + getInterval().hashCode();
}
if (hasValue()) {
hash = (37 * hash) + VALUE_FIELD_NUMBER;
hash = (53 * hash) + getValue().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.monitoring.v3.Point parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.Point parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.Point parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.Point 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.monitoring.v3.Point parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.Point parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.Point parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.Point 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.monitoring.v3.Point parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.Point 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.monitoring.v3.Point parseFrom(com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.Point 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.monitoring.v3.Point 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 single data point in a time series.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.Point}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.monitoring.v3.Point)
com.google.monitoring.v3.PointOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.monitoring.v3.MetricProto
.internal_static_google_monitoring_v3_Point_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.MetricProto
.internal_static_google_monitoring_v3_Point_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.Point.class, com.google.monitoring.v3.Point.Builder.class);
}
// Construct using com.google.monitoring.v3.Point.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getIntervalFieldBuilder();
getValueFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
interval_ = null;
if (intervalBuilder_ != null) {
intervalBuilder_.dispose();
intervalBuilder_ = null;
}
value_ = null;
if (valueBuilder_ != null) {
valueBuilder_.dispose();
valueBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.monitoring.v3.MetricProto
.internal_static_google_monitoring_v3_Point_descriptor;
}
@java.lang.Override
public com.google.monitoring.v3.Point getDefaultInstanceForType() {
return com.google.monitoring.v3.Point.getDefaultInstance();
}
@java.lang.Override
public com.google.monitoring.v3.Point build() {
com.google.monitoring.v3.Point result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.monitoring.v3.Point buildPartial() {
com.google.monitoring.v3.Point result = new com.google.monitoring.v3.Point(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.monitoring.v3.Point result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.interval_ = intervalBuilder_ == null ? interval_ : intervalBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.value_ = valueBuilder_ == null ? value_ : valueBuilder_.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.monitoring.v3.Point) {
return mergeFrom((com.google.monitoring.v3.Point) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.monitoring.v3.Point other) {
if (other == com.google.monitoring.v3.Point.getDefaultInstance()) return this;
if (other.hasInterval()) {
mergeInterval(other.getInterval());
}
if (other.hasValue()) {
mergeValue(other.getValue());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(getIntervalFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getValueFieldBuilder().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.monitoring.v3.TimeInterval interval_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.TimeInterval,
com.google.monitoring.v3.TimeInterval.Builder,
com.google.monitoring.v3.TimeIntervalOrBuilder>
intervalBuilder_;
/**
*
*
* <pre>
* The time interval to which the data point applies. For `GAUGE` metrics,
* the start time is optional, but if it is supplied, it must equal the
* end time. For `DELTA` metrics, the start
* and end time should specify a non-zero interval, with subsequent points
* specifying contiguous and non-overlapping intervals. For `CUMULATIVE`
* metrics, the start and end time should specify a non-zero interval, with
* subsequent points specifying the same start time and increasing end times,
* until an event resets the cumulative value to zero and sets a new start
* time for the following points.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval interval = 1;</code>
*
* @return Whether the interval field is set.
*/
public boolean hasInterval() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The time interval to which the data point applies. For `GAUGE` metrics,
* the start time is optional, but if it is supplied, it must equal the
* end time. For `DELTA` metrics, the start
* and end time should specify a non-zero interval, with subsequent points
* specifying contiguous and non-overlapping intervals. For `CUMULATIVE`
* metrics, the start and end time should specify a non-zero interval, with
* subsequent points specifying the same start time and increasing end times,
* until an event resets the cumulative value to zero and sets a new start
* time for the following points.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval interval = 1;</code>
*
* @return The interval.
*/
public com.google.monitoring.v3.TimeInterval getInterval() {
if (intervalBuilder_ == null) {
return interval_ == null
? com.google.monitoring.v3.TimeInterval.getDefaultInstance()
: interval_;
} else {
return intervalBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The time interval to which the data point applies. For `GAUGE` metrics,
* the start time is optional, but if it is supplied, it must equal the
* end time. For `DELTA` metrics, the start
* and end time should specify a non-zero interval, with subsequent points
* specifying contiguous and non-overlapping intervals. For `CUMULATIVE`
* metrics, the start and end time should specify a non-zero interval, with
* subsequent points specifying the same start time and increasing end times,
* until an event resets the cumulative value to zero and sets a new start
* time for the following points.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval interval = 1;</code>
*/
public Builder setInterval(com.google.monitoring.v3.TimeInterval value) {
if (intervalBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
interval_ = value;
} else {
intervalBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The time interval to which the data point applies. For `GAUGE` metrics,
* the start time is optional, but if it is supplied, it must equal the
* end time. For `DELTA` metrics, the start
* and end time should specify a non-zero interval, with subsequent points
* specifying contiguous and non-overlapping intervals. For `CUMULATIVE`
* metrics, the start and end time should specify a non-zero interval, with
* subsequent points specifying the same start time and increasing end times,
* until an event resets the cumulative value to zero and sets a new start
* time for the following points.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval interval = 1;</code>
*/
public Builder setInterval(com.google.monitoring.v3.TimeInterval.Builder builderForValue) {
if (intervalBuilder_ == null) {
interval_ = builderForValue.build();
} else {
intervalBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The time interval to which the data point applies. For `GAUGE` metrics,
* the start time is optional, but if it is supplied, it must equal the
* end time. For `DELTA` metrics, the start
* and end time should specify a non-zero interval, with subsequent points
* specifying contiguous and non-overlapping intervals. For `CUMULATIVE`
* metrics, the start and end time should specify a non-zero interval, with
* subsequent points specifying the same start time and increasing end times,
* until an event resets the cumulative value to zero and sets a new start
* time for the following points.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval interval = 1;</code>
*/
public Builder mergeInterval(com.google.monitoring.v3.TimeInterval value) {
if (intervalBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& interval_ != null
&& interval_ != com.google.monitoring.v3.TimeInterval.getDefaultInstance()) {
getIntervalBuilder().mergeFrom(value);
} else {
interval_ = value;
}
} else {
intervalBuilder_.mergeFrom(value);
}
if (interval_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The time interval to which the data point applies. For `GAUGE` metrics,
* the start time is optional, but if it is supplied, it must equal the
* end time. For `DELTA` metrics, the start
* and end time should specify a non-zero interval, with subsequent points
* specifying contiguous and non-overlapping intervals. For `CUMULATIVE`
* metrics, the start and end time should specify a non-zero interval, with
* subsequent points specifying the same start time and increasing end times,
* until an event resets the cumulative value to zero and sets a new start
* time for the following points.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval interval = 1;</code>
*/
public Builder clearInterval() {
bitField0_ = (bitField0_ & ~0x00000001);
interval_ = null;
if (intervalBuilder_ != null) {
intervalBuilder_.dispose();
intervalBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The time interval to which the data point applies. For `GAUGE` metrics,
* the start time is optional, but if it is supplied, it must equal the
* end time. For `DELTA` metrics, the start
* and end time should specify a non-zero interval, with subsequent points
* specifying contiguous and non-overlapping intervals. For `CUMULATIVE`
* metrics, the start and end time should specify a non-zero interval, with
* subsequent points specifying the same start time and increasing end times,
* until an event resets the cumulative value to zero and sets a new start
* time for the following points.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval interval = 1;</code>
*/
public com.google.monitoring.v3.TimeInterval.Builder getIntervalBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getIntervalFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The time interval to which the data point applies. For `GAUGE` metrics,
* the start time is optional, but if it is supplied, it must equal the
* end time. For `DELTA` metrics, the start
* and end time should specify a non-zero interval, with subsequent points
* specifying contiguous and non-overlapping intervals. For `CUMULATIVE`
* metrics, the start and end time should specify a non-zero interval, with
* subsequent points specifying the same start time and increasing end times,
* until an event resets the cumulative value to zero and sets a new start
* time for the following points.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval interval = 1;</code>
*/
public com.google.monitoring.v3.TimeIntervalOrBuilder getIntervalOrBuilder() {
if (intervalBuilder_ != null) {
return intervalBuilder_.getMessageOrBuilder();
} else {
return interval_ == null
? com.google.monitoring.v3.TimeInterval.getDefaultInstance()
: interval_;
}
}
/**
*
*
* <pre>
* The time interval to which the data point applies. For `GAUGE` metrics,
* the start time is optional, but if it is supplied, it must equal the
* end time. For `DELTA` metrics, the start
* and end time should specify a non-zero interval, with subsequent points
* specifying contiguous and non-overlapping intervals. For `CUMULATIVE`
* metrics, the start and end time should specify a non-zero interval, with
* subsequent points specifying the same start time and increasing end times,
* until an event resets the cumulative value to zero and sets a new start
* time for the following points.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval interval = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.TimeInterval,
com.google.monitoring.v3.TimeInterval.Builder,
com.google.monitoring.v3.TimeIntervalOrBuilder>
getIntervalFieldBuilder() {
if (intervalBuilder_ == null) {
intervalBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.TimeInterval,
com.google.monitoring.v3.TimeInterval.Builder,
com.google.monitoring.v3.TimeIntervalOrBuilder>(
getInterval(), getParentForChildren(), isClean());
interval_ = null;
}
return intervalBuilder_;
}
private com.google.monitoring.v3.TypedValue value_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.TypedValue,
com.google.monitoring.v3.TypedValue.Builder,
com.google.monitoring.v3.TypedValueOrBuilder>
valueBuilder_;
/**
*
*
* <pre>
* The value of the data point.
* </pre>
*
* <code>.google.monitoring.v3.TypedValue value = 2;</code>
*
* @return Whether the value field is set.
*/
public boolean hasValue() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The value of the data point.
* </pre>
*
* <code>.google.monitoring.v3.TypedValue value = 2;</code>
*
* @return The value.
*/
public com.google.monitoring.v3.TypedValue getValue() {
if (valueBuilder_ == null) {
return value_ == null ? com.google.monitoring.v3.TypedValue.getDefaultInstance() : value_;
} else {
return valueBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The value of the data point.
* </pre>
*
* <code>.google.monitoring.v3.TypedValue value = 2;</code>
*/
public Builder setValue(com.google.monitoring.v3.TypedValue value) {
if (valueBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
value_ = value;
} else {
valueBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The value of the data point.
* </pre>
*
* <code>.google.monitoring.v3.TypedValue value = 2;</code>
*/
public Builder setValue(com.google.monitoring.v3.TypedValue.Builder builderForValue) {
if (valueBuilder_ == null) {
value_ = builderForValue.build();
} else {
valueBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The value of the data point.
* </pre>
*
* <code>.google.monitoring.v3.TypedValue value = 2;</code>
*/
public Builder mergeValue(com.google.monitoring.v3.TypedValue value) {
if (valueBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& value_ != null
&& value_ != com.google.monitoring.v3.TypedValue.getDefaultInstance()) {
getValueBuilder().mergeFrom(value);
} else {
value_ = value;
}
} else {
valueBuilder_.mergeFrom(value);
}
if (value_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The value of the data point.
* </pre>
*
* <code>.google.monitoring.v3.TypedValue value = 2;</code>
*/
public Builder clearValue() {
bitField0_ = (bitField0_ & ~0x00000002);
value_ = null;
if (valueBuilder_ != null) {
valueBuilder_.dispose();
valueBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The value of the data point.
* </pre>
*
* <code>.google.monitoring.v3.TypedValue value = 2;</code>
*/
public com.google.monitoring.v3.TypedValue.Builder getValueBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getValueFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The value of the data point.
* </pre>
*
* <code>.google.monitoring.v3.TypedValue value = 2;</code>
*/
public com.google.monitoring.v3.TypedValueOrBuilder getValueOrBuilder() {
if (valueBuilder_ != null) {
return valueBuilder_.getMessageOrBuilder();
} else {
return value_ == null ? com.google.monitoring.v3.TypedValue.getDefaultInstance() : value_;
}
}
/**
*
*
* <pre>
* The value of the data point.
* </pre>
*
* <code>.google.monitoring.v3.TypedValue value = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.TypedValue,
com.google.monitoring.v3.TypedValue.Builder,
com.google.monitoring.v3.TypedValueOrBuilder>
getValueFieldBuilder() {
if (valueBuilder_ == null) {
valueBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.TypedValue,
com.google.monitoring.v3.TypedValue.Builder,
com.google.monitoring.v3.TypedValueOrBuilder>(
getValue(), getParentForChildren(), isClean());
value_ = null;
}
return valueBuilder_;
}
@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.monitoring.v3.Point)
}
// @@protoc_insertion_point(class_scope:google.monitoring.v3.Point)
private static final com.google.monitoring.v3.Point DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.monitoring.v3.Point();
}
public static com.google.monitoring.v3.Point getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<Point> PARSER =
new com.google.protobuf.AbstractParser<Point>() {
@java.lang.Override
public Point 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<Point> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Point> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.monitoring.v3.Point getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
google/closure-compiler | 35,937 | test/com/google/javascript/jscomp/TypeCheckAbstractClassesAndMethodsTest.java | /*
* Copyright 2006 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static com.google.javascript.jscomp.TypeCheckTestCase.TypeTestBuilder.newTest;
import com.google.javascript.jscomp.testing.TestExternsBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests {@link TypeCheck}. */
@RunWith(JUnit4.class)
public final class TypeCheckAbstractClassesAndMethodsTest {
@Test
public void testAbstractMethodInAbstractClass() {
newTest()
.addSource(
"""
/** @abstract @constructor */ var C = function() {};
/** @abstract */ C.prototype.foo = function() {};
""")
.run();
}
@Test
public void testAbstractMethodInAbstractEs6Class() {
newTest()
.addSource(
"""
/** @abstract */ class C {
/** @abstract */ foo() {}
}
""")
.run();
}
@Test
public void testAbstractMethodInConcreteClass() {
newTest()
.addSource(
"""
/** @constructor */ var C = function() {};
/** @abstract */ C.prototype.foo = function() {};
""")
.addDiagnostic(
"""
Abstract methods can only appear in abstract classes. Please declare the class as @abstract
""")
.run();
}
@Test
public void testAbstractMethodInConcreteEs6Class() {
newTest()
.addSource(
"""
class C {
/** @abstract */ foo() {}
}
""")
.addDiagnostic(
"""
Abstract methods can only appear in abstract classes. Please declare the class as @abstract
""")
.run();
}
@Test
public void testAbstractMethodInConcreteClassExtendingAbstractClass() {
newTest()
.addSource(
"""
/** @abstract @constructor */ var A = function() {};
/** @constructor @extends {A} */ var B = function() {};
/** @abstract */ B.prototype.foo = function() {};
""")
.addDiagnostic(
"""
Abstract methods can only appear in abstract classes. Please declare the class as @abstract
""")
.run();
}
@Test
public void testAbstractMethodInConcreteEs6ClassExtendingAbstractEs6Class() {
newTest()
.addSource(
"""
/** @abstract */ class A {}
/** @extends {A} */ class B {
/** @abstract */ foo() {}
}
""")
.addDiagnostic(
"Abstract methods can only appear in abstract classes. Please declare the class as "
+ "@abstract")
.run();
}
@Test
public void testConcreteMethodOverridingAbstractMethod() {
newTest()
.addSource(
"""
/** @abstract @constructor */ var A = function() {};
/** @abstract */ A.prototype.foo = function() {};
/** @constructor @extends {A} */ var B = function() {};
/** @override */ B.prototype.foo = function() {};
""")
.run();
}
@Test
public void testConcreteMethodOverridingAbstractMethodInEs6() {
newTest()
.addSource(
"""
/** @abstract */ class A {
/** @abstract*/ foo() {}
}
/** @extends {A} */ class B {
/** @override */ foo() {}
}
""")
.run();
}
@Test
public void testConcreteMethodInAbstractClass1() {
newTest()
.addSource(
"""
/** @abstract @constructor */ var A = function() {};
A.prototype.foo = function() {};
/** @constructor @extends {A} */ var B = function() {};
""")
.run();
}
@Test
public void testConcreteMethodInAbstractEs6Class1() {
newTest()
.addSource(
"""
/** @abstract */ class A {
foo() {}
}
class B extends A {}
""")
.includeDefaultExterns()
.run();
}
@Test
public void testConcreteMethodInAbstractClass2() {
// Currently goog.abstractMethod are not considered abstract, so no warning is given when a
// concrete subclass fails to implement it.
newTest()
.addSource(
CompilerTypeTestCase.CLOSURE_DEFS
+ """
/** @abstract @constructor */ var A = function() {};
A.prototype.foo = goog.abstractMethod;
/** @constructor @extends {A} */ var B = function() {};
""")
.run();
}
@Test
public void testAbstractMethodInInterface() {
// TODO(moz): There's no need to tag methods with @abstract in interfaces, maybe give a warning
// on this.
newTest()
.addSource(
"""
/** @interface */ var I = function() {};
/** @abstract */ I.prototype.foo = function() {};
""")
.run();
}
@Test
public void testAbstractMethodInEs6Interface() {
// TODO(moz): There's no need to tag methods with @abstract in interfaces, maybe give a warning
// on this.
newTest()
.addSource(
"""
/** @interface */ class I {
/** @abstract */ foo() {}
};
""")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodNotImplemented1() {
newTest()
.addSource(
"""
/** @abstract @constructor */ var A = function() {};
/** @abstract */ A.prototype.foo = function() {};
/** @constructor @extends {A} */ var B = function() {};
""")
.addDiagnostic("property foo on abstract class A is not implemented by type B")
.run();
}
@Test
public void testAbstractMethodInEs6NotImplemented1() {
newTest()
.addSource(
"""
/** @abstract */ class A {
/** @abstract */ foo() {}
}
class B extends A {}
""")
.addDiagnostic("property foo on abstract class A is not implemented by type B")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodNotImplemented2() {
newTest()
.addSource(
"""
/** @abstract @constructor */ var A = function() {};
/** @abstract */ A.prototype.foo = function() {};
/** @abstract */ A.prototype.bar = function() {};
/** @constructor @extends {A} */ var B = function() {};
/** @override */ B.prototype.foo = function() {};
""")
.addDiagnostic("property bar on abstract class A is not implemented by type B")
.run();
}
@Test
public void testAbstractMethodInEs6NotImplemented2() {
newTest()
.addSource(
"""
/** @abstract */ class A {
/** @abstract */ foo() {}
/** @abstract */ bar() {}
}
class B extends A {
/** @override */ foo() {}
}
""")
.addDiagnostic("property bar on abstract class A is not implemented by type B")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodNotImplemented3() {
newTest()
.addSource(
"""
/** @abstract @constructor */ var A = function() {};
/** @abstract */ A.prototype.foo = function() {};
/** @abstract @constructor @extends {A} */ var B = function() {};
/** @abstract @override */ B.prototype.foo = function() {};
/** @constructor @extends {B} */ var C = function() {};
""")
.addDiagnostic("property foo on abstract class B is not implemented by type C")
.run();
}
@Test
public void testAbstractMethodInEs6NotImplemented3() {
newTest()
.addSource(
"""
/** @abstract */ class A {
/** @abstract */ foo() {}
}
/** @abstract */ class B extends A {
/** @abstract @override */ foo() {}
}
class C extends B {}
""")
.addDiagnostic("property foo on abstract class B is not implemented by type C")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodNotImplemented4() {
newTest()
.addSource(
"""
/** @abstract @constructor */ var A = function() {};
/** @abstract */ A.prototype.foo = function() {};
/** @abstract @constructor @extends {A} */ var B = function() {};
/** @constructor @extends {B} */ var C = function() {};
""")
.addDiagnostic("property foo on abstract class A is not implemented by type C")
.run();
}
@Test
public void testAbstractMethodInEs6NotImplemented4() {
newTest()
.addSource(
"""
/** @abstract */ class A {
/** @abstract */ foo() {}
}
/** @abstract */ class B extends A {}
class C extends B {}
""")
.addDiagnostic("property foo on abstract class A is not implemented by type C")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodNotImplemented5() {
newTest()
.addSource(
"""
/** @interface */ var I = function() {};
I.prototype.foo = function() {};
/** @abstract @constructor @implements {I} */ var A = function() {};
/** @abstract @override */ A.prototype.foo = function() {};
/** @constructor @extends {A} */ var B = function() {};
""")
.addDiagnostic("property foo on abstract class A is not implemented by type B")
.run();
}
@Test
public void testAbstractMethodInEs6NotImplemented5() {
newTest()
.addSource(
"""
/** @interface */ class I {
foo() {}
bar() {} // Not overridden by abstract class
}
/** @abstract @implements {I} */ class A {
/** @abstract @override */ foo() {}
}
class B extends A {}
""")
.addDiagnostic("property bar on interface I is not implemented by type B")
.addDiagnostic("property foo on abstract class A is not implemented by type B")
.run();
}
@Test
public void testAbstractMethodNotImplemented6() {
newTest()
.addSource(
"""
/** @abstract @constructor */ var A = function() {};
/** @abstract */ A.prototype.foo = function() {};
/** @constructor @extends {A} */ var B = function() {};
/** @override @type {number} */ B.prototype.foo;
""")
.addDiagnostic("property foo on abstract class A is not implemented by type B")
.run();
}
@Test
public void testAbstractMethodImplemented1() {
newTest()
.addSource(
"""
/** @abstract @constructor */ var A = function() {};
/** @abstract */ A.prototype.foo = function() {};
/** @abstract */ A.prototype.bar = function() {};
/** @constructor @extends {A} */ var B = function() {};
/** @override */ B.prototype.foo = function() {};
/** @override */ B.prototype.bar = function() {};
/** @constructor @extends {B} */ var C = function() {};
""")
.run();
}
@Test
public void testAbstractMethodInEs6Implemented1() {
newTest()
.addSource(
"""
/** @abstract */ class A {
/** @abstract */ foo() {}
/** @abstract */ bar() {}
}
class B extends A {
/** @override */ foo() {}
/** @override */ bar() {}
}
class C extends B {}
""")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodImplemented2() {
newTest()
.addSource(
"""
/** @abstract @constructor */ var A = function() {};
/** @abstract */ A.prototype.foo = function() {};
/** @abstract */ A.prototype.bar = function() {};
/** @abstract @constructor @extends {A} */ var B = function() {};
/** @override */ B.prototype.foo = function() {};
/** @constructor @extends {B} */ var C = function() {};
/** @override */ C.prototype.bar = function() {};
""")
.run();
}
@Test
public void testAbstractMethodInEs6Implemented2() {
newTest()
.addSource(
"""
/** @abstract */ class A {
/** @abstract */ foo() {}
/** @abstract */ bar() {}
}
/** @abstract */ class B extends A {
/** @override */ foo() {}
}
class C extends B {
/** @override */ bar() {}
}
""")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodInEs6NotImplemented_symbolProp() {
newTest()
.addSource(
"""
/** @abstract */ class A {
/** @abstract */ [Symbol.iterator]() {}
}
class B extends A {}
""")
.addDiagnostic("property Symbol.iterator on abstract class A is not implemented by type B")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodHandling1() {
newTest()
.addSource(
"""
/** @type {Function} */ var abstractFn = function() {};
abstractFn(1);
""")
.run();
}
@Test
public void testAbstractMethodHandling2() {
newTest()
.addSource(
"""
var abstractFn = function() {};
abstractFn(1);
""")
.addDiagnostic(
"""
Function abstractFn: called with 1 argument(s). Function requires at least 0 argument(s) and no more than 0 argument(s).
""")
.run();
}
@Test
public void testAbstractMethodHandling3() {
newTest()
.addSource(
"""
var goog = {};
/** @type {Function} */ goog.abstractFn = function() {};
goog.abstractFn(1);
""")
.run();
}
@Test
public void testAbstractMethodHandling4() {
newTest()
.addSource(
"""
var goog = {};
goog.abstractFn = function() {};
goog.abstractFn(1);
""")
.addDiagnostic(
"""
Function goog.abstractFn: called with 1 argument(s). \
Function requires at least 0 argument(s) and no more than 0 argument(s).\
""")
.run();
}
@Test
public void testAbstractFunctionHandling() {
newTest()
.addSource(
"""
/** @type {!Function} */ var abstractFn = function() {};
// the type of 'f' will become 'Function'
/** @param {number} x */ var f = abstractFn;
f('x');
""")
.run();
}
@Test
public void testAbstractMethodHandling6() {
newTest()
.addSource(
"""
var goog = {};
/** @type {Function} */ goog.abstractFn = function() {};
/** @param {number} x */ goog.f = abstractFn;
goog.f('x');
""")
.addDiagnostic(
"""
actual parameter 1 of goog.f does not match formal parameter
found : string
required: number
""")
.run();
}
// https://github.com/google/closure-compiler/issues/2458
@Test
public void testAbstractSpread() {
newTest()
.addSource(
"""
/** @abstract */
class X {
/** @abstract */
m1() {}
m2() {
return () => this.m1(...[]);
}
}
""")
.includeDefaultExterns()
.run();
}
@Test
public void testOverriddenReturnOnAbstractClass() {
newTest()
.addSource(
"""
/** @interface */ function IFoo() {}
/** @return {*} */ IFoo.prototype.foo = function() {}
/** @constructor */ function Foo() {}
/** @return {string} */ Foo.prototype.foo = function() {}
/** @constructor @extends {Foo} */ function Bar() {}
/**
* @constructor @abstract
* @extends {Bar} @implements {IFoo}
*/
function Baz() {}
// Even there is a closer definition in IFoo, Foo should be still the source of truth.
/** @return {string} */
function test() { return (/** @type {Baz} */ (null)).foo(); }
""")
.run();
}
@Test
public void testOverriddenReturnDoesntMatchOnAbstractClass() {
newTest()
.addSource(
"""
/** @interface */ function IFoo() {}
/** @return {number} */ IFoo.prototype.foo = function() {}
/** @constructor */ function Foo() {}
/** @return {string} */ Foo.prototype.foo = function() {}
/** @constructor @extends {Foo} */ function Bar() {}
/**
* @constructor @abstract
* @extends {Bar} @implements {IFoo}
*/
function Baz() {}
/** @return {string} */
function test() { return (/** @type {Baz} */ (null)).foo(); }
""")
.addDiagnostic(
"""
mismatch of the foo property on type Baz and the type of the property it overrides from interface IFoo
original: function(this:IFoo): number
override: function(this:Foo): string
""")
.run();
}
@Test
public void testOverriddenReturnDoesntMatchOnAbstractClass_symbolProp() {
newTest()
.addSource(
"""
/** @interface */ function IFoo() {}
/** @return {number} */ IFoo.prototype[Symbol.iterator] = function() {}
/** @constructor */ function Foo() {}
/** @return {string} */ Foo.prototype[Symbol.iterator] = function() {}
/** @constructor @extends {Foo} */ function Bar() {}
/**
* @constructor
* @abstract
* @extends {Bar}
* @implements {IFoo}
*/
function Baz() {}
/** @return {string} */
function test() { return (/** @type {Baz} */ (null))[Symbol.iterator](); }
""")
.addDiagnostic(
"""
mismatch of the Symbol.iterator property on type Baz and the type of the property it overrides from interface IFoo
original: function(this:IFoo): number
override: function(this:Foo): string
""")
.run();
}
@Test
public void testAbstractMethodCall1() {
// Converted from Closure style "goog.base" super call
newTest()
.addSource(
"""
/** @constructor @abstract */ var A = function() {};
/** @abstract */ A.prototype.foo = function() {};
/** @constructor @extends {A} */ var B = function() {};
B.superClass_ = A.prototype
/** @override */ B.prototype.foo = function() { B.superClass_.foo.call(this); };
""")
.addDiagnostic("Abstract super method A.prototype.foo cannot be dereferenced")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall2() {
// Converted from Closure style "goog.base" super call, with namespace
newTest()
.addSource(
"""
/** @const */ var ns = {};
/** @constructor @abstract */ ns.A = function() {};
/** @abstract */ ns.A.prototype.foo = function() {};
/** @constructor @extends {ns.A} */ ns.B = function() {};
ns.B.superClass_ = ns.A.prototype
/** @override */ ns.B.prototype.foo = function() {
ns.B.superClass_.foo.call(this);
};
""")
.addDiagnostic("Abstract super method ns.A.prototype.foo cannot be dereferenced")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall3() {
// Converted from ES6 super call
newTest()
.addSource(
"""
/** @constructor @abstract */ var A = function() {};
/** @abstract */ A.prototype.foo = function() {};
/** @constructor @extends {A} */ var B = function() {};
/** @override */ B.prototype.foo = function() { A.prototype.foo.call(this); };
""")
.addDiagnostic("Abstract super method A.prototype.foo cannot be dereferenced")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall4() {
newTest()
.addSource(
"""
/** @const */ var ns = {};
/** @constructor @abstract */ ns.A = function() {};
ns.A.prototype.foo = function() {};
/** @constructor @extends {ns.A} */ ns.B = function() {};
ns.B.superClass_ = ns.A.prototype
/** @override */ ns.B.prototype.foo = function() {
ns.B.superClass_.foo.call(this);
};
""")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall5() {
newTest()
.addSource(
"""
/** @constructor @abstract */ var A = function() {};
A.prototype.foo = function() {};
/** @constructor @extends {A} */ var B = function() {};
/** @override */ B.prototype.foo = function() { A.prototype.foo.call(this); };
""")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall6() {
newTest()
.addSource(
"""
/** @const */ var ns = {};
/** @constructor @abstract */ ns.A = function() {};
ns.A.prototype.foo = function() {};
ns.A.prototype.foo.bar = function() {};
/** @constructor @extends {ns.A} */ ns.B = function() {};
ns.B.superClass_ = ns.A.prototype
/** @override */ ns.B.prototype.foo = function() {
ns.B.superClass_.foo.bar.call(this);
};
""")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall7() {
newTest()
.addSource(
"""
/** @constructor @abstract */ var A = function() {};
A.prototype.foo = function() {};
A.prototype.foo.bar = function() {};
/** @constructor @extends {A} */ var B = function() {};
/** @override */ B.prototype.foo = function() { A.prototype.foo.bar.call(this); };
""")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall8() {
newTest()
.addSource(
"""
/** @constructor @abstract */ var A = function() {};
A.prototype.foo = function() {};
/** @constructor @extends {A} */ var B = function() {};
/** @override */ B.prototype.foo = function() { A.prototype.foo['call'](this); };
""")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall9() {
newTest()
.addSource(
"""
/** @struct @constructor */ var A = function() {};
A.prototype.foo = function() {};
/** @struct @constructor @extends {A} */ var B = function() {};
/** @override */ B.prototype.foo = function() {
(function() {
return A.prototype.foo.call($jscomp$this);
})();
};
""")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall10() {
newTest()
.addSource(
"""
/** @constructor @abstract */ var A = function() {};
/** @abstract */ A.prototype.foo = function() {};
A.prototype.foo.call(new Subtype);
""")
.addDiagnostic("Abstract super method A.prototype.foo cannot be dereferenced")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall11() {
newTest()
.addSource(
"""
/** @constructor @abstract */ function A() {};
/** @abstract */ A.prototype.foo = function() {};
/** @constructor @extends {A} */ function B() {};
/** @override */ B.prototype.foo = function() {};
var abstractMethod = A.prototype.foo;
abstractMethod.call(new B);
""")
.addDiagnostic("Abstract super method A.prototype.foo cannot be dereferenced")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall12() {
newTest()
.addSource(
"""
/** @constructor @abstract */ var A = function() {};
/** @abstract */ A.prototype.foo = function() {};
/** @constructor @extends {A} */ var B = function() {};
B.superClass_ = A.prototype
/** @override */ B.prototype.foo = function() { B.superClass_.foo.apply(this); };
""")
.addDiagnostic("Abstract super method A.prototype.foo cannot be dereferenced")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall13() {
// Calling abstract @constructor is allowed
newTest()
.addSource(
"""
/** @constructor @abstract */ var A = function() {};
/** @constructor @extends {A} */ var B = function() { A.call(this); };
""")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall_Indirect1() {
newTest()
.addSource(
"""
/** @constructor @abstract */ function A() {};
/** @abstract */ A.prototype.foo = function() {};
/** @constructor @extends {A} */ function B() {};
/** @override */ B.prototype.foo = function() {};
var abstractMethod = A.prototype.foo;
(0, abstractMethod).call(new B);
""")
.addDiagnostic("Abstract super method A.prototype.foo cannot be dereferenced")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall_Indirect2() {
newTest()
.addSource(
"""
/** @constructor @abstract */ function A() {};
/** @abstract */ A.prototype.foo = function() {};
/** @constructor @extends {A} */ function B() {};
/** @override */ B.prototype.foo = function() {};
var abstractMethod = A.prototype.foo;
(abstractMethod = abstractMethod).call(new B);
""")
.addDiagnostic("Abstract super method A.prototype.foo cannot be dereferenced")
.includeDefaultExterns()
.run();
}
@Test
public void testDefiningPropOnAbstractMethodForbidden() {
newTest()
.addSource(
"""
/** @constructor @abstract */ function A() {};
/** @abstract */ A.prototype.foo = function() {};
A.prototype.foo.callFirst = true;
""")
.addDiagnostic("Abstract super method A.prototype.foo cannot be dereferenced")
.includeDefaultExterns()
.run();
}
@Test
public void testPassingAbstractMethodAsArgForbidden() {
newTest()
.addExterns("function externsFn(callback) {}")
.addSource(
"""
/** @constructor @abstract */ function A() {};
/** @abstract */ A.prototype.foo = function() {};
externsFn(A.prototype.foo);
""")
.addDiagnostic("Abstract super method A.prototype.foo cannot be dereferenced")
.run();
}
@Test
public void testAbstractMethodCall_Es6Class() {
newTest()
.addSource(
"""
/** @abstract */
class Base {
/** @abstract */
foo() {}
bar() {
this.foo();
}
}
class Sub extends Base {
/** @override */
foo() {}
/** @override */
bar() {
this.foo();
}
}
""")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall_Es6Class_prototype() {
newTest()
.addSource(
"""
/** @abstract */
class Base {
/** @abstract */
foo() {}
}
class Sub extends Base {
/** @override */
foo() {}
bar() {
Sub.prototype.foo();
}
}
""")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall_Es6Class_prototype_warning() {
newTest()
.addSource(
"""
/** @abstract */
class Base {
/** @abstract */
foo() {}
}
class Sub extends Base {
/** @override */
foo() {}
bar() {
Base.prototype.foo();
}
}
""")
.addDiagnostic("Abstract super method Base.prototype.foo cannot be dereferenced")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall_Es6Class_abstractSubclass_warns() {
newTest()
.addSource(
"""
/** @abstract */
class Base {
/** @abstract */
foo() {}
}
/** @abstract */
class Sub extends Base {
bar() {
Sub.prototype.foo();
}
}
""")
.addDiagnostic("Abstract super method Base.prototype.foo cannot be dereferenced")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall_Es6Class_onAbstractSubclassPrototype_warns() {
newTest()
.addSource(
"""
/** @abstract */
class Base {
/** @abstract */
foo() {}
}
/** @abstract */
class Sub extends Base {
bar() {
Base.prototype.foo();
}
}
""")
.addDiagnostic("Abstract super method Base.prototype.foo cannot be dereferenced")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall_Es6Class_concreteSubclassMissingImplementation_warns() {
newTest()
.addSource(
"""
/** @abstract */
class Base {
/** @abstract */
foo() {}
}
class Sub extends Base {
bar() {
Sub.prototype.foo();
}
}
""")
.includeDefaultExterns()
.addDiagnostic("property foo on abstract class Base is not implemented by type Sub")
.addDiagnostic("Abstract super method Base.prototype.foo cannot be dereferenced")
.run();
}
@Test
public void testAbstractMethodCall_Es6Class_concreteSubclassWithImplementation_noWarning() {
newTest()
.addSource(
"""
/** @abstract */
class Base {
/** @abstract */
foo() {}
}
class Sub extends Base {
/** @override */
foo() {}
bar() {
Sub.prototype.foo();
}
}
""")
.includeDefaultExterns()
.run();
}
@Test
public void testAbstractMethodCall_NamespacedEs6Class_prototype_warns() {
newTest()
.addSource(
"""
const ns = {};
/** @abstract */
ns.Base = class {
/** @abstract */
foo() {}
}
class Sub extends ns.Base {
/** @override */
foo() {}
bar() {
ns.Base.prototype.foo();
}
}
""")
.addDiagnostic("Abstract super method ns.Base.prototype.foo cannot be dereferenced")
.includeDefaultExterns()
.run();
}
@Test
public void testNonAbstractMethodCall_Es6Class_prototype() {
newTest()
.addSource(
"""
/** @abstract */
class Base {
/** @abstract */
foo() {}
bar() {}
}
class Sub extends Base {
/** @override */
foo() {}
/** @override */
bar() {
Base.prototype.bar();
}
}
""")
.includeDefaultExterns()
.run();
}
// GitHub issue #2262: https://github.com/google/closure-compiler/issues/2262
@Test
public void testAbstractMethodCall_Es6ClassWithSpread() {
newTest()
.addExterns(new TestExternsBuilder().addObject().addArray().addArguments().build())
.addSource(
"""
/** @abstract */
class Base {
/** @abstract */
foo() {}
}
class Sub extends Base {
/** @override */
foo() {}
/** @param {!Array} arr */
bar(arr) {
this.foo.apply(this, [].concat(arr));
}
}
""")
.run();
}
@Test
public void testImplementedInterfacePropertiesShouldFailOnConflictForAbstractClasses() {
// TODO(b/132718172): Provide an error message.
newTest()
.addSource(
"""
/** @interface */function Int0() {};
/** @interface */function Int1() {};
/** @type {number} */
Int0.prototype.foo;
/** @type {string} */
Int1.prototype.foo;
/** @constructor @abstract @implements {Int0} @implements {Int1} */
function Foo() {};
""")
.run();
}
@Test
public void testImplementedInterfacePropertiesShouldFailOnConflictForAbstractClasses2() {
// TODO(b/132718172): Provide an error message.
newTest()
.addSource(
"""
/** @interface */function Int0() {};
/** @interface */function Int1() {};
/** @type {number} */
Int0.prototype.foo;
/** @type {string} */
Int1.prototype.foo;
/** @constructor @abstract @implements {Int0} */
function Foo() {};
/** @constructor @abstract @extends {Foo} @implements {Int1} */
function Zoo() {};
""")
.run();
}
}
|
openjdk/jdk8 | 36,676 | jdk/src/share/classes/javax/swing/plaf/metal/MetalRootPaneUI.java | /*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.metal;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;
import java.awt.*;
import java.io.*;
import java.security.*;
/**
* Provides the metal look and feel implementation of <code>RootPaneUI</code>.
* <p>
* <code>MetalRootPaneUI</code> provides support for the
* <code>windowDecorationStyle</code> property of <code>JRootPane</code>.
* <code>MetalRootPaneUI</code> does this by way of installing a custom
* <code>LayoutManager</code>, a private <code>Component</code> to render
* the appropriate widgets, and a private <code>Border</code>. The
* <code>LayoutManager</code> is always installed, regardless of the value of
* the <code>windowDecorationStyle</code> property, but the
* <code>Border</code> and <code>Component</code> are only installed/added if
* the <code>windowDecorationStyle</code> is other than
* <code>JRootPane.NONE</code>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans™
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @author Terry Kellerman
* @since 1.4
*/
public class MetalRootPaneUI extends BasicRootPaneUI
{
/**
* Keys to lookup borders in defaults table.
*/
private static final String[] borderKeys = new String[] {
null, "RootPane.frameBorder", "RootPane.plainDialogBorder",
"RootPane.informationDialogBorder",
"RootPane.errorDialogBorder", "RootPane.colorChooserDialogBorder",
"RootPane.fileChooserDialogBorder", "RootPane.questionDialogBorder",
"RootPane.warningDialogBorder"
};
/**
* The amount of space (in pixels) that the cursor is changed on.
*/
private static final int CORNER_DRAG_WIDTH = 16;
/**
* Region from edges that dragging is active from.
*/
private static final int BORDER_DRAG_THICKNESS = 5;
/**
* Window the <code>JRootPane</code> is in.
*/
private Window window;
/**
* <code>JComponent</code> providing window decorations. This will be
* null if not providing window decorations.
*/
private JComponent titlePane;
/**
* <code>MouseInputListener</code> that is added to the parent
* <code>Window</code> the <code>JRootPane</code> is contained in.
*/
private MouseInputListener mouseInputListener;
/**
* The <code>LayoutManager</code> that is set on the
* <code>JRootPane</code>.
*/
private LayoutManager layoutManager;
/**
* <code>LayoutManager</code> of the <code>JRootPane</code> before we
* replaced it.
*/
private LayoutManager savedOldLayout;
/**
* <code>JRootPane</code> providing the look and feel for.
*/
private JRootPane root;
/**
* <code>Cursor</code> used to track the cursor set by the user.
* This is initially <code>Cursor.DEFAULT_CURSOR</code>.
*/
private Cursor lastCursor =
Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
/**
* Creates a UI for a <code>JRootPane</code>.
*
* @param c the JRootPane the RootPaneUI will be created for
* @return the RootPaneUI implementation for the passed in JRootPane
*/
public static ComponentUI createUI(JComponent c) {
return new MetalRootPaneUI();
}
/**
* Invokes supers implementation of <code>installUI</code> to install
* the necessary state onto the passed in <code>JRootPane</code>
* to render the metal look and feel implementation of
* <code>RootPaneUI</code>. If
* the <code>windowDecorationStyle</code> property of the
* <code>JRootPane</code> is other than <code>JRootPane.NONE</code>,
* this will add a custom <code>Component</code> to render the widgets to
* <code>JRootPane</code>, as well as installing a custom
* <code>Border</code> and <code>LayoutManager</code> on the
* <code>JRootPane</code>.
*
* @param c the JRootPane to install state onto
*/
public void installUI(JComponent c) {
super.installUI(c);
root = (JRootPane)c;
int style = root.getWindowDecorationStyle();
if (style != JRootPane.NONE) {
installClientDecorations(root);
}
}
/**
* Invokes supers implementation to uninstall any of its state. This will
* also reset the <code>LayoutManager</code> of the <code>JRootPane</code>.
* If a <code>Component</code> has been added to the <code>JRootPane</code>
* to render the window decoration style, this method will remove it.
* Similarly, this will revert the Border and LayoutManager of the
* <code>JRootPane</code> to what it was before <code>installUI</code>
* was invoked.
*
* @param c the JRootPane to uninstall state from
*/
public void uninstallUI(JComponent c) {
super.uninstallUI(c);
uninstallClientDecorations(root);
layoutManager = null;
mouseInputListener = null;
root = null;
}
/**
* Installs the appropriate <code>Border</code> onto the
* <code>JRootPane</code>.
*/
void installBorder(JRootPane root) {
int style = root.getWindowDecorationStyle();
if (style == JRootPane.NONE) {
LookAndFeel.uninstallBorder(root);
}
else {
LookAndFeel.installBorder(root, borderKeys[style]);
}
}
/**
* Removes any border that may have been installed.
*/
private void uninstallBorder(JRootPane root) {
LookAndFeel.uninstallBorder(root);
}
/**
* Installs the necessary Listeners on the parent <code>Window</code>,
* if there is one.
* <p>
* This takes the parent so that cleanup can be done from
* <code>removeNotify</code>, at which point the parent hasn't been
* reset yet.
*
* @param parent The parent of the JRootPane
*/
private void installWindowListeners(JRootPane root, Component parent) {
if (parent instanceof Window) {
window = (Window)parent;
}
else {
window = SwingUtilities.getWindowAncestor(parent);
}
if (window != null) {
if (mouseInputListener == null) {
mouseInputListener = createWindowMouseInputListener(root);
}
window.addMouseListener(mouseInputListener);
window.addMouseMotionListener(mouseInputListener);
}
}
/**
* Uninstalls the necessary Listeners on the <code>Window</code> the
* Listeners were last installed on.
*/
private void uninstallWindowListeners(JRootPane root) {
if (window != null) {
window.removeMouseListener(mouseInputListener);
window.removeMouseMotionListener(mouseInputListener);
}
}
/**
* Installs the appropriate LayoutManager on the <code>JRootPane</code>
* to render the window decorations.
*/
private void installLayout(JRootPane root) {
if (layoutManager == null) {
layoutManager = createLayoutManager();
}
savedOldLayout = root.getLayout();
root.setLayout(layoutManager);
}
/**
* Uninstalls the previously installed <code>LayoutManager</code>.
*/
private void uninstallLayout(JRootPane root) {
if (savedOldLayout != null) {
root.setLayout(savedOldLayout);
savedOldLayout = null;
}
}
/**
* Installs the necessary state onto the JRootPane to render client
* decorations. This is ONLY invoked if the <code>JRootPane</code>
* has a decoration style other than <code>JRootPane.NONE</code>.
*/
private void installClientDecorations(JRootPane root) {
installBorder(root);
JComponent titlePane = createTitlePane(root);
setTitlePane(root, titlePane);
installWindowListeners(root, root.getParent());
installLayout(root);
if (window != null) {
root.revalidate();
root.repaint();
}
}
/**
* Uninstalls any state that <code>installClientDecorations</code> has
* installed.
* <p>
* NOTE: This may be called if you haven't installed client decorations
* yet (ie before <code>installClientDecorations</code> has been invoked).
*/
private void uninstallClientDecorations(JRootPane root) {
uninstallBorder(root);
uninstallWindowListeners(root);
setTitlePane(root, null);
uninstallLayout(root);
// We have to revalidate/repaint root if the style is JRootPane.NONE
// only. When we needs to call revalidate/repaint with other styles
// the installClientDecorations is always called after this method
// imediatly and it will cause the revalidate/repaint at the proper
// time.
int style = root.getWindowDecorationStyle();
if (style == JRootPane.NONE) {
root.repaint();
root.revalidate();
}
// Reset the cursor, as we may have changed it to a resize cursor
if (window != null) {
window.setCursor(Cursor.getPredefinedCursor
(Cursor.DEFAULT_CURSOR));
}
window = null;
}
/**
* Returns the <code>JComponent</code> to render the window decoration
* style.
*/
private JComponent createTitlePane(JRootPane root) {
return new MetalTitlePane(root, this);
}
/**
* Returns a <code>MouseListener</code> that will be added to the
* <code>Window</code> containing the <code>JRootPane</code>.
*/
private MouseInputListener createWindowMouseInputListener(JRootPane root) {
return new MouseInputHandler();
}
/**
* Returns a <code>LayoutManager</code> that will be set on the
* <code>JRootPane</code>.
*/
private LayoutManager createLayoutManager() {
return new MetalRootLayout();
}
/**
* Sets the window title pane -- the JComponent used to provide a plaf a
* way to override the native operating system's window title pane with
* one whose look and feel are controlled by the plaf. The plaf creates
* and sets this value; the default is null, implying a native operating
* system window title pane.
*
* @param content the <code>JComponent</code> to use for the window title pane.
*/
private void setTitlePane(JRootPane root, JComponent titlePane) {
JLayeredPane layeredPane = root.getLayeredPane();
JComponent oldTitlePane = getTitlePane();
if (oldTitlePane != null) {
oldTitlePane.setVisible(false);
layeredPane.remove(oldTitlePane);
}
if (titlePane != null) {
layeredPane.add(titlePane, JLayeredPane.FRAME_CONTENT_LAYER);
titlePane.setVisible(true);
}
this.titlePane = titlePane;
}
/**
* Returns the <code>JComponent</code> rendering the title pane. If this
* returns null, it implies there is no need to render window decorations.
*
* @return the current window title pane, or null
* @see #setTitlePane
*/
private JComponent getTitlePane() {
return titlePane;
}
/**
* Returns the <code>JRootPane</code> we're providing the look and
* feel for.
*/
private JRootPane getRootPane() {
return root;
}
/**
* Invoked when a property changes. <code>MetalRootPaneUI</code> is
* primarily interested in events originating from the
* <code>JRootPane</code> it has been installed on identifying the
* property <code>windowDecorationStyle</code>. If the
* <code>windowDecorationStyle</code> has changed to a value other
* than <code>JRootPane.NONE</code>, this will add a <code>Component</code>
* to the <code>JRootPane</code> to render the window decorations, as well
* as installing a <code>Border</code> on the <code>JRootPane</code>.
* On the other hand, if the <code>windowDecorationStyle</code> has
* changed to <code>JRootPane.NONE</code>, this will remove the
* <code>Component</code> that has been added to the <code>JRootPane</code>
* as well resetting the Border to what it was before
* <code>installUI</code> was invoked.
*
* @param e A PropertyChangeEvent object describing the event source
* and the property that has changed.
*/
public void propertyChange(PropertyChangeEvent e) {
super.propertyChange(e);
String propertyName = e.getPropertyName();
if(propertyName == null) {
return;
}
if(propertyName.equals("windowDecorationStyle")) {
JRootPane root = (JRootPane) e.getSource();
int style = root.getWindowDecorationStyle();
// This is potentially more than needs to be done,
// but it rarely happens and makes the install/uninstall process
// simpler. MetalTitlePane also assumes it will be recreated if
// the decoration style changes.
uninstallClientDecorations(root);
if (style != JRootPane.NONE) {
installClientDecorations(root);
}
}
else if (propertyName.equals("ancestor")) {
uninstallWindowListeners(root);
if (((JRootPane)e.getSource()).getWindowDecorationStyle() !=
JRootPane.NONE) {
installWindowListeners(root, root.getParent());
}
}
return;
}
/**
* A custom layout manager that is responsible for the layout of
* layeredPane, glassPane, menuBar and titlePane, if one has been
* installed.
*/
// NOTE: Ideally this would extends JRootPane.RootLayout, but that
// would force this to be non-static.
private static class MetalRootLayout implements LayoutManager2 {
/**
* Returns the amount of space the layout would like to have.
*
* @param the Container for which this layout manager is being used
* @return a Dimension object containing the layout's preferred size
*/
public Dimension preferredLayoutSize(Container parent) {
Dimension cpd, mbd, tpd;
int cpWidth = 0;
int cpHeight = 0;
int mbWidth = 0;
int mbHeight = 0;
int tpWidth = 0;
int tpHeight = 0;
Insets i = parent.getInsets();
JRootPane root = (JRootPane) parent;
if(root.getContentPane() != null) {
cpd = root.getContentPane().getPreferredSize();
} else {
cpd = root.getSize();
}
if (cpd != null) {
cpWidth = cpd.width;
cpHeight = cpd.height;
}
if(root.getMenuBar() != null) {
mbd = root.getMenuBar().getPreferredSize();
if (mbd != null) {
mbWidth = mbd.width;
mbHeight = mbd.height;
}
}
if (root.getWindowDecorationStyle() != JRootPane.NONE &&
(root.getUI() instanceof MetalRootPaneUI)) {
JComponent titlePane = ((MetalRootPaneUI)root.getUI()).
getTitlePane();
if (titlePane != null) {
tpd = titlePane.getPreferredSize();
if (tpd != null) {
tpWidth = tpd.width;
tpHeight = tpd.height;
}
}
}
return new Dimension(Math.max(Math.max(cpWidth, mbWidth), tpWidth) + i.left + i.right,
cpHeight + mbHeight + tpWidth + i.top + i.bottom);
}
/**
* Returns the minimum amount of space the layout needs.
*
* @param the Container for which this layout manager is being used
* @return a Dimension object containing the layout's minimum size
*/
public Dimension minimumLayoutSize(Container parent) {
Dimension cpd, mbd, tpd;
int cpWidth = 0;
int cpHeight = 0;
int mbWidth = 0;
int mbHeight = 0;
int tpWidth = 0;
int tpHeight = 0;
Insets i = parent.getInsets();
JRootPane root = (JRootPane) parent;
if(root.getContentPane() != null) {
cpd = root.getContentPane().getMinimumSize();
} else {
cpd = root.getSize();
}
if (cpd != null) {
cpWidth = cpd.width;
cpHeight = cpd.height;
}
if(root.getMenuBar() != null) {
mbd = root.getMenuBar().getMinimumSize();
if (mbd != null) {
mbWidth = mbd.width;
mbHeight = mbd.height;
}
}
if (root.getWindowDecorationStyle() != JRootPane.NONE &&
(root.getUI() instanceof MetalRootPaneUI)) {
JComponent titlePane = ((MetalRootPaneUI)root.getUI()).
getTitlePane();
if (titlePane != null) {
tpd = titlePane.getMinimumSize();
if (tpd != null) {
tpWidth = tpd.width;
tpHeight = tpd.height;
}
}
}
return new Dimension(Math.max(Math.max(cpWidth, mbWidth), tpWidth) + i.left + i.right,
cpHeight + mbHeight + tpWidth + i.top + i.bottom);
}
/**
* Returns the maximum amount of space the layout can use.
*
* @param the Container for which this layout manager is being used
* @return a Dimension object containing the layout's maximum size
*/
public Dimension maximumLayoutSize(Container target) {
Dimension cpd, mbd, tpd;
int cpWidth = Integer.MAX_VALUE;
int cpHeight = Integer.MAX_VALUE;
int mbWidth = Integer.MAX_VALUE;
int mbHeight = Integer.MAX_VALUE;
int tpWidth = Integer.MAX_VALUE;
int tpHeight = Integer.MAX_VALUE;
Insets i = target.getInsets();
JRootPane root = (JRootPane) target;
if(root.getContentPane() != null) {
cpd = root.getContentPane().getMaximumSize();
if (cpd != null) {
cpWidth = cpd.width;
cpHeight = cpd.height;
}
}
if(root.getMenuBar() != null) {
mbd = root.getMenuBar().getMaximumSize();
if (mbd != null) {
mbWidth = mbd.width;
mbHeight = mbd.height;
}
}
if (root.getWindowDecorationStyle() != JRootPane.NONE &&
(root.getUI() instanceof MetalRootPaneUI)) {
JComponent titlePane = ((MetalRootPaneUI)root.getUI()).
getTitlePane();
if (titlePane != null)
{
tpd = titlePane.getMaximumSize();
if (tpd != null) {
tpWidth = tpd.width;
tpHeight = tpd.height;
}
}
}
int maxHeight = Math.max(Math.max(cpHeight, mbHeight), tpHeight);
// Only overflows if 3 real non-MAX_VALUE heights, sum to > MAX_VALUE
// Only will happen if sums to more than 2 billion units. Not likely.
if (maxHeight != Integer.MAX_VALUE) {
maxHeight = cpHeight + mbHeight + tpHeight + i.top + i.bottom;
}
int maxWidth = Math.max(Math.max(cpWidth, mbWidth), tpWidth);
// Similar overflow comment as above
if (maxWidth != Integer.MAX_VALUE) {
maxWidth += i.left + i.right;
}
return new Dimension(maxWidth, maxHeight);
}
/**
* Instructs the layout manager to perform the layout for the specified
* container.
*
* @param the Container for which this layout manager is being used
*/
public void layoutContainer(Container parent) {
JRootPane root = (JRootPane) parent;
Rectangle b = root.getBounds();
Insets i = root.getInsets();
int nextY = 0;
int w = b.width - i.right - i.left;
int h = b.height - i.top - i.bottom;
if(root.getLayeredPane() != null) {
root.getLayeredPane().setBounds(i.left, i.top, w, h);
}
if(root.getGlassPane() != null) {
root.getGlassPane().setBounds(i.left, i.top, w, h);
}
// Note: This is laying out the children in the layeredPane,
// technically, these are not our children.
if (root.getWindowDecorationStyle() != JRootPane.NONE &&
(root.getUI() instanceof MetalRootPaneUI)) {
JComponent titlePane = ((MetalRootPaneUI)root.getUI()).
getTitlePane();
if (titlePane != null) {
Dimension tpd = titlePane.getPreferredSize();
if (tpd != null) {
int tpHeight = tpd.height;
titlePane.setBounds(0, 0, w, tpHeight);
nextY += tpHeight;
}
}
}
if(root.getMenuBar() != null) {
Dimension mbd = root.getMenuBar().getPreferredSize();
root.getMenuBar().setBounds(0, nextY, w, mbd.height);
nextY += mbd.height;
}
if(root.getContentPane() != null) {
Dimension cpd = root.getContentPane().getPreferredSize();
root.getContentPane().setBounds(0, nextY, w,
h < nextY ? 0 : h - nextY);
}
}
public void addLayoutComponent(String name, Component comp) {}
public void removeLayoutComponent(Component comp) {}
public void addLayoutComponent(Component comp, Object constraints) {}
public float getLayoutAlignmentX(Container target) { return 0.0f; }
public float getLayoutAlignmentY(Container target) { return 0.0f; }
public void invalidateLayout(Container target) {}
}
/**
* Maps from positions to cursor type. Refer to calculateCorner and
* calculatePosition for details of this.
*/
private static final int[] cursorMapping = new int[]
{ Cursor.NW_RESIZE_CURSOR, Cursor.NW_RESIZE_CURSOR, Cursor.N_RESIZE_CURSOR,
Cursor.NE_RESIZE_CURSOR, Cursor.NE_RESIZE_CURSOR,
Cursor.NW_RESIZE_CURSOR, 0, 0, 0, Cursor.NE_RESIZE_CURSOR,
Cursor.W_RESIZE_CURSOR, 0, 0, 0, Cursor.E_RESIZE_CURSOR,
Cursor.SW_RESIZE_CURSOR, 0, 0, 0, Cursor.SE_RESIZE_CURSOR,
Cursor.SW_RESIZE_CURSOR, Cursor.SW_RESIZE_CURSOR, Cursor.S_RESIZE_CURSOR,
Cursor.SE_RESIZE_CURSOR, Cursor.SE_RESIZE_CURSOR
};
/**
* MouseInputHandler is responsible for handling resize/moving of
* the Window. It sets the cursor directly on the Window when then
* mouse moves over a hot spot.
*/
private class MouseInputHandler implements MouseInputListener {
/**
* Set to true if the drag operation is moving the window.
*/
private boolean isMovingWindow;
/**
* Used to determine the corner the resize is occurring from.
*/
private int dragCursor;
/**
* X location the mouse went down on for a drag operation.
*/
private int dragOffsetX;
/**
* Y location the mouse went down on for a drag operation.
*/
private int dragOffsetY;
/**
* Width of the window when the drag started.
*/
private int dragWidth;
/**
* Height of the window when the drag started.
*/
private int dragHeight;
public void mousePressed(MouseEvent ev) {
JRootPane rootPane = getRootPane();
if (rootPane.getWindowDecorationStyle() == JRootPane.NONE) {
return;
}
Point dragWindowOffset = ev.getPoint();
Window w = (Window)ev.getSource();
if (w != null) {
w.toFront();
}
Point convertedDragWindowOffset = SwingUtilities.convertPoint(
w, dragWindowOffset, getTitlePane());
Frame f = null;
Dialog d = null;
if (w instanceof Frame) {
f = (Frame)w;
} else if (w instanceof Dialog) {
d = (Dialog)w;
}
int frameState = (f != null) ? f.getExtendedState() : 0;
if (getTitlePane() != null &&
getTitlePane().contains(convertedDragWindowOffset)) {
if ((f != null && ((frameState & Frame.MAXIMIZED_BOTH) == 0)
|| (d != null))
&& dragWindowOffset.y >= BORDER_DRAG_THICKNESS
&& dragWindowOffset.x >= BORDER_DRAG_THICKNESS
&& dragWindowOffset.x < w.getWidth()
- BORDER_DRAG_THICKNESS) {
isMovingWindow = true;
dragOffsetX = dragWindowOffset.x;
dragOffsetY = dragWindowOffset.y;
}
}
else if (f != null && f.isResizable()
&& ((frameState & Frame.MAXIMIZED_BOTH) == 0)
|| (d != null && d.isResizable())) {
dragOffsetX = dragWindowOffset.x;
dragOffsetY = dragWindowOffset.y;
dragWidth = w.getWidth();
dragHeight = w.getHeight();
dragCursor = getCursor(calculateCorner(
w, dragWindowOffset.x, dragWindowOffset.y));
}
}
public void mouseReleased(MouseEvent ev) {
if (dragCursor != 0 && window != null && !window.isValid()) {
// Some Window systems validate as you resize, others won't,
// thus the check for validity before repainting.
window.validate();
getRootPane().repaint();
}
isMovingWindow = false;
dragCursor = 0;
}
public void mouseMoved(MouseEvent ev) {
JRootPane root = getRootPane();
if (root.getWindowDecorationStyle() == JRootPane.NONE) {
return;
}
Window w = (Window)ev.getSource();
Frame f = null;
Dialog d = null;
if (w instanceof Frame) {
f = (Frame)w;
} else if (w instanceof Dialog) {
d = (Dialog)w;
}
// Update the cursor
int cursor = getCursor(calculateCorner(w, ev.getX(), ev.getY()));
if (cursor != 0 && ((f != null && (f.isResizable() &&
(f.getExtendedState() & Frame.MAXIMIZED_BOTH) == 0))
|| (d != null && d.isResizable()))) {
w.setCursor(Cursor.getPredefinedCursor(cursor));
}
else {
w.setCursor(lastCursor);
}
}
private void adjust(Rectangle bounds, Dimension min, int deltaX,
int deltaY, int deltaWidth, int deltaHeight) {
bounds.x += deltaX;
bounds.y += deltaY;
bounds.width += deltaWidth;
bounds.height += deltaHeight;
if (min != null) {
if (bounds.width < min.width) {
int correction = min.width - bounds.width;
if (deltaX != 0) {
bounds.x -= correction;
}
bounds.width = min.width;
}
if (bounds.height < min.height) {
int correction = min.height - bounds.height;
if (deltaY != 0) {
bounds.y -= correction;
}
bounds.height = min.height;
}
}
}
public void mouseDragged(MouseEvent ev) {
Window w = (Window)ev.getSource();
Point pt = ev.getPoint();
if (isMovingWindow) {
Point eventLocationOnScreen = ev.getLocationOnScreen();
w.setLocation(eventLocationOnScreen.x - dragOffsetX,
eventLocationOnScreen.y - dragOffsetY);
}
else if (dragCursor != 0) {
Rectangle r = w.getBounds();
Rectangle startBounds = new Rectangle(r);
Dimension min = w.getMinimumSize();
switch (dragCursor) {
case Cursor.E_RESIZE_CURSOR:
adjust(r, min, 0, 0, pt.x + (dragWidth - dragOffsetX) -
r.width, 0);
break;
case Cursor.S_RESIZE_CURSOR:
adjust(r, min, 0, 0, 0, pt.y + (dragHeight - dragOffsetY) -
r.height);
break;
case Cursor.N_RESIZE_CURSOR:
adjust(r, min, 0, pt.y -dragOffsetY, 0,
-(pt.y - dragOffsetY));
break;
case Cursor.W_RESIZE_CURSOR:
adjust(r, min, pt.x - dragOffsetX, 0,
-(pt.x - dragOffsetX), 0);
break;
case Cursor.NE_RESIZE_CURSOR:
adjust(r, min, 0, pt.y - dragOffsetY,
pt.x + (dragWidth - dragOffsetX) - r.width,
-(pt.y - dragOffsetY));
break;
case Cursor.SE_RESIZE_CURSOR:
adjust(r, min, 0, 0,
pt.x + (dragWidth - dragOffsetX) - r.width,
pt.y + (dragHeight - dragOffsetY) -
r.height);
break;
case Cursor.NW_RESIZE_CURSOR:
adjust(r, min, pt.x - dragOffsetX,
pt.y - dragOffsetY,
-(pt.x - dragOffsetX),
-(pt.y - dragOffsetY));
break;
case Cursor.SW_RESIZE_CURSOR:
adjust(r, min, pt.x - dragOffsetX, 0,
-(pt.x - dragOffsetX),
pt.y + (dragHeight - dragOffsetY) - r.height);
break;
default:
break;
}
if (!r.equals(startBounds)) {
w.setBounds(r);
// Defer repaint/validate on mouseReleased unless dynamic
// layout is active.
if (Toolkit.getDefaultToolkit().isDynamicLayoutActive()) {
w.validate();
getRootPane().repaint();
}
}
}
}
public void mouseEntered(MouseEvent ev) {
Window w = (Window)ev.getSource();
lastCursor = w.getCursor();
mouseMoved(ev);
}
public void mouseExited(MouseEvent ev) {
Window w = (Window)ev.getSource();
w.setCursor(lastCursor);
}
public void mouseClicked(MouseEvent ev) {
Window w = (Window)ev.getSource();
Frame f = null;
if (w instanceof Frame) {
f = (Frame)w;
} else {
return;
}
Point convertedPoint = SwingUtilities.convertPoint(
w, ev.getPoint(), getTitlePane());
int state = f.getExtendedState();
if (getTitlePane() != null &&
getTitlePane().contains(convertedPoint)) {
if ((ev.getClickCount() % 2) == 0 &&
((ev.getModifiers() & InputEvent.BUTTON1_MASK) != 0)) {
if (f.isResizable()) {
if ((state & Frame.MAXIMIZED_BOTH) != 0) {
f.setExtendedState(state & ~Frame.MAXIMIZED_BOTH);
}
else {
f.setExtendedState(state | Frame.MAXIMIZED_BOTH);
}
return;
}
}
}
}
/**
* Returns the corner that contains the point <code>x</code>,
* <code>y</code>, or -1 if the position doesn't match a corner.
*/
private int calculateCorner(Window w, int x, int y) {
Insets insets = w.getInsets();
int xPosition = calculatePosition(x - insets.left,
w.getWidth() - insets.left - insets.right);
int yPosition = calculatePosition(y - insets.top,
w.getHeight() - insets.top - insets.bottom);
if (xPosition == -1 || yPosition == -1) {
return -1;
}
return yPosition * 5 + xPosition;
}
/**
* Returns the Cursor to render for the specified corner. This returns
* 0 if the corner doesn't map to a valid Cursor
*/
private int getCursor(int corner) {
if (corner == -1) {
return 0;
}
return cursorMapping[corner];
}
/**
* Returns an integer indicating the position of <code>spot</code>
* in <code>width</code>. The return value will be:
* 0 if < BORDER_DRAG_THICKNESS
* 1 if < CORNER_DRAG_WIDTH
* 2 if >= CORNER_DRAG_WIDTH && < width - BORDER_DRAG_THICKNESS
* 3 if >= width - CORNER_DRAG_WIDTH
* 4 if >= width - BORDER_DRAG_THICKNESS
* 5 otherwise
*/
private int calculatePosition(int spot, int width) {
if (spot < BORDER_DRAG_THICKNESS) {
return 0;
}
if (spot < CORNER_DRAG_WIDTH) {
return 1;
}
if (spot >= (width - BORDER_DRAG_THICKNESS)) {
return 4;
}
if (spot >= (width - CORNER_DRAG_WIDTH)) {
return 3;
}
return 2;
}
}
}
|
apache/ofbiz-plugins | 36,448 | ebay/src/main/java/org/apache/ofbiz/ebay/ProductsExportToEbay.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.ebay;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.StringUtil;
import org.apache.ofbiz.base.util.UtilCodec;
import org.apache.ofbiz.base.util.UtilGenerics;
import org.apache.ofbiz.base.util.UtilMisc;
import org.apache.ofbiz.base.util.UtilProperties;
import org.apache.ofbiz.base.util.UtilURL;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.base.util.UtilXml;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.condition.EntityCondition;
import org.apache.ofbiz.entity.condition.EntityOperator;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.entity.util.EntityUtil;
import org.apache.ofbiz.entity.util.EntityUtilProperties;
import org.apache.ofbiz.product.product.ProductContentWrapper;
import org.apache.ofbiz.service.DispatchContext;
import org.apache.ofbiz.service.ModelService;
import org.apache.ofbiz.service.ServiceUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class ProductsExportToEbay {
private static final String RESOURCE = "EbayUiLabels";
private static final String CONFIG_FILE_NAME = "ebayExport.properties";
private static final String MODULE = ProductsExportToEbay.class.getName();
private static List<String> productExportSuccessMessageList = new LinkedList<>();
private static List<String> productExportFailureMessageList = new LinkedList<>();
public static Map<String, Object> exportToEbay(DispatchContext dctx, Map<String, Object> context) {
Locale locale = (Locale) context.get("locale");
Delegator delegator = dctx.getDelegator();
productExportSuccessMessageList.clear();
productExportFailureMessageList.clear();
Map<String, Object> result = new HashMap<>();
Map<String, Object> response = null;
try {
List<String> selectResult = UtilGenerics.checkCollection(context.get("selectResult"), String.class);
List<GenericValue> productsList = EntityQuery.use(delegator).from("Product").where(EntityCondition.makeCondition("productId",
EntityOperator.IN, selectResult)).queryList();
if (UtilValidate.isNotEmpty(productsList)) {
for (GenericValue product : productsList) {
GenericValue startPriceValue = EntityUtil.getFirst(EntityUtil.filterByDate(product.getRelated("ProductPrice", UtilMisc.toMap(
"productPricePurposeId", "EBAY", "productPriceTypeId", "MINIMUM_PRICE"), null, false)));
if (UtilValidate.isEmpty(startPriceValue)) {
String startPriceMissingMsg = "Unable to find a starting price for auction of product with id (" + product.getString(
"productId") + "), So Ignoring the export of this product to eBay.";
productExportFailureMessageList.add(startPriceMissingMsg);
// Ignore the processing of product having no start price value
continue;
}
Map<String, Object> eBayConfigResult = EbayHelper.buildEbayConfig(context, delegator);
StringBuffer dataItemsXml = new StringBuffer();
Map<String, Object> resultMap = buildDataItemsXml(dctx, context, dataItemsXml, eBayConfigResult.get("token").toString(), product);
if (!ServiceUtil.isFailure(resultMap)) {
response = postItem(eBayConfigResult.get("xmlGatewayUri").toString(), dataItemsXml,
eBayConfigResult.get("devID").toString(), eBayConfigResult.get("appID").toString(),
eBayConfigResult.get("certID").toString(), "AddItem", eBayConfigResult.get("compatibilityLevel").toString(),
eBayConfigResult.get("siteID").toString());
if (ServiceUtil.isFailure(response)) {
return ServiceUtil.returnFailure(ServiceUtil.getErrorMessage(response));
}
if (UtilValidate.isNotEmpty(response)) {
exportToEbayResponse((String) response.get("successMessage"), product);
}
} else {
return ServiceUtil.returnFailure(ServiceUtil.getErrorMessage(resultMap));
}
}
}
} catch (Exception e) {
Debug.logError("Exception in exportToEbay " + e, MODULE);
return ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay.exceptionInExportToEbay", locale));
}
if (UtilValidate.isNotEmpty(productExportSuccessMessageList)) {
result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
result.put(ModelService.SUCCESS_MESSAGE_LIST, productExportSuccessMessageList);
}
if (UtilValidate.isNotEmpty(productExportFailureMessageList)) {
result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_FAIL);
result.put(ModelService.ERROR_MESSAGE_LIST, productExportFailureMessageList);
}
return result;
}
private static void appendRequesterCredentials(Element elem, Document doc, String token) {
Element requesterCredentialsElem = UtilXml.addChildElement(elem, "RequesterCredentials", doc);
UtilXml.addChildElementValue(requesterCredentialsElem, "eBayAuthToken", token, doc);
}
private static String toString(InputStream inputStream) throws IOException {
String string;
StringBuilder outputBuilder = new StringBuilder();
if (inputStream != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
while (null != (string = reader.readLine())) {
outputBuilder.append(string).append('\n');
}
}
return outputBuilder.toString();
}
private static Map<String, Object> postItem(String postItemsUrl, StringBuffer dataItems, String devID, String appID, String certID,
String callName, String compatibilityLevel, String siteID) throws IOException {
if (Debug.verboseOn()) {
Debug.logVerbose("Request of " + callName + " To eBay:\n" + dataItems.toString(), MODULE);
}
HttpURLConnection connection = (HttpURLConnection) (UtilURL.fromUrlString(postItemsUrl)).openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("X-EBAY-API-COMPATIBILITY-LEVEL", compatibilityLevel);
connection.setRequestProperty("X-EBAY-API-DEV-NAME", devID);
connection.setRequestProperty("X-EBAY-API-APP-NAME", appID);
connection.setRequestProperty("X-EBAY-API-CERT-NAME", certID);
connection.setRequestProperty("X-EBAY-API-CALL-NAME", callName);
connection.setRequestProperty("X-EBAY-API-SITEID", siteID);
connection.setRequestProperty("Content-Type", "text/xml");
OutputStream outputStream = connection.getOutputStream();
outputStream.write(dataItems.toString().getBytes());
outputStream.close();
int responseCode = connection.getResponseCode();
InputStream inputStream;
Map<String, Object> result = new HashMap<>();
String response = null;
if (responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
response = toString(inputStream);
result = ServiceUtil.returnSuccess(response);
} else {
inputStream = connection.getErrorStream();
response = toString(inputStream);
result = ServiceUtil.returnFailure(response);
}
if (Debug.verboseOn()) {
Debug.logVerbose("Response of " + callName + " From eBay:\n" + response, MODULE);
}
return result;
}
public static Map<String, Object> buildDataItemsXml(DispatchContext dctx, Map<String, Object> context, StringBuffer dataItemsXml, String token,
GenericValue prod) {
Locale locale = (Locale) context.get("locale");
try {
Delegator delegator = dctx.getDelegator();
String webSiteUrl = (String) context.get("webSiteUrl");
UtilCodec.SimpleEncoder encoder = UtilCodec.getEncoder("xml");
// Get the list of products to be exported to eBay
try {
Document itemDocument = UtilXml.makeEmptyXmlDocument("AddItemRequest");
Element itemRequestElem = itemDocument.getDocumentElement();
itemRequestElem.setAttribute("xmlns", "urn:ebay:apis:eBLBaseComponents");
appendRequesterCredentials(itemRequestElem, itemDocument, token);
String title = prod.getString("internalName");
String qnt = (String) context.get("quantity");
if (UtilValidate.isEmpty(qnt)) {
qnt = "1";
}
String productDescription = "";
String description = prod.getString("description");
String longDescription = prod.getString("longDescription");
if (UtilValidate.isNotEmpty(description)) {
productDescription = description;
} else if (UtilValidate.isNotEmpty(longDescription)) {
productDescription = longDescription;
} else if (UtilValidate.isNotEmpty(prod.getString("productName"))) {
productDescription = prod.getString("productName");
}
String startPrice = (String) context.get("startPrice");
String startPriceCurrencyUomId = null;
if (UtilValidate.isEmpty(startPrice)) {
GenericValue startPriceValue = EntityUtil.getFirst(EntityUtil.filterByDate(prod.getRelated("ProductPrice", UtilMisc.toMap(
"productPricePurposeId", "EBAY", "productPriceTypeId", "MINIMUM_PRICE"), null, false)));
if (UtilValidate.isNotEmpty(startPriceValue)) {
startPrice = startPriceValue.getString("price");
startPriceCurrencyUomId = startPriceValue.getString("currencyUomId");
}
}
// Buy it now is the optional value for a product that you send to eBay. Once this value is entered by user - this option allow
// user to win auction immediately.
String buyItNowPrice = (String) context.get("buyItNowPrice");
String buyItNowCurrencyUomId = null;
if (UtilValidate.isEmpty(buyItNowPrice)) {
GenericValue buyItNowPriceValue = EntityUtil.getFirst(EntityUtil.filterByDate(prod.getRelated("ProductPrice", UtilMisc.toMap(
"productPricePurposeId", "EBAY", "productPriceTypeId", "MAXIMUM_PRICE"), null, false)));
if (UtilValidate.isNotEmpty(buyItNowPriceValue)) {
buyItNowPrice = buyItNowPriceValue.getString("price");
buyItNowCurrencyUomId = buyItNowPriceValue.getString("currencyUomId");
}
}
Element itemElem = UtilXml.addChildElement(itemRequestElem, "Item", itemDocument);
UtilXml.addChildElementValue(itemElem, "Country", (String) context.get("country"), itemDocument);
String location = (String) context.get("location");
if (UtilValidate.isNotEmpty(location)) {
UtilXml.addChildElementValue(itemElem, "Location", location, itemDocument);
}
UtilXml.addChildElementValue(itemElem, "ApplicationData", prod.getString("productId"), itemDocument);
UtilXml.addChildElementValue(itemElem, "SKU", prod.getString("productId"), itemDocument);
UtilXml.addChildElementValue(itemElem, "Title", title, itemDocument);
UtilXml.addChildElementValue(itemElem, "ListingDuration", (String) context.get("listingDuration"), itemDocument);
UtilXml.addChildElementValue(itemElem, "Quantity", qnt, itemDocument);
String listingFormat = "";
if (UtilValidate.isNotEmpty(context.get("listingFormat"))) {
listingFormat = (String) context.get("listingFormat");
UtilXml.addChildElementValue(itemElem, "ListingType", listingFormat, itemDocument);
}
if ("FixedPriceItem".equals(listingFormat)) {
Element startPriceElem = UtilXml.addChildElementValue(itemElem, "StartPrice", startPrice, itemDocument);
if (UtilValidate.isEmpty(startPriceCurrencyUomId)) {
startPriceCurrencyUomId = EntityUtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD", delegator);
}
startPriceElem.setAttribute("currencyID", startPriceCurrencyUomId);
} else {
Element startPriceElem = UtilXml.addChildElementValue(itemElem, "StartPrice", startPrice, itemDocument);
if (UtilValidate.isEmpty(startPriceCurrencyUomId)) {
startPriceCurrencyUomId = EntityUtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD", delegator);
}
startPriceElem.setAttribute("currencyID", startPriceCurrencyUomId);
if (UtilValidate.isNotEmpty(buyItNowPrice)) {
Element buyNowPriceElem = UtilXml.addChildElementValue(itemElem, "BuyItNowPrice", buyItNowPrice, itemDocument);
if (UtilValidate.isEmpty(buyItNowCurrencyUomId)) {
buyItNowCurrencyUomId = EntityUtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD", delegator);
}
buyNowPriceElem.setAttribute("currencyID", buyItNowCurrencyUomId);
}
}
ProductContentWrapper pcw = new ProductContentWrapper(dctx.getDispatcher(), prod, locale, EntityUtilProperties.getPropertyValue(
"content", "defaultMimeType", "text/html; charset=utf-8", delegator));
StringUtil.StringWrapper ebayDescription = pcw.get("EBAY_DESCRIPTION", "html");
if (UtilValidate.isNotEmpty(ebayDescription.toString())) {
UtilXml.addChildElementCDATAValue(itemElem, "Description", ebayDescription.toString(), itemDocument);
} else {
UtilXml.addChildElementValue(itemElem, "Description", encoder.encode(productDescription), itemDocument);
}
String smallImage = prod.getString("smallImageUrl");
String mediumImage = prod.getString("mediumImageUrl");
String largeImage = prod.getString("largeImageUrl");
String ebayImage = null;
if (UtilValidate.isNotEmpty(largeImage)) {
ebayImage = largeImage;
} else if (UtilValidate.isNotEmpty(mediumImage)) {
ebayImage = mediumImage;
} else if (UtilValidate.isNotEmpty(smallImage)) {
ebayImage = smallImage;
}
if (UtilValidate.isNotEmpty(ebayImage)) {
Element pictureDetails = UtilXml.addChildElement(itemElem, "PictureDetails", itemDocument);
UtilXml.addChildElementValue(pictureDetails, "PictureURL", webSiteUrl + ebayImage, itemDocument);
}
setPaymentMethodAccepted(itemDocument, itemElem, context);
setMiscDetails(itemDocument, itemElem, context, delegator);
String categoryCode = (String) context.get("ebayCategory");
String primaryCategoryId = "";
if (categoryCode != null) {
if (categoryCode.indexOf("_") != -1) {
String[] params = categoryCode.split("_");
if (UtilValidate.isEmpty(params) || params[1].isEmpty()) {
ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay"
+ ".parametersNotCorrectInGetEbayCategories", locale));
} else {
primaryCategoryId = params[1];
}
} else {
primaryCategoryId = categoryCode;
}
} else {
GenericValue productCategoryValue = EntityQuery.use(delegator).from("ProductCategoryAndMember")
.where("productCategoryTypeId", "EBAY_CATEGORY", "productId", prod.getString("productId"))
.filterByDate()
.queryFirst();
if (UtilValidate.isNotEmpty(productCategoryValue)) {
primaryCategoryId = productCategoryValue.getString("categoryName");
}
}
Element primaryCatElem = UtilXml.addChildElement(itemElem, "PrimaryCategory", itemDocument);
UtilXml.addChildElementValue(primaryCatElem, "CategoryID", primaryCategoryId, itemDocument);
UtilXml.addChildElementValue(itemElem, "ConditionID", "1000", itemDocument);
Element itemSpecificsElem = UtilXml.addChildElement(itemElem, "ItemSpecifics", itemDocument);
Element nameValueListElem = UtilXml.addChildElement(itemSpecificsElem, "NameValueList", itemDocument);
UtilXml.addChildElementValue(nameValueListElem, "Name", "Condition", itemDocument);
UtilXml.addChildElementValue(nameValueListElem, "Value", "New: With Tags", itemDocument);
//Debug.logInfo("The generated string is ======= " + UtilXml.writeXmlDocument(itemDocument), MODULE);
dataItemsXml.append(UtilXml.writeXmlDocument(itemDocument));
} catch (Exception e) {
Debug.logError("Exception during building data items to eBay: " + e.getMessage(), MODULE);
return ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay.exceptionDuringBuildingDataItemsToEbay",
locale));
}
} catch (Exception e) {
Debug.logError("Exception during building data items to eBay: " + e.getMessage(), MODULE);
return ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay.exceptionDuringBuildingDataItemsToEbay",
locale));
}
return ServiceUtil.returnSuccess();
}
private static Map<String, Object> buildCategoriesXml(Map<String, Object> context, StringBuffer dataItemsXml, String token, String siteID,
String categoryParent, String levelLimit) {
Locale locale = (Locale) context.get("locale");
try {
Document itemRequest = UtilXml.makeEmptyXmlDocument("GetCategoriesRequest");
Element itemRequestElem = itemRequest.getDocumentElement();
itemRequestElem.setAttribute("xmlns", "urn:ebay:apis:eBLBaseComponents");
appendRequesterCredentials(itemRequestElem, itemRequest, token);
UtilXml.addChildElementValue(itemRequestElem, "DetailLevel", "ReturnAll", itemRequest);
UtilXml.addChildElementValue(itemRequestElem, "CategorySiteID", siteID, itemRequest);
if (UtilValidate.isNotEmpty(categoryParent)) {
UtilXml.addChildElementValue(itemRequestElem, "CategoryParent", categoryParent, itemRequest);
}
if (UtilValidate.isEmpty(levelLimit)) {
levelLimit = "1";
}
UtilXml.addChildElementValue(itemRequestElem, "LevelLimit", levelLimit, itemRequest);
UtilXml.addChildElementValue(itemRequestElem, "ViewAllNodes", "true", itemRequest);
dataItemsXml.append(UtilXml.writeXmlDocument(itemRequest));
} catch (Exception e) {
Debug.logError("Exception during building data items to eBay", MODULE);
return ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay.exceptionDuringBuildingGetCategoriesRequest",
locale));
}
return ServiceUtil.returnSuccess();
}
/*
private static Map<String, Object> buildSetTaxTableRequestXml(DispatchContext dctx, Map<String, Object> context, StringBuffer
setTaxTableRequestXml, String token) {
Locale locale = (Locale) context.get("locale");
try {
Document taxRequestDocument = UtilXml.makeEmptyXmlDocument("SetTaxTableRequest");
Element taxRequestElem = taxRequestDocument.getDocumentElement();
taxRequestElem.setAttribute("xmlns", "urn:ebay:apis:eBLBaseComponents");
appendRequesterCredentials(taxRequestElem, taxRequestDocument, token);
Element taxTableElem = UtilXml.addChildElement(taxRequestElem, "TaxTable", taxRequestDocument);
Element taxJurisdictionElem = UtilXml.addChildElement(taxTableElem, "TaxJurisdiction", taxRequestDocument);
UtilXml.addChildElementValue(taxJurisdictionElem, "JurisdictionID", "NY", taxRequestDocument);
UtilXml.addChildElementValue(taxJurisdictionElem, "SalesTaxPercent", "4.25", taxRequestDocument);
UtilXml.addChildElementValue(taxJurisdictionElem, "ShippingIncludedInTax", "false", taxRequestDocument);
setTaxTableRequestXml.append(UtilXml.writeXmlDocument(taxRequestDocument));
} catch (Exception e) {
Debug.logError("Exception during building request set tax table to eBay", MODULE);
return ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay
.exceptionDuringBuildingRequestSetTaxTableToEbay", locale));
}
return ServiceUtil.returnSuccess();
}
private static Map<String, Object> buildAddTransactionConfirmationItemRequest(Map<String, Object> context, StringBuffer dataItemsXml, String
token, String itemId) {
Locale locale = (Locale) context.get("locale");
try {
Document transDoc = UtilXml.makeEmptyXmlDocument("AddTransactionConfirmationItemRequest");
Element transElem = transDoc.getDocumentElement();
transElem.setAttribute("xmlns", "urn:ebay:apis:eBLBaseComponents");
appendRequesterCredentials(transElem, transDoc, token);
UtilXml.addChildElementValue(transElem, "ItemID", itemId, transDoc);
UtilXml.addChildElementValue(transElem, "ListingDuration", "Days_1", transDoc);
Element negotiatePriceElem = UtilXml.addChildElementValue(transElem, "NegotiatedPrice", "50.00", transDoc);
negotiatePriceElem.setAttribute("currencyID", "USD");
UtilXml.addChildElementValue(transElem, "RecipientRelationType", "1", transDoc);
UtilXml.addChildElementValue(transElem, "RecipientUserID", "buyer_anytime", transDoc);
dataItemsXml.append(UtilXml.writeXmlDocument(transDoc));
Debug.logInfo(dataItemsXml.toString(), MODULE);
} catch (Exception e) {
Debug.logError("Exception during building AddTransactionConfirmationItemRequest eBay", MODULE);
return ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay
.exceptionDuringBuildingAddTransactionConfirmationItemRequestToEbay", locale));
}
return ServiceUtil.returnSuccess();
}*/
private static void setPaymentMethodAccepted(Document itemDocument, Element itemElem, Map<String, Object> context) {
String payPal = (String) context.get("paymentPayPal");
String payPalEmail = (String) context.get("payPalEmail");
String visaMC = (String) context.get("paymentVisaMC");
String amEx = (String) context.get("paymentAmEx");
String discover = (String) context.get("paymentDiscover");
String ccAccepted = (String) context.get("paymentCCAccepted");
String cashInPerson = (String) context.get("paymentCashInPerson");
String cashOnPickup = (String) context.get("paymentCashOnPickup");
String cod = (String) context.get("paymentCOD");
String codPrePayDelivery = (String) context.get("paymentCODPrePayDelivery");
String mocc = (String) context.get("paymentMOCC");
String moneyXferAccepted = (String) context.get("paymentMoneyXferAccepted");
String personalCheck = (String) context.get("paymentPersonalCheck");
// PayPal
if (UtilValidate.isNotEmpty(payPal) && "on".equals(payPal)) {
UtilXml.addChildElementValue(itemElem, "PaymentMethods", "PayPal", itemDocument);
// PayPal email
if (UtilValidate.isNotEmpty(payPalEmail)) {
UtilXml.addChildElementValue(itemElem, "PayPalEmailAddress", payPalEmail, itemDocument);
}
}
// Visa/Master Card
if (UtilValidate.isNotEmpty(visaMC) && "on".equals(visaMC)) {
UtilXml.addChildElementValue(itemElem, "PaymentMethods", "VisaMC", itemDocument);
}
// American Express
if (UtilValidate.isNotEmpty(amEx) && "on".equals(amEx)) {
UtilXml.addChildElementValue(itemElem, "PaymentMethods", "AmEx", itemDocument);
}
// Discover
if (UtilValidate.isNotEmpty(discover) && "on".equals(discover)) {
UtilXml.addChildElementValue(itemElem, "PaymentMethods", "Discover", itemDocument);
}
// Credit Card Accepted
if (UtilValidate.isNotEmpty(ccAccepted) && "on".equals(ccAccepted)) {
UtilXml.addChildElementValue(itemElem, "PaymentMethods", "CCAccepted", itemDocument);
}
// Cash In Person
if (UtilValidate.isNotEmpty(cashInPerson) && "on".equals(cashInPerson)) {
UtilXml.addChildElementValue(itemElem, "PaymentMethods", "CashInPerson", itemDocument);
}
// Cash on Pickup
if (UtilValidate.isNotEmpty(cashOnPickup) && "on".equals(cashOnPickup)) {
UtilXml.addChildElementValue(itemElem, "PaymentMethods", "CashOnPickup", itemDocument);
}
// Cash on Delivery
if (UtilValidate.isNotEmpty(cod) && "on".equals(cod)) {
UtilXml.addChildElementValue(itemElem, "PaymentMethods", "COD", itemDocument);
}
// Cash On Delivery After Paid
if (UtilValidate.isNotEmpty(codPrePayDelivery) && "on".equals(codPrePayDelivery)) {
UtilXml.addChildElementValue(itemElem, "PaymentMethods", "CODPrePayDelivery", itemDocument);
}
// Money order/cashiers check
if (UtilValidate.isNotEmpty(mocc) && "on".equals(mocc)) {
UtilXml.addChildElementValue(itemElem, "PaymentMethods", "MOCC", itemDocument);
}
// Direct transfer of money
if (UtilValidate.isNotEmpty(moneyXferAccepted) && "on".equals(moneyXferAccepted)) {
UtilXml.addChildElementValue(itemElem, "PaymentMethods", "MoneyXferAccepted", itemDocument);
}
// Personal Check
if (UtilValidate.isNotEmpty(personalCheck) && "on".equals(personalCheck)) {
UtilXml.addChildElementValue(itemElem, "PaymentMethods", "PersonalCheck", itemDocument);
}
}
private static void setMiscDetails(Document itemDocument, Element itemElem, Map<String, Object> context, Delegator delegator) throws Exception {
String customXmlFromUI = (String) context.get("customXml");
String customXml = "";
if (UtilValidate.isNotEmpty(customXmlFromUI)) {
customXml = customXmlFromUI;
} else {
customXml = EntityUtilProperties.getPropertyValue(CONFIG_FILE_NAME, "eBayExport.customXml", delegator);
}
if (UtilValidate.isNotEmpty(customXml)) {
Document customXmlDoc = UtilXml.readXmlDocument(customXml);
if (UtilValidate.isNotEmpty(customXmlDoc)) {
Element customXmlElement = customXmlDoc.getDocumentElement();
for (Element eBayElement : UtilXml.childElementList(customXmlElement)) {
Node importedElement = itemElem.getOwnerDocument().importNode(eBayElement, true);
itemElem.appendChild(importedElement);
}
}
}
}
public static Map<String, Object> getEbayCategories(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
Locale locale = (Locale) context.get("locale");
String categoryCode = (String) context.get("categoryCode");
Map<String, Object> result = null;
try {
Map<String, Object> eBayConfigResult = EbayHelper.buildEbayConfig(context, delegator);
String categoryParent = "";
String levelLimit = "";
if (categoryCode != null) {
String[] params = categoryCode.split("_");
if (params == null || params.length != 3) {
ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay.parametersNotCorrectInGetEbayCategories",
locale));
} else {
categoryParent = params[1];
levelLimit = params[2];
Integer level = Integer.valueOf(levelLimit);
levelLimit = (level + 1) + "";
}
}
StringBuffer dataItemsXml = new StringBuffer();
if (!ServiceUtil.isFailure(buildCategoriesXml(context, dataItemsXml, eBayConfigResult.get("token").toString(), eBayConfigResult.get(
"siteID").toString(), categoryParent, levelLimit))) {
Map<String, Object> resultCat = postItem(eBayConfigResult.get("xmlGatewayUri").toString(), dataItemsXml, eBayConfigResult.get(
"devID").toString(), eBayConfigResult.get("appID").toString(), eBayConfigResult.get("certID").toString(), "GetCategories",
eBayConfigResult.get("compatibilityLevel").toString(), eBayConfigResult.get("siteID").toString());
String successMessage = (String) resultCat.get("successMessage");
if (successMessage != null) {
result = readEbayCategoriesResponse(successMessage, locale);
} else {
ServiceUtil.returnFailure(ServiceUtil.getErrorMessage(resultCat));
}
}
} catch (Exception e) {
Debug.logError("Exception in GetEbayCategories " + e, MODULE);
return ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay.exceptionInGetEbayCategories", locale));
}
return result;
}
private static Map<String, Object> readEbayCategoriesResponse(String msg, Locale locale) {
Map<String, Object> results = null;
List<Map<String, Object>> categories = new LinkedList<>();
try {
Document docResponse = UtilXml.readXmlDocument(msg, true);
Element elemResponse = docResponse.getDocumentElement();
String ack = UtilXml.childElementValue(elemResponse, "Ack", "Failure");
if (ack != null && "Failure".equals(ack)) {
String errorMessage = "";
for (Element errorElement : UtilXml.childElementList(elemResponse, "Errors")) {
errorMessage = UtilXml.childElementValue(errorElement, "ShortMessage", "");
}
return ServiceUtil.returnFailure(errorMessage);
} else {
// retrieve Category Array
for (Element categoryArrayElement : UtilXml.childElementList(elemResponse, "CategoryArray")) {
// retrieve Category
for (Element categoryElement : UtilXml.childElementList(categoryArrayElement, "Category")) {
Map<String, Object> categ = new HashMap<>();
String categoryCode = ("true".equalsIgnoreCase((UtilXml.childElementValue(categoryElement, "LeafCategory", "").trim()))
? "Y" : "N") + "_"
+ UtilXml.childElementValue(categoryElement, "CategoryID", "").trim() + "_"
+ UtilXml.childElementValue(categoryElement, "CategoryLevel", "").trim();
categ.put("CategoryCode", categoryCode);
categ.put("CategoryName", UtilXml.childElementValue(categoryElement, "CategoryName"));
categories.add(categ);
}
}
categories = UtilGenerics.cast(UtilMisc.sortMaps(UtilGenerics.<List<Map<Object, Object>>>cast(categories), UtilMisc.toList(
"CategoryName")));
results = UtilMisc.toMap("categories", (Object) categories);
}
} catch (Exception e) {
return ServiceUtil.returnFailure();
}
return results;
}
public static Map<String, Object> exportToEbayResponse(String msg, GenericValue product) {
Map<String, Object> result = ServiceUtil.returnSuccess();
try {
Document docResponse = UtilXml.readXmlDocument(msg, true);
Element elemResponse = docResponse.getDocumentElement();
String ack = UtilXml.childElementValue(elemResponse, "Ack", "Failure");
if (ack != null && "Failure".equals(ack)) {
String errorMessage = "";
for (Element errorElement : UtilXml.childElementList(elemResponse, "Errors")) {
errorMessage = UtilXml.childElementValue(errorElement, "LongMessage");
}
productExportFailureMessageList.add(errorMessage);
} else {
String productSuccessfullyExportedMsg = "Product successfully exported with ID (" + product.getString("productId") + ").";
productExportSuccessMessageList.add(productSuccessfullyExportedMsg);
}
} catch (Exception e) {
Debug.logError("Error in processing xml string" + e.getMessage(), MODULE);
return ServiceUtil.returnFailure();
}
return result;
}
public static List<String> getProductExportSuccessMessageList() {
return productExportSuccessMessageList;
}
public static List<String> getproductExportFailureMessageList() {
return productExportFailureMessageList;
}
}
|
apache/mina-sshd | 36,783 | sshd-core/src/main/java/org/apache/sshd/client/keyverifier/KnownHostsServerKeyVerifier.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.sshd.client.keyverifier;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.security.GeneralSecurityException;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.sshd.client.config.hosts.KnownHostEntry;
import org.apache.sshd.client.config.hosts.KnownHostHashValue;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.Factory;
import org.apache.sshd.common.FactoryManager;
import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.config.ConfigFileReaderSupport;
import org.apache.sshd.common.config.keys.AuthorizedKeyEntry;
import org.apache.sshd.common.config.keys.KeyUtils;
import org.apache.sshd.common.config.keys.OpenSshCertificate;
import org.apache.sshd.common.config.keys.PublicKeyEntry;
import org.apache.sshd.common.config.keys.PublicKeyEntryResolver;
import org.apache.sshd.common.config.keys.UnsupportedSshPublicKey;
import org.apache.sshd.common.mac.Mac;
import org.apache.sshd.common.random.Random;
import org.apache.sshd.common.session.SessionContext;
import org.apache.sshd.common.util.GenericUtils;
import org.apache.sshd.common.util.ValidateUtils;
import org.apache.sshd.common.util.io.IoUtils;
import org.apache.sshd.common.util.io.ModifiableFileWatcher;
import org.apache.sshd.common.util.net.SshdSocketAddress;
/**
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
public class KnownHostsServerKeyVerifier
extends ModifiableFileWatcher
implements ServerKeyVerifier, ModifiedServerKeyAcceptor {
/**
* Standard option used to indicate whether to use strict host key checking or not. Values may be
* "yes/no", "true/false" or "on/off"
*/
public static final String STRICT_CHECKING_OPTION = "StrictHostKeyChecking";
/**
* Standard option used to indicate alternative known hosts file location
*/
public static final String KNOWN_HOSTS_FILE_OPTION = "UserKnownHostsFile";
/**
* Represents an entry in the internal verifier's cache
*
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
public static class HostEntryPair {
private KnownHostEntry hostEntry;
private PublicKey serverKey;
public HostEntryPair() {
super();
}
public HostEntryPair(KnownHostEntry entry, PublicKey key) {
this.hostEntry = Objects.requireNonNull(entry, "No entry");
this.serverKey = Objects.requireNonNull(key, "No key");
}
public KnownHostEntry getHostEntry() {
return hostEntry;
}
public void setHostEntry(KnownHostEntry hostEntry) {
this.hostEntry = hostEntry;
}
public PublicKey getServerKey() {
return serverKey;
}
public void setServerKey(PublicKey serverKey) {
this.serverKey = serverKey;
}
@Override
public String toString() {
return String.valueOf(getHostEntry());
}
}
protected final Object updateLock = new Object();
private final ServerKeyVerifier delegate;
private final AtomicReference<Supplier<? extends Collection<HostEntryPair>>> keysSupplier
= new AtomicReference<>(getKnownHostSupplier(null, getPath()));
private ModifiedServerKeyAcceptor modKeyAcceptor;
public KnownHostsServerKeyVerifier(ServerKeyVerifier delegate, Path file) {
this(delegate, file, IoUtils.EMPTY_LINK_OPTIONS);
}
public KnownHostsServerKeyVerifier(ServerKeyVerifier delegate, Path file, LinkOption... options) {
super(file, options);
this.delegate = Objects.requireNonNull(delegate, "No delegate");
}
public ServerKeyVerifier getDelegateVerifier() {
return delegate;
}
/**
* @return The delegate {@link ModifiedServerKeyAcceptor} to consult if a server presents a modified key. If
* {@code null} then assumed to reject such a modification
*/
public ModifiedServerKeyAcceptor getModifiedServerKeyAcceptor() {
return modKeyAcceptor;
}
/**
* @param acceptor The delegate {@link ModifiedServerKeyAcceptor} to consult if a server presents a modified key. If
* {@code null} then assumed to reject such a modification
*/
public void setModifiedServerKeyAcceptor(ModifiedServerKeyAcceptor acceptor) {
modKeyAcceptor = acceptor;
}
@Override
public boolean verifyServerKey(ClientSession clientSession, SocketAddress remoteAddress, PublicKey serverKey) {
try {
if (checkReloadRequired()) {
Path file = getPath();
if (exists()) {
updateReloadAttributes();
keysSupplier.set(GenericUtils.memoizeLock(getKnownHostSupplier(clientSession, file)));
} else {
if (log.isDebugEnabled()) {
log.debug("verifyServerKey({})[{}] missing known hosts file {}",
clientSession, remoteAddress, file);
}
keysSupplier.set(GenericUtils.memoizeLock(Collections::emptyList));
}
}
} catch (Throwable t) {
return acceptIncompleteHostKeys(clientSession, remoteAddress, serverKey, t);
}
Collection<HostEntryPair> knownHosts = keysSupplier.get().get();
return acceptKnownHostEntries(clientSession, remoteAddress, serverKey, knownHosts);
}
protected Supplier<Collection<HostEntryPair>> getKnownHostSupplier(ClientSession clientSession, Path file) {
return () -> {
try {
return reloadKnownHosts(clientSession, file);
} catch (Exception e) {
log.warn("verifyServerKey({}) Could not reload known hosts file {}",
clientSession, file, e);
return Collections.emptyList();
}
};
}
protected void setLoadedHostsEntries(Collection<HostEntryPair> keys) {
keysSupplier.set(() -> keys);
}
/**
* @param session The {@link ClientSession} that triggered this request
* @param file The {@link Path} to reload from
* @return A {@link List} of the loaded {@link HostEntryPair}s - may be {@code null}/empty
* @throws IOException If failed to parse the file
* @throws GeneralSecurityException If failed to resolve the encoded public keys
*/
protected List<HostEntryPair> reloadKnownHosts(ClientSession session, Path file)
throws IOException, GeneralSecurityException {
Collection<KnownHostEntry> entries = KnownHostEntry.readKnownHostEntries(file);
boolean debugEnabled = log.isDebugEnabled();
if (debugEnabled) {
log.debug("reloadKnownHosts({}) loaded {} entries", file, entries.size());
}
updateReloadAttributes();
if (GenericUtils.isEmpty(entries)) {
return Collections.emptyList();
}
List<HostEntryPair> keys = new ArrayList<>(entries.size());
PublicKeyEntryResolver resolver = getFallbackPublicKeyEntryResolver();
for (KnownHostEntry entry : entries) {
try {
PublicKey key = resolveHostKey(session, entry, resolver);
if (key != null) {
keys.add(new HostEntryPair(entry, key));
}
} catch (Throwable t) {
warn("reloadKnownHosts({}) failed ({}) to load key of {}: {}",
file, t.getClass().getSimpleName(), entry, t.getMessage(), t);
}
}
return keys;
}
/**
* Recover the associated public key from a known host entry
*
* @param session The {@link ClientSession} that triggered this request
* @param entry The {@link KnownHostEntry} - ignored if {@code null}
* @param resolver The {@link PublicKeyEntryResolver} to use if immediate - decoding does not work
* - ignored if {@code null}
* @return The extracted {@link PublicKey} - {@code null} if none
* @throws IOException If failed to decode the key
* @throws GeneralSecurityException If failed to generate the key
* @see #getFallbackPublicKeyEntryResolver()
* @see AuthorizedKeyEntry#resolvePublicKey(SessionContext, PublicKeyEntryResolver)
*/
protected PublicKey resolveHostKey(
ClientSession session, KnownHostEntry entry, PublicKeyEntryResolver resolver)
throws IOException, GeneralSecurityException {
if (entry == null) {
return null;
}
AuthorizedKeyEntry authEntry = ValidateUtils.checkNotNull(entry.getKeyEntry(), "No key extracted from %s", entry);
PublicKey key = authEntry.resolvePublicKey(session, resolver);
if (log.isDebugEnabled()) {
log.debug("resolveHostKey({}) loaded {}-{}", entry, KeyUtils.getKeyType(key), KeyUtils.getFingerPrint(key));
}
return key;
}
protected PublicKeyEntryResolver getFallbackPublicKeyEntryResolver() {
return PublicKeyEntryResolver.UNSUPPORTED;
}
protected boolean acceptKnownHostEntries(
ClientSession clientSession, SocketAddress remoteAddress, PublicKey serverKey,
Collection<HostEntryPair> knownHosts) {
List<HostEntryPair> hostMatches = findKnownHostEntries(clientSession, remoteAddress, knownHosts);
if (hostMatches.isEmpty()) {
return acceptUnknownHostKey(clientSession, remoteAddress, serverKey);
}
PublicKey keyToCheck = serverKey instanceof OpenSshCertificate
? ((OpenSshCertificate) serverKey).getCaPubKey()
: serverKey;
boolean isCert = serverKey instanceof OpenSshCertificate;
String keyType = KeyUtils.getKeyType(keyToCheck);
List<HostEntryPair> keyMatches = hostMatches.stream()
.filter(entry -> keyType.equals(entry.getHostEntry().getKeyEntry().getKeyType()))
.filter(k -> KeyUtils.compareKeys(k.getServerKey(), keyToCheck))
.collect(Collectors.toList());
if (keyMatches.stream()
.anyMatch(k -> "revoked".equals(k.getHostEntry().getMarker()))) {
handleRevokedKey(clientSession, remoteAddress, serverKey);
return false;
}
keyMatches = keyMatches.stream()
.filter(e -> isCert == "cert-authority".equals(e.getHostEntry().getMarker()))
.collect(Collectors.toList());
if (!keyMatches.isEmpty()) {
return true;
}
if (isCert) {
return false;
}
Optional<HostEntryPair> anyNonRevokedMatch = hostMatches.stream()
.filter(k -> !"revoked".equals(k.getHostEntry().getMarker()))
.findAny();
if (!anyNonRevokedMatch.isPresent()) {
return acceptUnknownHostKey(clientSession, remoteAddress, serverKey);
}
KnownHostEntry entry = anyNonRevokedMatch.get().getHostEntry();
PublicKey expected = anyNonRevokedMatch.get().getServerKey();
try {
if (acceptModifiedServerKey(clientSession, remoteAddress, entry, expected, serverKey)) {
updateModifiedServerKey(clientSession, remoteAddress, serverKey, knownHosts, anyNonRevokedMatch.get());
return true;
}
} catch (Throwable t) {
warn("acceptKnownHostEntries({})[{}] failed ({}) to accept modified server key: {}",
clientSession, remoteAddress, t.getClass().getSimpleName(), t.getMessage(), t);
}
return false;
}
protected void updateModifiedServerKey(
ClientSession clientSession, SocketAddress remoteAddress, PublicKey serverKey, Collection<HostEntryPair> knownHosts,
HostEntryPair match) {
Path file = getPath();
try {
updateModifiedServerKey(clientSession, remoteAddress, match, serverKey, file, knownHosts);
} catch (Throwable t) {
handleModifiedServerKeyUpdateFailure(clientSession, remoteAddress, match, serverKey, file, knownHosts, t);
}
}
/**
* Invoked if a matching host entry was found, but the key did not match and
* {@link #acceptModifiedServerKey(ClientSession, SocketAddress, KnownHostEntry, PublicKey, PublicKey)} returned
* {@code true}. By default it locates the line to be updated and updates only its key data, marking the file for
* reload on next verification just to be on the safe side.
*
* @param clientSession The {@link ClientSession}
* @param remoteAddress The remote host address
* @param match The {@link HostEntryPair} whose key does not match
* @param actual The presented server {@link PublicKey} to be updated
* @param file The file {@link Path} to be updated
* @param knownHosts The currently loaded entries
* @throws Exception If failed to update the file - <B>Note:</B> this may mean the file is now corrupted
* @see #handleModifiedServerKeyUpdateFailure(ClientSession, SocketAddress, HostEntryPair,
* PublicKey, Path, Collection, Throwable)
* @see #prepareModifiedServerKeyLine(ClientSession, SocketAddress, KnownHostEntry, String,
* PublicKey, PublicKey)
*/
protected void updateModifiedServerKey(
ClientSession clientSession, SocketAddress remoteAddress, HostEntryPair match, PublicKey actual,
Path file, Collection<HostEntryPair> knownHosts)
throws Exception {
if (match.getServerKey() instanceof UnsupportedSshPublicKey) {
// Never replace unsupported keys, always add.
updateKnownHostsFile(clientSession, remoteAddress, actual, file, knownHosts);
return;
}
KnownHostEntry entry = match.getHostEntry();
String matchLine = ValidateUtils.checkNotNullAndNotEmpty(entry.getConfigLine(), "No entry config line");
String newLine = prepareModifiedServerKeyLine(
clientSession, remoteAddress, entry, matchLine, match.getServerKey(), actual);
if (GenericUtils.isEmpty(newLine)) {
if (log.isDebugEnabled()) {
log.debug("updateModifiedServerKey({})[{}] no replacement generated for {}",
clientSession, remoteAddress, matchLine);
}
return;
}
if (matchLine.equals(newLine)) {
if (log.isDebugEnabled()) {
log.debug("updateModifiedServerKey({})[{}] unmodified updated line for {}",
clientSession, remoteAddress, matchLine);
}
return;
}
List<String> lines = new ArrayList<>();
synchronized (updateLock) {
int matchingIndex = -1; // read all lines but replace the updated one
try (BufferedReader rdr = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
for (String line = rdr.readLine(); line != null; line = rdr.readLine()) {
// skip if already replaced the original line
if (matchingIndex >= 0) {
lines.add(line);
continue;
}
line = GenericUtils.trimToEmpty(line);
if (GenericUtils.isEmpty(line)) {
lines.add(line);
continue;
}
int pos = line.indexOf(ConfigFileReaderSupport.COMMENT_CHAR);
if (pos == 0) {
lines.add(line);
continue;
}
if (pos > 0) {
line = line.substring(0, pos);
line = line.trim();
}
if (!matchLine.equals(line)) {
lines.add(line);
continue;
}
lines.add(newLine);
matchingIndex = lines.size();
}
}
ValidateUtils.checkTrue(matchingIndex >= 0, "No match found for line=%s", matchLine);
try (Writer w = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
for (String l : lines) {
w.append(l).append(IoUtils.EOL);
}
}
synchronized (match) {
match.setServerKey(actual);
entry.setConfigLine(newLine);
}
}
if (log.isDebugEnabled()) {
log.debug("updateModifiedServerKey({}) replaced '{}' with '{}'", file, matchLine, newLine);
}
resetReloadAttributes(); // force reload on next verification
}
/**
* Invoked by
* {@link #updateModifiedServerKey(ClientSession, SocketAddress, HostEntryPair, PublicKey, Path, Collection)} in
* order to prepare the replacement - by default it replaces the key part with the new one
*
* @param clientSession The {@link ClientSession}
* @param remoteAddress The remote host address
* @param entry The {@link KnownHostEntry}
* @param curLine The current entry line data
* @param expected The expected {@link PublicKey}
* @param actual The present key to be update
* @return The updated line - ignored if {@code null}/empty or same as original one
* @throws Exception if failed to prepare the line
*/
protected String prepareModifiedServerKeyLine(
ClientSession clientSession, SocketAddress remoteAddress, KnownHostEntry entry,
String curLine, PublicKey expected, PublicKey actual)
throws Exception {
if ((entry == null) || GenericUtils.isEmpty(curLine)) {
return curLine; // just to be on the safe side
}
int pos = curLine.indexOf(' ');
if (curLine.charAt(0) == KnownHostEntry.MARKER_INDICATOR) {
// skip marker till next token
for (pos++; pos < curLine.length(); pos++) {
if (curLine.charAt(pos) != ' ') {
break;
}
}
pos = (pos < curLine.length()) ? curLine.indexOf(' ', pos) : -1;
}
ValidateUtils.checkTrue((pos > 0) && (pos < (curLine.length() - 1)), "Missing encoded key in line=%s", curLine);
StringBuilder sb = new StringBuilder(curLine.length());
sb.append(curLine.substring(0, pos)); // copy the marker/patterns as-is
PublicKeyEntry.appendPublicKeyEntry(sb.append(' '), actual);
return sb.toString();
}
/**
* Invoked if {@code #updateModifiedServerKey(ClientSession, SocketAddress, HostEntryPair, PublicKey, Path)} throws
* an exception. This may mean the file is corrupted, but it can be recovered from the known hosts that are being
* provided. By default, it only logs a warning and does not attempt to recover the file
*
* @param clientSession The {@link ClientSession}
* @param remoteAddress The remote host address
* @param match The {@link HostEntryPair} whose key does not match
* @param serverKey The presented server {@link PublicKey} to be updated
* @param file The file {@link Path} to be updated
* @param knownHosts The currently cached entries (may be {@code null}/empty)
* @param reason The failure reason
*/
protected void handleModifiedServerKeyUpdateFailure(
ClientSession clientSession, SocketAddress remoteAddress, HostEntryPair match,
PublicKey serverKey, Path file, Collection<HostEntryPair> knownHosts, Throwable reason) {
// NOTE !!! this may mean the file is corrupted, but it can be recovered from the known hosts
warn("acceptKnownHostEntries({})[{}] failed ({}) to update modified server key of {}: {}",
clientSession, remoteAddress, reason.getClass().getSimpleName(), match, reason.getMessage(), reason);
}
protected List<HostEntryPair> findKnownHostEntries(
ClientSession clientSession, SocketAddress remoteAddress, Collection<HostEntryPair> knownHosts) {
if (GenericUtils.isEmpty(knownHosts)) {
return Collections.emptyList();
}
Collection<SshdSocketAddress> candidates = resolveHostNetworkIdentities(clientSession, remoteAddress);
boolean debugEnabled = log.isDebugEnabled();
if (debugEnabled) {
log.debug("findKnownHostEntries({})[{}] host network identities: {}",
clientSession, remoteAddress, candidates);
}
if (GenericUtils.isEmpty(candidates)) {
return Collections.emptyList();
}
List<HostEntryPair> matches = new ArrayList<>();
for (HostEntryPair line : knownHosts) {
KnownHostEntry entry = line.getHostEntry();
for (SshdSocketAddress host : candidates) {
try {
if (entry.isHostMatch(host.getHostName(), host.getPort())) {
if (debugEnabled) {
log.debug("findKnownHostEntries({})[{}] matched host={} for entry={}",
clientSession, remoteAddress, host, entry);
}
matches.add(line);
break;
}
} catch (RuntimeException | Error e) {
warn("findKnownHostEntries({})[{}] failed ({}) to check host={} for entry={}: {}",
clientSession, remoteAddress, e.getClass().getSimpleName(),
host, entry.getConfigLine(), e.getMessage(), e);
}
}
}
return matches;
}
/**
* Invoked if any matching host entry has a 'revoked' marker
*
* @param clientSession The {@link ClientSession}
* @param remoteAddress The remote host address
* @param serverKey The presented server {@link PublicKey}
*/
protected void handleRevokedKey(ClientSession clientSession, SocketAddress remoteAddress, PublicKey serverKey) {
log.debug("acceptKnownHostEntry({})[{}] key={}-{} marked as revoked",
clientSession, remoteAddress, KeyUtils.getKeyType(serverKey), KeyUtils.getFingerPrint(serverKey));
}
/**
* Called if failed to reload known hosts - by default invokes
* {@link #acceptUnknownHostKey(ClientSession, SocketAddress, PublicKey)}
*
* @param clientSession The {@link ClientSession}
* @param remoteAddress The remote host address
* @param serverKey The presented server {@link PublicKey}
* @param reason The {@link Throwable} that indicates the reload failure
* @return {@code true} if accept the server key anyway
* @see #acceptUnknownHostKey(ClientSession, SocketAddress, PublicKey)
*/
protected boolean acceptIncompleteHostKeys(
ClientSession clientSession, SocketAddress remoteAddress, PublicKey serverKey, Throwable reason) {
warn("Failed ({}) to reload server keys from {}: {}",
reason.getClass().getSimpleName(), getPath(), reason.getMessage(), reason);
return acceptUnknownHostKey(clientSession, remoteAddress, serverKey);
}
/**
* Invoked if none of the known hosts matches the current one - by default invokes the delegate. If the delegate
* accepts the key, then it is <U>appended</U> to the currently monitored entries and the file is updated
*
* @param clientSession The {@link ClientSession}
* @param remoteAddress The remote host address
* @param serverKey The presented server {@link PublicKey}
* @return {@code true} if accept the server key
* @see #updateKnownHostsFile(ClientSession, SocketAddress, PublicKey, Path, Collection)
* @see #handleKnownHostsFileUpdateFailure(ClientSession, SocketAddress, PublicKey, Path,
* Collection, Throwable)
*/
protected boolean acceptUnknownHostKey(ClientSession clientSession, SocketAddress remoteAddress, PublicKey serverKey) {
if (log.isDebugEnabled()) {
log.debug("acceptUnknownHostKey({}) host={}, key={}",
clientSession, remoteAddress, KeyUtils.getFingerPrint(serverKey));
}
if (delegate.verifyServerKey(clientSession, remoteAddress, serverKey) && !(serverKey instanceof OpenSshCertificate)) {
Path file = getPath();
Collection<HostEntryPair> keys = keysSupplier.get().get();
try {
updateKnownHostsFile(clientSession, remoteAddress, serverKey, file, keys);
} catch (Throwable t) {
handleKnownHostsFileUpdateFailure(clientSession, remoteAddress, serverKey, file, keys, t);
}
return true;
}
return false;
}
/**
* Invoked when {@link #updateKnownHostsFile(ClientSession, SocketAddress, PublicKey, Path, Collection)} fails - by
* default just issues a warning. <B>Note:</B> there is a chance that the file is now corrupted and cannot be
* re-used, so we provide a way to recover it via overriding this method and using the cached entries to re-created
* it.
*
* @param clientSession The {@link ClientSession}
* @param remoteAddress The remote host address
* @param serverKey The server {@link PublicKey} that was attempted to update
* @param file The file {@link Path} to be updated
* @param knownHosts The currently known entries (may be {@code null}/empty
* @param reason The failure reason
*/
protected void handleKnownHostsFileUpdateFailure(
ClientSession clientSession, SocketAddress remoteAddress, PublicKey serverKey,
Path file, Collection<HostEntryPair> knownHosts, Throwable reason) {
warn("handleKnownHostsFileUpdateFailure({})[{}] failed ({}) to update key={}-{} in {}: {}",
clientSession, remoteAddress, reason.getClass().getSimpleName(),
KeyUtils.getKeyType(serverKey), KeyUtils.getFingerPrint(serverKey),
file, reason.getMessage(), reason);
}
/**
* Invoked if a new previously unknown host key has been accepted - by default appends a new entry at the end of the
* currently monitored known hosts file
*
* @param clientSession The {@link ClientSession}
* @param remoteAddress The remote host address
* @param serverKey The server {@link PublicKey} that to update
* @param file The file {@link Path} to be updated
* @param knownHosts The currently cached entries (may be {@code null}/empty)
* @return The generated {@link KnownHostEntry} or {@code null} if nothing updated. If anything
* updated then the file will be re-loaded on next verification regardless of which server is
* verified
* @throws Exception If failed to update the file - <B>Note:</B> in this case the file may be corrupted so
* {@link #handleKnownHostsFileUpdateFailure(ClientSession, SocketAddress, PublicKey, Path, Collection, Throwable)}
* will be called in order to enable recovery of its data
* @see #resetReloadAttributes()
*/
protected KnownHostEntry updateKnownHostsFile(
ClientSession clientSession, SocketAddress remoteAddress, PublicKey serverKey,
Path file, Collection<HostEntryPair> knownHosts)
throws Exception {
KnownHostEntry entry = prepareKnownHostEntry(clientSession, remoteAddress, serverKey);
if (entry == null) {
if (log.isDebugEnabled()) {
log.debug("updateKnownHostsFile({})[{}] no entry generated for key={}",
clientSession, remoteAddress, KeyUtils.getFingerPrint(serverKey));
}
return null;
}
String line = entry.getConfigLine();
byte[] lineData = line.getBytes(StandardCharsets.UTF_8);
boolean reuseExisting = Files.exists(file) && (Files.size(file) > 0);
byte[] eolBytes = IoUtils.getEOLBytes();
synchronized (updateLock) {
try (OutputStream output = reuseExisting
? Files.newOutputStream(file, StandardOpenOption.APPEND)
: Files.newOutputStream(file)) {
if (reuseExisting) {
output.write(eolBytes); // separate from previous lines
}
output.write(lineData);
output.write(eolBytes); // add another separator for trailing lines - in case regular SSH client appends
// to it
}
}
if (log.isDebugEnabled()) {
log.debug("updateKnownHostsFile({}) updated: {}", file, entry);
}
resetReloadAttributes(); // force reload on next verification
return entry;
}
/**
* Invoked by {@link #updateKnownHostsFile(ClientSession, SocketAddress, PublicKey, Path, Collection)} in order to
* generate the host entry to be written
*
* @param clientSession The {@link ClientSession}
* @param remoteAddress The remote host address
* @param serverKey The server {@link PublicKey} that was attempted to update
* @return The {@link KnownHostEntry} to use - if {@code null} then entry is not updated in the file
* @throws Exception If failed to generate the entry - e.g. failed to hash
* @see #resolveHostNetworkIdentities(ClientSession, SocketAddress)
* @see KnownHostEntry#getConfigLine()
*/
protected KnownHostEntry prepareKnownHostEntry(
ClientSession clientSession, SocketAddress remoteAddress, PublicKey serverKey)
throws Exception {
Collection<SshdSocketAddress> patterns = resolveHostNetworkIdentities(clientSession, remoteAddress);
if (GenericUtils.isEmpty(patterns)) {
return null;
}
StringBuilder sb = new StringBuilder(Byte.MAX_VALUE);
Random rnd = null;
for (SshdSocketAddress hostIdentity : patterns) {
if (sb.length() > 0) {
sb.append(',');
}
NamedFactory<Mac> digester = getHostValueDigester(clientSession, remoteAddress, hostIdentity);
if (digester != null) {
if (rnd == null) {
FactoryManager manager = Objects.requireNonNull(clientSession.getFactoryManager(), "No factory manager");
Factory<? extends Random> factory = Objects.requireNonNull(manager.getRandomFactory(), "No random factory");
rnd = Objects.requireNonNull(factory.create(), "No randomizer created");
}
Mac mac = digester.create();
int blockSize = mac.getDefaultBlockSize();
byte[] salt = new byte[blockSize];
rnd.fill(salt);
byte[] digestValue = KnownHostHashValue.calculateHashValue(
hostIdentity.getHostName(), hostIdentity.getPort(), mac, salt);
KnownHostHashValue.append(sb, digester, salt, digestValue);
} else {
KnownHostHashValue.appendHostPattern(sb, hostIdentity.getHostName(), hostIdentity.getPort());
}
}
PublicKeyEntry.appendPublicKeyEntry(sb.append(' '), serverKey);
return KnownHostEntry.parseKnownHostEntry(sb.toString());
}
/**
* Invoked by {@link #prepareKnownHostEntry(ClientSession, SocketAddress, PublicKey)} in order to query whether to
* use a hashed value instead of a plain one for the written host name/address - default returns {@code null} -
* i.e., no hashing
*
* @param clientSession The {@link ClientSession}
* @param remoteAddress The remote host address
* @param hostIdentity The entry's host name/address
* @return The digester {@link NamedFactory} - {@code null} if no hashing is to be made
*/
protected NamedFactory<Mac> getHostValueDigester(
ClientSession clientSession, SocketAddress remoteAddress, SshdSocketAddress hostIdentity) {
return null;
}
/**
* Retrieves the host identities to be used when matching or updating an entry for it - by default returns the
* reported remote address and the original connection target host name/address (if same, then only one value is
* returned)
*
* @param clientSession The {@link ClientSession}
* @param remoteAddress The remote host address
* @return A {@link Collection} of the {@code InetSocketAddress}-es to use - if {@code null}/empty
* then ignored (i.e., no matching is done or no entry is generated)
* @see ClientSession#getConnectAddress()
* @see SshdSocketAddress#toSshdSocketAddress(SocketAddress)
*/
protected Collection<SshdSocketAddress> resolveHostNetworkIdentities(
ClientSession clientSession, SocketAddress remoteAddress) {
/*
* NOTE !!! we do not resolve the fully-qualified name to avoid long DNS timeouts. Instead we use the reported
* peer address and the original connection target host
*/
Collection<SshdSocketAddress> candidates = new TreeSet<>(SshdSocketAddress.BY_HOST_AND_PORT);
candidates.add(SshdSocketAddress.toSshdSocketAddress(remoteAddress));
SocketAddress connectAddress = clientSession.getConnectAddress();
candidates.add(SshdSocketAddress.toSshdSocketAddress(connectAddress));
return candidates;
}
@Override
public boolean acceptModifiedServerKey(
ClientSession clientSession, SocketAddress remoteAddress,
KnownHostEntry entry, PublicKey expected, PublicKey actual)
throws Exception {
ModifiedServerKeyAcceptor acceptor = getModifiedServerKeyAcceptor();
if (acceptor != null) {
return acceptor.acceptModifiedServerKey(clientSession, remoteAddress, entry, expected, actual);
}
log.warn("acceptModifiedServerKey({}) mismatched keys presented by {} for entry={}: expected={}-{}, actual={}-{}",
clientSession, remoteAddress, entry,
KeyUtils.getKeyType(expected), KeyUtils.getFingerPrint(expected),
KeyUtils.getKeyType(actual), KeyUtils.getFingerPrint(actual));
return false;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.