repo_id stringclasses 875
values | size int64 974 38.9k | file_path stringlengths 10 308 | content stringlengths 974 38.9k |
|---|---|---|---|
googleapis/google-cloud-java | 36,470 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/PairwiseMetricInstance.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>
* Pairwise metric instance. Usually one instance corresponds to one row in an
* evaluation dataset.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.PairwiseMetricInstance}
*/
public final class PairwiseMetricInstance extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.PairwiseMetricInstance)
PairwiseMetricInstanceOrBuilder {
private static final long serialVersionUID = 0L;
// Use PairwiseMetricInstance.newBuilder() to construct.
private PairwiseMetricInstance(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private PairwiseMetricInstance() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new PairwiseMetricInstance();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_PairwiseMetricInstance_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_PairwiseMetricInstance_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance.class,
com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance.Builder.class);
}
private int instanceCase_ = 0;
@SuppressWarnings("serial")
private java.lang.Object instance_;
public enum InstanceCase
implements
com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
JSON_INSTANCE(1),
CONTENT_MAP_INSTANCE(2),
INSTANCE_NOT_SET(0);
private final int value;
private InstanceCase(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 InstanceCase valueOf(int value) {
return forNumber(value);
}
public static InstanceCase forNumber(int value) {
switch (value) {
case 1:
return JSON_INSTANCE;
case 2:
return CONTENT_MAP_INSTANCE;
case 0:
return INSTANCE_NOT_SET;
default:
return null;
}
}
public int getNumber() {
return this.value;
}
};
public InstanceCase getInstanceCase() {
return InstanceCase.forNumber(instanceCase_);
}
public static final int JSON_INSTANCE_FIELD_NUMBER = 1;
/**
*
*
* <pre>
* Instance specified as a json string. String key-value pairs are expected
* in the json_instance to render
* PairwiseMetricSpec.instance_prompt_template.
* </pre>
*
* <code>string json_instance = 1;</code>
*
* @return Whether the jsonInstance field is set.
*/
public boolean hasJsonInstance() {
return instanceCase_ == 1;
}
/**
*
*
* <pre>
* Instance specified as a json string. String key-value pairs are expected
* in the json_instance to render
* PairwiseMetricSpec.instance_prompt_template.
* </pre>
*
* <code>string json_instance = 1;</code>
*
* @return The jsonInstance.
*/
public java.lang.String getJsonInstance() {
java.lang.Object ref = "";
if (instanceCase_ == 1) {
ref = instance_;
}
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (instanceCase_ == 1) {
instance_ = s;
}
return s;
}
}
/**
*
*
* <pre>
* Instance specified as a json string. String key-value pairs are expected
* in the json_instance to render
* PairwiseMetricSpec.instance_prompt_template.
* </pre>
*
* <code>string json_instance = 1;</code>
*
* @return The bytes for jsonInstance.
*/
public com.google.protobuf.ByteString getJsonInstanceBytes() {
java.lang.Object ref = "";
if (instanceCase_ == 1) {
ref = instance_;
}
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (instanceCase_ == 1) {
instance_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CONTENT_MAP_INSTANCE_FIELD_NUMBER = 2;
/**
*
*
* <pre>
* Key-value contents for the mutlimodality input, including text, image,
* video, audio, and pdf, etc. The key is placeholder in metric prompt
* template, and the value is the multimodal content.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.ContentMap content_map_instance = 2;</code>
*
* @return Whether the contentMapInstance field is set.
*/
@java.lang.Override
public boolean hasContentMapInstance() {
return instanceCase_ == 2;
}
/**
*
*
* <pre>
* Key-value contents for the mutlimodality input, including text, image,
* video, audio, and pdf, etc. The key is placeholder in metric prompt
* template, and the value is the multimodal content.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.ContentMap content_map_instance = 2;</code>
*
* @return The contentMapInstance.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ContentMap getContentMapInstance() {
if (instanceCase_ == 2) {
return (com.google.cloud.aiplatform.v1beta1.ContentMap) instance_;
}
return com.google.cloud.aiplatform.v1beta1.ContentMap.getDefaultInstance();
}
/**
*
*
* <pre>
* Key-value contents for the mutlimodality input, including text, image,
* video, audio, and pdf, etc. The key is placeholder in metric prompt
* template, and the value is the multimodal content.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.ContentMap content_map_instance = 2;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ContentMapOrBuilder getContentMapInstanceOrBuilder() {
if (instanceCase_ == 2) {
return (com.google.cloud.aiplatform.v1beta1.ContentMap) instance_;
}
return com.google.cloud.aiplatform.v1beta1.ContentMap.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 (instanceCase_ == 1) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, instance_);
}
if (instanceCase_ == 2) {
output.writeMessage(2, (com.google.cloud.aiplatform.v1beta1.ContentMap) instance_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (instanceCase_ == 1) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, instance_);
}
if (instanceCase_ == 2) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
2, (com.google.cloud.aiplatform.v1beta1.ContentMap) instance_);
}
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.PairwiseMetricInstance)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance other =
(com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance) obj;
if (!getInstanceCase().equals(other.getInstanceCase())) return false;
switch (instanceCase_) {
case 1:
if (!getJsonInstance().equals(other.getJsonInstance())) return false;
break;
case 2:
if (!getContentMapInstance().equals(other.getContentMapInstance())) 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 (instanceCase_) {
case 1:
hash = (37 * hash) + JSON_INSTANCE_FIELD_NUMBER;
hash = (53 * hash) + getJsonInstance().hashCode();
break;
case 2:
hash = (37 * hash) + CONTENT_MAP_INSTANCE_FIELD_NUMBER;
hash = (53 * hash) + getContentMapInstance().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance 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.PairwiseMetricInstance parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance 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.PairwiseMetricInstance parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance 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.PairwiseMetricInstance parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance 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.PairwiseMetricInstance parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance 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.PairwiseMetricInstance 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.PairwiseMetricInstance 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.PairwiseMetricInstance 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>
* Pairwise metric instance. Usually one instance corresponds to one row in an
* evaluation dataset.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.PairwiseMetricInstance}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.PairwiseMetricInstance)
com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstanceOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_PairwiseMetricInstance_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_PairwiseMetricInstance_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance.class,
com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (contentMapInstanceBuilder_ != null) {
contentMapInstanceBuilder_.clear();
}
instanceCase_ = 0;
instance_ = 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_PairwiseMetricInstance_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance build() {
com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance buildPartial() {
com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance result =
new com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
buildPartialOneofs(result);
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance result) {
int from_bitField0_ = bitField0_;
}
private void buildPartialOneofs(
com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance result) {
result.instanceCase_ = instanceCase_;
result.instance_ = this.instance_;
if (instanceCase_ == 2 && contentMapInstanceBuilder_ != null) {
result.instance_ = contentMapInstanceBuilder_.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.PairwiseMetricInstance) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance other) {
if (other == com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance.getDefaultInstance())
return this;
switch (other.getInstanceCase()) {
case JSON_INSTANCE:
{
instanceCase_ = 1;
instance_ = other.instance_;
onChanged();
break;
}
case CONTENT_MAP_INSTANCE:
{
mergeContentMapInstance(other.getContentMapInstance());
break;
}
case INSTANCE_NOT_SET:
{
break;
}
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
instanceCase_ = 1;
instance_ = s;
break;
} // case 10
case 18:
{
input.readMessage(
getContentMapInstanceFieldBuilder().getBuilder(), extensionRegistry);
instanceCase_ = 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 instanceCase_ = 0;
private java.lang.Object instance_;
public InstanceCase getInstanceCase() {
return InstanceCase.forNumber(instanceCase_);
}
public Builder clearInstance() {
instanceCase_ = 0;
instance_ = null;
onChanged();
return this;
}
private int bitField0_;
/**
*
*
* <pre>
* Instance specified as a json string. String key-value pairs are expected
* in the json_instance to render
* PairwiseMetricSpec.instance_prompt_template.
* </pre>
*
* <code>string json_instance = 1;</code>
*
* @return Whether the jsonInstance field is set.
*/
@java.lang.Override
public boolean hasJsonInstance() {
return instanceCase_ == 1;
}
/**
*
*
* <pre>
* Instance specified as a json string. String key-value pairs are expected
* in the json_instance to render
* PairwiseMetricSpec.instance_prompt_template.
* </pre>
*
* <code>string json_instance = 1;</code>
*
* @return The jsonInstance.
*/
@java.lang.Override
public java.lang.String getJsonInstance() {
java.lang.Object ref = "";
if (instanceCase_ == 1) {
ref = instance_;
}
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (instanceCase_ == 1) {
instance_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Instance specified as a json string. String key-value pairs are expected
* in the json_instance to render
* PairwiseMetricSpec.instance_prompt_template.
* </pre>
*
* <code>string json_instance = 1;</code>
*
* @return The bytes for jsonInstance.
*/
@java.lang.Override
public com.google.protobuf.ByteString getJsonInstanceBytes() {
java.lang.Object ref = "";
if (instanceCase_ == 1) {
ref = instance_;
}
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (instanceCase_ == 1) {
instance_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Instance specified as a json string. String key-value pairs are expected
* in the json_instance to render
* PairwiseMetricSpec.instance_prompt_template.
* </pre>
*
* <code>string json_instance = 1;</code>
*
* @param value The jsonInstance to set.
* @return This builder for chaining.
*/
public Builder setJsonInstance(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
instanceCase_ = 1;
instance_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Instance specified as a json string. String key-value pairs are expected
* in the json_instance to render
* PairwiseMetricSpec.instance_prompt_template.
* </pre>
*
* <code>string json_instance = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearJsonInstance() {
if (instanceCase_ == 1) {
instanceCase_ = 0;
instance_ = null;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Instance specified as a json string. String key-value pairs are expected
* in the json_instance to render
* PairwiseMetricSpec.instance_prompt_template.
* </pre>
*
* <code>string json_instance = 1;</code>
*
* @param value The bytes for jsonInstance to set.
* @return This builder for chaining.
*/
public Builder setJsonInstanceBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
instanceCase_ = 1;
instance_ = value;
onChanged();
return this;
}
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.ContentMap,
com.google.cloud.aiplatform.v1beta1.ContentMap.Builder,
com.google.cloud.aiplatform.v1beta1.ContentMapOrBuilder>
contentMapInstanceBuilder_;
/**
*
*
* <pre>
* Key-value contents for the mutlimodality input, including text, image,
* video, audio, and pdf, etc. The key is placeholder in metric prompt
* template, and the value is the multimodal content.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.ContentMap content_map_instance = 2;</code>
*
* @return Whether the contentMapInstance field is set.
*/
@java.lang.Override
public boolean hasContentMapInstance() {
return instanceCase_ == 2;
}
/**
*
*
* <pre>
* Key-value contents for the mutlimodality input, including text, image,
* video, audio, and pdf, etc. The key is placeholder in metric prompt
* template, and the value is the multimodal content.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.ContentMap content_map_instance = 2;</code>
*
* @return The contentMapInstance.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ContentMap getContentMapInstance() {
if (contentMapInstanceBuilder_ == null) {
if (instanceCase_ == 2) {
return (com.google.cloud.aiplatform.v1beta1.ContentMap) instance_;
}
return com.google.cloud.aiplatform.v1beta1.ContentMap.getDefaultInstance();
} else {
if (instanceCase_ == 2) {
return contentMapInstanceBuilder_.getMessage();
}
return com.google.cloud.aiplatform.v1beta1.ContentMap.getDefaultInstance();
}
}
/**
*
*
* <pre>
* Key-value contents for the mutlimodality input, including text, image,
* video, audio, and pdf, etc. The key is placeholder in metric prompt
* template, and the value is the multimodal content.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.ContentMap content_map_instance = 2;</code>
*/
public Builder setContentMapInstance(com.google.cloud.aiplatform.v1beta1.ContentMap value) {
if (contentMapInstanceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
instance_ = value;
onChanged();
} else {
contentMapInstanceBuilder_.setMessage(value);
}
instanceCase_ = 2;
return this;
}
/**
*
*
* <pre>
* Key-value contents for the mutlimodality input, including text, image,
* video, audio, and pdf, etc. The key is placeholder in metric prompt
* template, and the value is the multimodal content.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.ContentMap content_map_instance = 2;</code>
*/
public Builder setContentMapInstance(
com.google.cloud.aiplatform.v1beta1.ContentMap.Builder builderForValue) {
if (contentMapInstanceBuilder_ == null) {
instance_ = builderForValue.build();
onChanged();
} else {
contentMapInstanceBuilder_.setMessage(builderForValue.build());
}
instanceCase_ = 2;
return this;
}
/**
*
*
* <pre>
* Key-value contents for the mutlimodality input, including text, image,
* video, audio, and pdf, etc. The key is placeholder in metric prompt
* template, and the value is the multimodal content.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.ContentMap content_map_instance = 2;</code>
*/
public Builder mergeContentMapInstance(com.google.cloud.aiplatform.v1beta1.ContentMap value) {
if (contentMapInstanceBuilder_ == null) {
if (instanceCase_ == 2
&& instance_ != com.google.cloud.aiplatform.v1beta1.ContentMap.getDefaultInstance()) {
instance_ =
com.google.cloud.aiplatform.v1beta1.ContentMap.newBuilder(
(com.google.cloud.aiplatform.v1beta1.ContentMap) instance_)
.mergeFrom(value)
.buildPartial();
} else {
instance_ = value;
}
onChanged();
} else {
if (instanceCase_ == 2) {
contentMapInstanceBuilder_.mergeFrom(value);
} else {
contentMapInstanceBuilder_.setMessage(value);
}
}
instanceCase_ = 2;
return this;
}
/**
*
*
* <pre>
* Key-value contents for the mutlimodality input, including text, image,
* video, audio, and pdf, etc. The key is placeholder in metric prompt
* template, and the value is the multimodal content.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.ContentMap content_map_instance = 2;</code>
*/
public Builder clearContentMapInstance() {
if (contentMapInstanceBuilder_ == null) {
if (instanceCase_ == 2) {
instanceCase_ = 0;
instance_ = null;
onChanged();
}
} else {
if (instanceCase_ == 2) {
instanceCase_ = 0;
instance_ = null;
}
contentMapInstanceBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Key-value contents for the mutlimodality input, including text, image,
* video, audio, and pdf, etc. The key is placeholder in metric prompt
* template, and the value is the multimodal content.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.ContentMap content_map_instance = 2;</code>
*/
public com.google.cloud.aiplatform.v1beta1.ContentMap.Builder getContentMapInstanceBuilder() {
return getContentMapInstanceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Key-value contents for the mutlimodality input, including text, image,
* video, audio, and pdf, etc. The key is placeholder in metric prompt
* template, and the value is the multimodal content.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.ContentMap content_map_instance = 2;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ContentMapOrBuilder
getContentMapInstanceOrBuilder() {
if ((instanceCase_ == 2) && (contentMapInstanceBuilder_ != null)) {
return contentMapInstanceBuilder_.getMessageOrBuilder();
} else {
if (instanceCase_ == 2) {
return (com.google.cloud.aiplatform.v1beta1.ContentMap) instance_;
}
return com.google.cloud.aiplatform.v1beta1.ContentMap.getDefaultInstance();
}
}
/**
*
*
* <pre>
* Key-value contents for the mutlimodality input, including text, image,
* video, audio, and pdf, etc. The key is placeholder in metric prompt
* template, and the value is the multimodal content.
* </pre>
*
* <code>.google.cloud.aiplatform.v1beta1.ContentMap content_map_instance = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.ContentMap,
com.google.cloud.aiplatform.v1beta1.ContentMap.Builder,
com.google.cloud.aiplatform.v1beta1.ContentMapOrBuilder>
getContentMapInstanceFieldBuilder() {
if (contentMapInstanceBuilder_ == null) {
if (!(instanceCase_ == 2)) {
instance_ = com.google.cloud.aiplatform.v1beta1.ContentMap.getDefaultInstance();
}
contentMapInstanceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.ContentMap,
com.google.cloud.aiplatform.v1beta1.ContentMap.Builder,
com.google.cloud.aiplatform.v1beta1.ContentMapOrBuilder>(
(com.google.cloud.aiplatform.v1beta1.ContentMap) instance_,
getParentForChildren(),
isClean());
instance_ = null;
}
instanceCase_ = 2;
onChanged();
return contentMapInstanceBuilder_;
}
@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.PairwiseMetricInstance)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.PairwiseMetricInstance)
private static final com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance();
}
public static com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<PairwiseMetricInstance> PARSER =
new com.google.protobuf.AbstractParser<PairwiseMetricInstance>() {
@java.lang.Override
public PairwiseMetricInstance 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<PairwiseMetricInstance> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<PairwiseMetricInstance> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.PairwiseMetricInstance getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
oracle/nosql | 36,602 | kvmain/src/main/java/oracle/kv/impl/util/DatabaseUtils.java | /*-
* Copyright (C) 2011, 2025 Oracle and/or its affiliates. All rights reserved.
*
* This file was distributed by Oracle as part of a version of Oracle NoSQL
* Database made available at:
*
* http://www.oracle.com/technetwork/database/database-technologies/nosqldb/downloads/index.html
*
* Please see the LICENSE file included in the top-level directory of the
* appropriate version of Oracle NoSQL Database for a copy of the license and
* additional information.
*/
package oracle.kv.impl.util;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import oracle.kv.impl.test.TestHook;
import oracle.kv.impl.test.TestHookExecute;
import oracle.kv.impl.topo.ResourceId;
import oracle.nosql.common.json.JsonUtils;
import oracle.nosql.common.json.ObjectNode;
import com.sleepycat.je.Database;
import com.sleepycat.je.Durability;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.EnvironmentMutableConfig;
import com.sleepycat.je.LockNotAvailableException;
import com.sleepycat.je.LockTimeoutException;
import com.sleepycat.je.VerifyConfig;
import com.sleepycat.je.VerifyError;
import com.sleepycat.je.VerifyListener;
import com.sleepycat.je.VerifySummary;
import com.sleepycat.je.rep.InsufficientAcksException;
import com.sleepycat.je.rep.InsufficientReplicasException;
import com.sleepycat.je.rep.ReplicaWriteException;
import com.sleepycat.je.rep.ReplicatedEnvironment;
import com.sleepycat.je.rep.ReplicationConfig;
import com.sleepycat.je.rep.UnknownMasterException;
import com.sleepycat.je.rep.impl.RepParams;
import com.sleepycat.je.util.DbVerifyLog;
import com.sleepycat.je.util.VerifyLogError;
import com.sleepycat.je.util.VerifyLogListener;
import com.sleepycat.je.util.VerifyLogSummary;
import com.sleepycat.je.utilint.StoppableThread;
/**
* Collection of utilities for JE Database operations
*/
public class DatabaseUtils {
public volatile static TestHook<ReplicatedEnvironment> VERIFY_ERROR_HOOK;
public volatile static TestHook<VerificationThread> VERIFY_INTERRUPT_HOOK;
public volatile static TestHook<Object[]> VERIFY_CORRUPTDATA_HOOK;
public volatile static TestHook<VerificationInfo> VERIFY_CORRUPTFILE_HOOK;
/**
* Prevent instantiation.
*/
private DatabaseUtils() {
}
/**
* Handles an exception opening a replicated DB. Returns
* true if the open should be retried otherwise the exception is
* re-thrown.
*
* @param re the exception from the open
* @param logger a logger
* @param dbName name of DB that was opened
* @return true if the open should be retried
*/
public static boolean handleException(RuntimeException re,
Logger logger,
String dbName) {
try {
throw re;
} catch (ReplicaWriteException | UnknownMasterException de) {
/*
* Master has not had a chance to create the database as
* yet, or the current environment (in the replica, or
* unknown) state is lagging or the node has become a
* replica. Wait, giving the environment
* time to catch up and become current.
*/
logger.log(Level.FINE,
"Failed to open database for {0}. {1}",
new Object[] {dbName, de.getMessage()});
return true;
} catch (InsufficientReplicasException ire) {
logger.log(Level.FINE,
"Insufficient replicas when creating " +
"database {0}. {1}",
new Object[] {dbName, ire.getMessage()});
return true;
} catch (InsufficientAcksException iae) {
logger.log(Level.FINE,
"Insufficient acks when creating database {0}. {1}",
new Object[] {dbName, iae.getMessage()});
/*
* Database has already been created locally, ignore
* the exception.
*/
return false;
} catch (IllegalStateException ise) {
logger.log(Level.FINE,
"Problem accessing database {0}. {1}",
new Object[] {dbName, ise.getMessage()});
return true;
} catch (LockTimeoutException lte) {
logger.log(Level.FINE, "Failed to open database for {0}. {1}",
new Object[] {dbName, lte.getMessage()});
return true;
} catch (LockNotAvailableException lna) {
logger.log(Level.FINE, "Failed to open database for {0}. {1}",
new Object[] {dbName, lna.getMessage()});
return true;
}
}
/*
* Resets the members of the JE replication group, replacing the group
* members with the single member associated with the specified
* environment. This method does what DbResetRepGroup.reset does, but
* using the specified configuration properties rather reading the
* configuration from the environment directory. Note that the
* configuration arguments will be modified.
*
* @param envDir the node's replicated environment directory
* @param envConfig the environment configuration
* @param repConfig the replicated environment configuration
* @see com.sleepycat.je.rep.util.DbResetRepGroup#reset
*/
/* TODO: Consider creating a JE entrypoint to do this */
public static void resetRepGroup(File envDir,
EnvironmentConfig envConfig,
ReplicationConfig repConfig) {
final Durability durability =
new Durability(Durability.SyncPolicy.SYNC,
Durability.SyncPolicy.SYNC,
Durability.ReplicaAckPolicy.NONE);
envConfig.setAllowCreate(true);
envConfig.setTransactional(true);
envConfig.setDurability(durability);
repConfig.setHelperHosts(repConfig.getNodeHostPort());
/* Force the re-initialization upon open. */
repConfig.setConfigParam(RepParams.RESET_REP_GROUP.getName(), "true");
/* Open the environment, thus replacing the group. */
final ReplicatedEnvironment repEnv =
new ReplicatedEnvironment(envDir, repConfig, envConfig);
repEnv.close();
}
/**
* Returns true if the specified database handle needs to be refreshed.
* Specifically, true is returned if db is null or the database's
* environment is null or does not match the current environment.
*
* @param db the database to check, or null
* @param current the current environment
* @return true if the specified database handle needs refreshing
*/
public static boolean needsRefresh(Database db, Environment current) {
if (db == null) {
return true;
}
final Environment dbEnv = db.getEnvironment();
if (dbEnv == null) {
return true;
}
/* If the old and current envs match, no need to refresh */
if (dbEnv == current) {
return false;
}
/* The old and current env are different, the old should be invalid */
if (dbEnv.isValid()) {
throw new IllegalStateException("Database needs refreshing, but " +
"references a valid environment");
}
return true;
}
/**
* Verify data for a node.
* @param env the environment for the node
* @param verifyBtreeConfig properties for verifyBtree
* @param logListener listener for logVerify
* @param logDelay delay between log file reads
* @param logger
* @throws IOException
*/
public static void verifyData(ReplicatedEnvironment env,
VerifyConfig verifyBtreeConfig,
VerifyLogListener logListener,
long logDelay,
Logger logger) throws IOException {
logger.info("Stop running scheduled verification.");
EnvironmentMutableConfig mutableConfig = env.getMutableConfig();
String oldScheduledConfig =
mutableConfig.getConfigParam(EnvironmentConfig.ENV_RUN_VERIFIER);
try {
/* cancel any running scheduled verification */
mutableConfig.setConfigParam(EnvironmentConfig.ENV_RUN_VERIFIER,
"false");
/* for testing */
assert TestHookExecute.doHookIfSet(DatabaseUtils.VERIFY_ERROR_HOOK,
env);
/* btree verification */
if (verifyBtreeConfig != null) {
logger.info("Start JE btree verification.");
env.verify(verifyBtreeConfig);
}
/* log file verification */
if (logListener != null) {
DbVerifyLog logVerify = new DbVerifyLog(env, 0, logListener);
if (logDelay >= 0) {
logVerify.setReadDelay(logDelay, TimeUnit.MILLISECONDS);
}
logger.info("Start JE log verification.");
logVerify.verifyAll();
}
} finally {
/*
* set the configuration for scheduled verification back to previous
* value.
*/
mutableConfig.setConfigParam(EnvironmentConfig.ENV_RUN_VERIFIER,
oldScheduledConfig);
}
}
public static class VerificationThread extends StoppableThread {
private final ReplicatedEnvironment env;
private final VerificationInfo info;
private final VerificationOptions options;
private final Logger logger;
private volatile boolean isShutdown = false;
private static final int THREAD_SOFT_SHUTDOWN_MS = 10000;
private static final int MAXIMUM_CORRUPT_KEYS_NUM = 5000;
public VerificationThread(ReplicatedEnvironment env,
VerificationInfo info,
VerificationOptions options,
Logger logger) {
super("VerificationThread");
this.env = env;
this.info = info;
this.options = options;
this.logger = logger;
}
@Override
public void run() {
try {
VerifyConfig config = null;
if (options.verifyBtree) {
VerifyListener listener = getBtreeVerifyListener();
config = new VerifyConfig();
if (options.btreeDelay >= 0) {
config.setBatchDelay(options.btreeDelay,
TimeUnit.MILLISECONDS);
}
config.setVerifyDataRecords(options.verifyRecord);
config.setVerifySecondaries(options.verifyIndex);
config.setListener(listener);
}
VerifyLogListener logListener = null;
if (options.verifyLog) {
logListener = getLogVerifyListener();
}
verifyData(env, config, logListener, options.logDelay, logger);
} catch (Exception e) {
String errorMsg = "Verification fails. Exception: " +
e.getMessage();
info.setException(errorMsg);
} finally {
/*
* If the state is not COMPLETED but it is not ERROR it means
* that JE didn't call the OnEnd() callback and didn't throw an
* exception either. This is unlikely to happen and would
* indicate a possible bug in JE.
*/
if (info.getCurrentState() !=
VerificationInfo.State.COMPLETED &&
info.getCurrentState() != VerificationInfo.State.ERROR) {
info.setException("UNKNOWN ERROR.");
}
initiateSoftShutdown();
}
}
@Override
protected synchronized int initiateSoftShutdown() {
isShutdown = true;
notifyAll();
return THREAD_SOFT_SHUTDOWN_MS;
}
protected synchronized boolean checkForDone() {
return isShutdown;
}
@Override
protected Logger getLogger() {
return logger;
}
private VerifyLogListener getLogVerifyListener() {
VerifyLogListener listener = new VerifyLogListener() {
@Override
public boolean onBegin(int totalFiles) {
info.startVerify();
return !isShutdown;
}
@Override
public void onEnd(VerifyLogSummary summary) {
info.completeVerify();
}
@Override
public boolean onFile(long file,
List<VerifyLogError> errors,
boolean deleted) {
if (!errors.isEmpty()) {
/*
* Copy errors into a new ArrayList because
* JE reuses the input list.
*/
info.logFileErrorList.put(file, new ArrayList<>(errors));
}
return !isShutdown;
}
@Override
public boolean onRead(long file,
int bytesRead) {
return !isShutdown;
}
};
return listener;
}
private VerifyListener getBtreeVerifyListener() {
VerifyListener listener = new VerifyListener() {
@Override
public boolean onBegin() {
info.startVerify();
assert TestHookExecute.
doHookIfSet(DatabaseUtils.VERIFY_INTERRUPT_HOOK, null);
return !isShutdown;
}
@Override
public boolean
onDatabase(String dbName,
List<com.sleepycat.je.VerifyError> errors) {
if (errors != null && !errors.isEmpty()) {
info.dbErrorList.
put(dbName, new ArrayList<VerifyError>(errors));
}
return !isShutdown;
}
@Override
public void onEnd(VerifySummary summary) {
if (!options.verifyLog) {
info.completeVerify();
}
if (options.showMissingFiles) {
assert TestHookExecute.
doHookIfSet(DatabaseUtils.VERIFY_CORRUPTFILE_HOOK,
info);
info.missingFilesReferenced.
addAll(summary.getMissingFilesReferenced());
info.reservedFilesReferenced.
addAll(summary.getReservedFilesReferenced());
info.reservedFilesRepaired.
addAll(summary.getReservedFilesRepaired());
}
}
@Override
public boolean
onOtherError(List<com.sleepycat.je.VerifyError> errors) {
info.otherErrorList.addAll(errors);
return !isShutdown;
}
@Override
public boolean
onRecord(String dbName,
byte[] priKey,
byte[] secKey,
List<com.sleepycat.je.VerifyError> errors) {
if (errors != null && !errors.isEmpty()) {
if (info.recordErrorList.size() <
MAXIMUM_CORRUPT_KEYS_NUM) {
List<byte[]> keys = new ArrayList<byte[]>();
keys.add(dbName.getBytes());
keys.add(priKey);
keys.add(secKey);
info.recordErrorList.put(keys,
new ArrayList<VerifyError>(errors));
} else {
/* stop verification since the number of
* corrupt keys has exceed the limit. */
info.moreCorruptKeys = true;
return false;
}
}
return !isShutdown;
}
};
return listener;
}
}
/**
* Manages verification of databases on a node, which can be a rn or admin.
* Only one running verification is allowed.
*/
public static class VerificationManager {
private VerificationInfo info; /* Verification status and result */
private volatile VerificationThread curThread;
private ReplicatedEnvironment env;
private final ResourceId id;
private final Logger logger;
private VerificationOptions curOptions;
private int curPlanId;
public VerificationManager(ResourceId id,
Logger logger) {
this.id = id;
this.logger = logger;
info = null;
}
public synchronized void setEnv(ReplicatedEnvironment env) {
this.env = env;
}
public synchronized VerificationInfo getInfo() {
return info;
}
public synchronized VerificationThread getThread() {
return curThread;
}
/* Kicks off a verification, or checks the status of the running
* verification when options is null. */
public synchronized VerificationInfo
startAndPollVerification(VerificationOptions options,
int planId) {
if (env == null) {
throw new IllegalStateException("Environment cannot be null.");
}
if (info != null) {
if (planId < curPlanId) {
/* An old plan polls for status. Return a result notifying
* the old plan that its verification has been interrupted
* by a new plan. */
VerificationInfo oldInfo =
new VerificationInfo(false, false, id);
oldInfo.interruptedByAnotherPlan = true;
oldInfo.completeVerify();
return oldInfo;
}
if (!info.getCurrentState().isDone()) {
/*verification is in progress*/
if (planId != curPlanId) {
if (options != null) {
/* A new plan initiates a new verification, so
* interrupt the current verification and
* starts a new one. */
interruptVerification();
startNewVerification(options, planId);
return info;
}
/* The node crushed before and there are two or more
* verification plans running in parallel. Now the newer
* plan polls for status, so ask it to resend
* options. */
return null;
}
return info;
}
/*check the completed time for the last verification.*/
long curTime = System.currentTimeMillis();
if ((options == null && curPlanId == planId) ||
(options != null &&
curTime - info.getLastVerifyTime() < options.expiredTime &&
options.equals(curOptions) && !info.isInterrupted)) {
return info;
}
}
if (options == null) {
/* ask admin to send options. */
curPlanId = Math.max(planId, curPlanId);
info = null;
return info;
}
assert TestHookExecute.doHookIfSet(
DatabaseUtils.VERIFY_CORRUPTDATA_HOOK,
new Object[] { env, id });
startNewVerification(options, planId);
return info;
}
private void startNewVerification(VerificationOptions options,
int planId) {
info = new VerificationInfo(options.verifyBtree, options.verifyLog,
id);
curThread = new VerificationThread(env, info, options, logger);
/*start verify.*/
curOptions = options;
curPlanId = planId;
curThread.start();
}
/* Interrupts the running verification. */
public synchronized boolean interruptVerification() {
if (curThread == null || info == null ||
info.getCurrentState().isDone()) {
return false;
}
try {
curThread.join(curThread.initiateSoftShutdown());
} catch (InterruptedException e) {
/* ignore */
}
info.isInterrupted = true;
return true;
}
}
public static class VerificationInfo implements Serializable {
private static final long serialVersionUID = 1L;
public static enum State {
NOT_STARTED, /* verification requested but not started yet */
INPROGRESS,
COMPLETED() {
@Override
public boolean isDone() { return true; }
},
ERROR() {
@Override
public boolean isDone() { return true; }
};
public boolean isDone() { return false; }
}
private State currentState = State.NOT_STARTED;
private long completeTime = 0l;
private String exceptionMsg = null;
public final boolean verifyBtree;
public final boolean verifyLog;
public final ResourceId id;
public final Map<List<byte[]>, List<VerifyError>> recordErrorList =
new HashMap<>();
public final Map<String, List<VerifyError>> dbErrorList =
new HashMap<>();
public final List<VerifyError> otherErrorList = new ArrayList<>();
public final Map<Long, List<VerifyLogError>> logFileErrorList =
new HashMap<>();
public final Set<Long> missingFilesReferenced = new HashSet<>();
public final Set<Long> reservedFilesReferenced = new HashSet<>();
public final Set<Long> reservedFilesRepaired = new HashSet<>();
public boolean moreCorruptKeys = false;
public boolean isInterrupted = false;
public boolean interruptedByAnotherPlan = false;
public VerificationInfo(boolean verifyBtree,
boolean verifyLog,
ResourceId id) {
this.verifyBtree = verifyBtree;
this.verifyLog = verifyLog;
this.id = id;
}
public void setNotStarted() {
currentState = State.NOT_STARTED;
}
public State getCurrentState() {
return currentState;
}
public void startVerify() {
currentState = State.INPROGRESS;
}
public void completeVerify() {
currentState = State.COMPLETED;
completeTime = System.currentTimeMillis();
}
public void setException(String errorMsg) {
currentState = State.ERROR;
this.exceptionMsg = errorMsg;
completeTime = System.currentTimeMillis();
}
public long getLastVerifyTime() {
return completeTime;
}
public String getExceptionMsg() {
return exceptionMsg;
}
public boolean noBtreeCorruptions() {
return recordErrorList.isEmpty() && dbErrorList.isEmpty() &&
otherErrorList.isEmpty() &&
missingFilesReferenced.isEmpty() &&
reservedFilesReferenced.isEmpty() &&
reservedFilesRepaired.isEmpty();
}
public boolean noLogFileCorruptions() {
return logFileErrorList.isEmpty();
}
public ObjectNode getJson(boolean showMissingFiles) {
ObjectNode jsonNodeTop = JsonUtils.createObjectNode();
ObjectNode jsonNode = jsonNodeTop.putObject("" + id);
if (getCurrentState() == VerificationInfo.State.ERROR) {
jsonNode.put("Verification failed. Error", getExceptionMsg());
return jsonNodeTop;
}
if (interruptedByAnotherPlan) {
jsonNode.put("INTERRUPTED", "Verification interrupted " +
"by another plan.");
return jsonNodeTop;
}
if (isInterrupted) {
jsonNode.put("INTERRUPTED", "Verification interrupted " +
"by users.");
}
if (verifyBtree) {
if (!noBtreeCorruptions()) {
ObjectNode jsonBtreeVerify =
jsonNode.putObject("Btree Verify");
if (!dbErrorList.isEmpty()) {
putDbCorruptionJson(jsonBtreeVerify);
}
putKeyCorruptionJson(jsonBtreeVerify);
if (showMissingFiles) {
putFileCorruptionJson(jsonBtreeVerify);
}
if (!otherErrorList.isEmpty()) {
putOtherErrorJson(jsonBtreeVerify);
}
} else {
jsonNode.put("Btree Verify", "No Btree Corruptions");
}
}
if (verifyLog) {
if (!noLogFileCorruptions()) {
putVerifyLogJson(jsonNode);
} else {
jsonNode.put("Log File Verify", "No Log File Corruptions");
}
}
return jsonNodeTop;
}
private void putDbCorruptionJson(ObjectNode jsonBtreeVerify) {
ObjectNode jsonDbErrors = jsonBtreeVerify.
putObject("Database corruptions");
jsonDbErrors.put("Total Number", dbErrorList.size());
ObjectNode jsonErrorList = jsonDbErrors.putObject("List");
for (String dbName : dbErrorList.keySet()) {
List<VerifyError> errors = dbErrorList.get(dbName);
ObjectNode jsonDbName = jsonErrorList.putObject(dbName);
int i = 1;
for (VerifyError error : errors) {
jsonDbName.put("" + i, error.getMessage());
i++;
}
}
}
private void putKeyCorruptionJson(ObjectNode jsonBtreeVerify) {
if (!recordErrorList.isEmpty()) {
ObjectNode jsonCorruptKeys =
jsonBtreeVerify.putObject("Corrupt Keys");
jsonCorruptKeys.put("Total number",
recordErrorList.size());
ObjectNode jsonErrorList = jsonCorruptKeys.putObject("List");
for (List<byte[]> keys : recordErrorList.keySet()) {
List<VerifyError> errors = recordErrorList.get(keys);
ObjectNode jsonKey = jsonErrorList.
putObject("dbName: " + (keys.get(0) == null ?
"null" : new String(keys.get(0))) +
" priKey: " + (keys.get(1) == null ?
"null" : new String(keys.get(1))) +
" secKey: " + (keys.get(2) == null ?
"null" : new String(keys.get(2))));
int i = 1;
for (VerifyError error : errors) {
jsonKey.put("" + i, error.getProblem() + ": " +
error.getMessage());
i++;
}
}
if (moreCorruptKeys) {
jsonErrorList.putObject("Number of corrupt keys " +
"exceeds the limit. There are more to report. " +
"Please fix the reported corruption first and run " +
"verification again.");
}
}
}
private void putFileCorruptionJson(ObjectNode jsonBtreeVerify) {
if (!missingFilesReferenced.isEmpty() ||
!reservedFilesReferenced.isEmpty() ||
!reservedFilesRepaired.isEmpty()) {
ObjectNode jsonMissingFile = jsonBtreeVerify.
putObject("Missing Files Referenced");
jsonMissingFile.put("Total number",
missingFilesReferenced.size());
if (!missingFilesReferenced.isEmpty()) {
ObjectNode jsonCorruptFilesList = jsonMissingFile.
putObject("List");
int i = 1;
for (Long file : missingFilesReferenced) {
jsonCorruptFilesList.put("" + i, "" + file);
i++;
}
}
ObjectNode jsonReservedFile = jsonBtreeVerify.
putObject("Reserved Files Referenced");
jsonReservedFile.put("Total number",
reservedFilesReferenced.size());
if (!reservedFilesReferenced.isEmpty()) {
ObjectNode jsonReservedFilesList = jsonReservedFile.
putObject("List");
int i = 1;
for (Long file : reservedFilesReferenced) {
jsonReservedFilesList.put("" + i, "" + file);
i++;
}
}
ObjectNode jsonRepairedFile =
jsonBtreeVerify.putObject("Reserved Files " +
"Repaired");
jsonRepairedFile.put("Total number",
reservedFilesRepaired.size());
if (!reservedFilesRepaired.isEmpty()) {
ObjectNode jsonRepairedFilesList = jsonRepairedFile.
putObject("List");
int i = 1;
for (Long file : reservedFilesRepaired) {
jsonRepairedFilesList.put("" + i, "" + file);
i++;
}
}
}
}
private void putOtherErrorJson(ObjectNode jsonBtreeVerify) {
ObjectNode jsonOtherErrors = jsonBtreeVerify.
putObject("Other Errors");
jsonOtherErrors.put("Total number", otherErrorList.size());
ObjectNode jsonOtherErrorList = jsonOtherErrors.putObject("List");
int i = 1;
for (VerifyError error : otherErrorList) {
jsonOtherErrorList.put("" + i, error.getMessage());
i++;
}
}
private void putVerifyLogJson(ObjectNode jsonNode) {
ObjectNode jsonLogVerify = jsonNode.putObject("Log File Verify");
ObjectNode jsonLogError = jsonLogVerify.putObject("Log File Error");
jsonLogError.put("Total number", logFileErrorList.size());
ObjectNode jsonLogErrorList = jsonLogError.putObject("List");
for (Long file : logFileErrorList.keySet()) {
ObjectNode jsonLogName = jsonLogErrorList.
putObject("Log File " + file);
int i = 1;
for (VerifyLogError error : logFileErrorList.get(file)) {
jsonLogName.put("" + i, error.getMessage());
i++;
}
}
}
}
public static class VerificationOptions implements Serializable {
/**
* Default values for verification options used by Admin CLI and
* KVLocal API
*/
public static final boolean DEFAULT_VERIFY_LOG = true;
public static final boolean DEFAULT_VERIFY_BTREE = true;
public static final boolean DEFAULT_VERIFY_INDEX = true;
public static final boolean DEFAULT_VERIFY_DATARECORD = false;
public static final long DEFAULT_BTREE_DELAY = -1;
public static final long DEFAULT_LOG_DELAY = -1;
public static final long DEFAULT_EXPIRED_TIME = 10 * 60000;/*10 mins*/
public static final boolean DEFAULT_SHOW_MISSING_FILES = false;
/**
*
*/
private static final long serialVersionUID = 1L;
public final boolean verifyBtree;
public final boolean verifyLog;
public final boolean verifyIndex;
public final boolean verifyRecord;
public final long btreeDelay;
public final long logDelay;
public final long expiredTime;
public final boolean showMissingFiles;
/**
* Options for verification set by users
* @param verifyBtree verifies the b-tree in memory containing
* valid references if it's true
* @param verifyLog verifies the checksum of each data record
* in JE log files if it's true
* @param verifyIndex runs verification on index. It can be combined
* with verifyBtree.
* @param verifyRecord verifies data records on disk. It can be combined
* with verifyBtree.
* @param btreeDelay configures the delay time between batches
* (1000 records) for verifyBtree
* @param logDelay configures the the delay time between file reads
* for verifyLog
* @param expiredTime the amount of time for which an existing
* verification will be considered valid.
* @param showMissingFiles shows the corrupt files, including missing
* files and reserved files.
*/
public VerificationOptions(boolean verifyBtree,
boolean verifyLog,
boolean verifyIndex,
boolean verifyRecord,
long btreeDelay,
long logDelay,
long expiredTime,
boolean showMissingFiles) {
this.verifyBtree = verifyBtree;
this.verifyLog = verifyLog;
this.verifyIndex = verifyIndex;
this.verifyRecord = verifyRecord;
this.btreeDelay = btreeDelay;
this.logDelay = logDelay;
this.expiredTime = expiredTime;
this.showMissingFiles = showMissingFiles;
}
public boolean equals(VerificationOptions other) {
if (other == null) {
return false;
}
return verifyBtree == other.verifyBtree &&
verifyLog == other.verifyLog &&
verifyIndex == other.verifyIndex &&
verifyRecord == other.verifyRecord &&
btreeDelay == other.btreeDelay &&
logDelay == other.logDelay &&
showMissingFiles == other.showMissingFiles;
}
}
}
|
googleapis/google-cloud-java | 36,755 | java-service-management/google-cloud-service-management/src/main/java/com/google/cloud/api/servicemanagement/v1/stub/GrpcServiceManagerStub.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.api.servicemanagement.v1.stub;
import static com.google.cloud.api.servicemanagement.v1.ServiceManagerClient.ListServiceConfigsPagedResponse;
import static com.google.cloud.api.servicemanagement.v1.ServiceManagerClient.ListServiceRolloutsPagedResponse;
import static com.google.cloud.api.servicemanagement.v1.ServiceManagerClient.ListServicesPagedResponse;
import com.google.api.Service;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.core.BackgroundResourceAggregation;
import com.google.api.gax.grpc.GrpcCallSettings;
import com.google.api.gax.grpc.GrpcStubCallableFactory;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.OperationCallable;
import com.google.api.gax.rpc.RequestParamsBuilder;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.api.servicemanagement.v1.CreateServiceConfigRequest;
import com.google.api.servicemanagement.v1.CreateServiceRequest;
import com.google.api.servicemanagement.v1.CreateServiceRolloutRequest;
import com.google.api.servicemanagement.v1.DeleteServiceRequest;
import com.google.api.servicemanagement.v1.GenerateConfigReportRequest;
import com.google.api.servicemanagement.v1.GenerateConfigReportResponse;
import com.google.api.servicemanagement.v1.GetServiceConfigRequest;
import com.google.api.servicemanagement.v1.GetServiceRequest;
import com.google.api.servicemanagement.v1.GetServiceRolloutRequest;
import com.google.api.servicemanagement.v1.ListServiceConfigsRequest;
import com.google.api.servicemanagement.v1.ListServiceConfigsResponse;
import com.google.api.servicemanagement.v1.ListServiceRolloutsRequest;
import com.google.api.servicemanagement.v1.ListServiceRolloutsResponse;
import com.google.api.servicemanagement.v1.ListServicesRequest;
import com.google.api.servicemanagement.v1.ListServicesResponse;
import com.google.api.servicemanagement.v1.ManagedService;
import com.google.api.servicemanagement.v1.OperationMetadata;
import com.google.api.servicemanagement.v1.Rollout;
import com.google.api.servicemanagement.v1.SubmitConfigSourceRequest;
import com.google.api.servicemanagement.v1.SubmitConfigSourceResponse;
import com.google.api.servicemanagement.v1.UndeleteServiceRequest;
import com.google.api.servicemanagement.v1.UndeleteServiceResponse;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.iam.v1.TestIamPermissionsRequest;
import com.google.iam.v1.TestIamPermissionsResponse;
import com.google.longrunning.Operation;
import com.google.longrunning.stub.GrpcOperationsStub;
import com.google.protobuf.Empty;
import io.grpc.MethodDescriptor;
import io.grpc.protobuf.ProtoUtils;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* gRPC stub implementation for the ServiceManager service API.
*
* <p>This class is for advanced usage and reflects the underlying API directly.
*/
@Generated("by gapic-generator-java")
public class GrpcServiceManagerStub extends ServiceManagerStub {
private static final MethodDescriptor<ListServicesRequest, ListServicesResponse>
listServicesMethodDescriptor =
MethodDescriptor.<ListServicesRequest, ListServicesResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.api.servicemanagement.v1.ServiceManager/ListServices")
.setRequestMarshaller(ProtoUtils.marshaller(ListServicesRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(ListServicesResponse.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<GetServiceRequest, ManagedService>
getServiceMethodDescriptor =
MethodDescriptor.<GetServiceRequest, ManagedService>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.api.servicemanagement.v1.ServiceManager/GetService")
.setRequestMarshaller(ProtoUtils.marshaller(GetServiceRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(ManagedService.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<CreateServiceRequest, Operation>
createServiceMethodDescriptor =
MethodDescriptor.<CreateServiceRequest, Operation>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.api.servicemanagement.v1.ServiceManager/CreateService")
.setRequestMarshaller(
ProtoUtils.marshaller(CreateServiceRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<DeleteServiceRequest, Operation>
deleteServiceMethodDescriptor =
MethodDescriptor.<DeleteServiceRequest, Operation>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.api.servicemanagement.v1.ServiceManager/DeleteService")
.setRequestMarshaller(
ProtoUtils.marshaller(DeleteServiceRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<UndeleteServiceRequest, Operation>
undeleteServiceMethodDescriptor =
MethodDescriptor.<UndeleteServiceRequest, Operation>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.api.servicemanagement.v1.ServiceManager/UndeleteService")
.setRequestMarshaller(
ProtoUtils.marshaller(UndeleteServiceRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<ListServiceConfigsRequest, ListServiceConfigsResponse>
listServiceConfigsMethodDescriptor =
MethodDescriptor.<ListServiceConfigsRequest, ListServiceConfigsResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.api.servicemanagement.v1.ServiceManager/ListServiceConfigs")
.setRequestMarshaller(
ProtoUtils.marshaller(ListServiceConfigsRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(ListServiceConfigsResponse.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<GetServiceConfigRequest, Service>
getServiceConfigMethodDescriptor =
MethodDescriptor.<GetServiceConfigRequest, Service>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.api.servicemanagement.v1.ServiceManager/GetServiceConfig")
.setRequestMarshaller(
ProtoUtils.marshaller(GetServiceConfigRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Service.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<CreateServiceConfigRequest, Service>
createServiceConfigMethodDescriptor =
MethodDescriptor.<CreateServiceConfigRequest, Service>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.api.servicemanagement.v1.ServiceManager/CreateServiceConfig")
.setRequestMarshaller(
ProtoUtils.marshaller(CreateServiceConfigRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Service.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<SubmitConfigSourceRequest, Operation>
submitConfigSourceMethodDescriptor =
MethodDescriptor.<SubmitConfigSourceRequest, Operation>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.api.servicemanagement.v1.ServiceManager/SubmitConfigSource")
.setRequestMarshaller(
ProtoUtils.marshaller(SubmitConfigSourceRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<ListServiceRolloutsRequest, ListServiceRolloutsResponse>
listServiceRolloutsMethodDescriptor =
MethodDescriptor.<ListServiceRolloutsRequest, ListServiceRolloutsResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.api.servicemanagement.v1.ServiceManager/ListServiceRollouts")
.setRequestMarshaller(
ProtoUtils.marshaller(ListServiceRolloutsRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(ListServiceRolloutsResponse.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<GetServiceRolloutRequest, Rollout>
getServiceRolloutMethodDescriptor =
MethodDescriptor.<GetServiceRolloutRequest, Rollout>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.api.servicemanagement.v1.ServiceManager/GetServiceRollout")
.setRequestMarshaller(
ProtoUtils.marshaller(GetServiceRolloutRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Rollout.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<CreateServiceRolloutRequest, Operation>
createServiceRolloutMethodDescriptor =
MethodDescriptor.<CreateServiceRolloutRequest, Operation>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.api.servicemanagement.v1.ServiceManager/CreateServiceRollout")
.setRequestMarshaller(
ProtoUtils.marshaller(CreateServiceRolloutRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Operation.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<GenerateConfigReportRequest, GenerateConfigReportResponse>
generateConfigReportMethodDescriptor =
MethodDescriptor.<GenerateConfigReportRequest, GenerateConfigReportResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.api.servicemanagement.v1.ServiceManager/GenerateConfigReport")
.setRequestMarshaller(
ProtoUtils.marshaller(GenerateConfigReportRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(GenerateConfigReportResponse.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<SetIamPolicyRequest, Policy> setIamPolicyMethodDescriptor =
MethodDescriptor.<SetIamPolicyRequest, Policy>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.iam.v1.IAMPolicy/SetIamPolicy")
.setRequestMarshaller(ProtoUtils.marshaller(SetIamPolicyRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<GetIamPolicyRequest, Policy> getIamPolicyMethodDescriptor =
MethodDescriptor.<GetIamPolicyRequest, Policy>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.iam.v1.IAMPolicy/GetIamPolicy")
.setRequestMarshaller(ProtoUtils.marshaller(GetIamPolicyRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsMethodDescriptor =
MethodDescriptor.<TestIamPermissionsRequest, TestIamPermissionsResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.iam.v1.IAMPolicy/TestIamPermissions")
.setRequestMarshaller(
ProtoUtils.marshaller(TestIamPermissionsRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(TestIamPermissionsResponse.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private final UnaryCallable<ListServicesRequest, ListServicesResponse> listServicesCallable;
private final UnaryCallable<ListServicesRequest, ListServicesPagedResponse>
listServicesPagedCallable;
private final UnaryCallable<GetServiceRequest, ManagedService> getServiceCallable;
private final UnaryCallable<CreateServiceRequest, Operation> createServiceCallable;
private final OperationCallable<CreateServiceRequest, ManagedService, OperationMetadata>
createServiceOperationCallable;
private final UnaryCallable<DeleteServiceRequest, Operation> deleteServiceCallable;
private final OperationCallable<DeleteServiceRequest, Empty, OperationMetadata>
deleteServiceOperationCallable;
private final UnaryCallable<UndeleteServiceRequest, Operation> undeleteServiceCallable;
private final OperationCallable<
UndeleteServiceRequest, UndeleteServiceResponse, OperationMetadata>
undeleteServiceOperationCallable;
private final UnaryCallable<ListServiceConfigsRequest, ListServiceConfigsResponse>
listServiceConfigsCallable;
private final UnaryCallable<ListServiceConfigsRequest, ListServiceConfigsPagedResponse>
listServiceConfigsPagedCallable;
private final UnaryCallable<GetServiceConfigRequest, Service> getServiceConfigCallable;
private final UnaryCallable<CreateServiceConfigRequest, Service> createServiceConfigCallable;
private final UnaryCallable<SubmitConfigSourceRequest, Operation> submitConfigSourceCallable;
private final OperationCallable<
SubmitConfigSourceRequest, SubmitConfigSourceResponse, OperationMetadata>
submitConfigSourceOperationCallable;
private final UnaryCallable<ListServiceRolloutsRequest, ListServiceRolloutsResponse>
listServiceRolloutsCallable;
private final UnaryCallable<ListServiceRolloutsRequest, ListServiceRolloutsPagedResponse>
listServiceRolloutsPagedCallable;
private final UnaryCallable<GetServiceRolloutRequest, Rollout> getServiceRolloutCallable;
private final UnaryCallable<CreateServiceRolloutRequest, Operation> createServiceRolloutCallable;
private final OperationCallable<CreateServiceRolloutRequest, Rollout, OperationMetadata>
createServiceRolloutOperationCallable;
private final UnaryCallable<GenerateConfigReportRequest, GenerateConfigReportResponse>
generateConfigReportCallable;
private final UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable;
private final UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable;
private final UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsCallable;
private final BackgroundResource backgroundResources;
private final GrpcOperationsStub operationsStub;
private final GrpcStubCallableFactory callableFactory;
public static final GrpcServiceManagerStub create(ServiceManagerStubSettings settings)
throws IOException {
return new GrpcServiceManagerStub(settings, ClientContext.create(settings));
}
public static final GrpcServiceManagerStub create(ClientContext clientContext)
throws IOException {
return new GrpcServiceManagerStub(
ServiceManagerStubSettings.newBuilder().build(), clientContext);
}
public static final GrpcServiceManagerStub create(
ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException {
return new GrpcServiceManagerStub(
ServiceManagerStubSettings.newBuilder().build(), clientContext, callableFactory);
}
/**
* Constructs an instance of GrpcServiceManagerStub, 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 GrpcServiceManagerStub(ServiceManagerStubSettings settings, ClientContext clientContext)
throws IOException {
this(settings, clientContext, new GrpcServiceManagerCallableFactory());
}
/**
* Constructs an instance of GrpcServiceManagerStub, 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 GrpcServiceManagerStub(
ServiceManagerStubSettings settings,
ClientContext clientContext,
GrpcStubCallableFactory callableFactory)
throws IOException {
this.callableFactory = callableFactory;
this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory);
GrpcCallSettings<ListServicesRequest, ListServicesResponse> listServicesTransportSettings =
GrpcCallSettings.<ListServicesRequest, ListServicesResponse>newBuilder()
.setMethodDescriptor(listServicesMethodDescriptor)
.build();
GrpcCallSettings<GetServiceRequest, ManagedService> getServiceTransportSettings =
GrpcCallSettings.<GetServiceRequest, ManagedService>newBuilder()
.setMethodDescriptor(getServiceMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("service_name", String.valueOf(request.getServiceName()));
return builder.build();
})
.build();
GrpcCallSettings<CreateServiceRequest, Operation> createServiceTransportSettings =
GrpcCallSettings.<CreateServiceRequest, Operation>newBuilder()
.setMethodDescriptor(createServiceMethodDescriptor)
.build();
GrpcCallSettings<DeleteServiceRequest, Operation> deleteServiceTransportSettings =
GrpcCallSettings.<DeleteServiceRequest, Operation>newBuilder()
.setMethodDescriptor(deleteServiceMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("service_name", String.valueOf(request.getServiceName()));
return builder.build();
})
.build();
GrpcCallSettings<UndeleteServiceRequest, Operation> undeleteServiceTransportSettings =
GrpcCallSettings.<UndeleteServiceRequest, Operation>newBuilder()
.setMethodDescriptor(undeleteServiceMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("service_name", String.valueOf(request.getServiceName()));
return builder.build();
})
.build();
GrpcCallSettings<ListServiceConfigsRequest, ListServiceConfigsResponse>
listServiceConfigsTransportSettings =
GrpcCallSettings.<ListServiceConfigsRequest, ListServiceConfigsResponse>newBuilder()
.setMethodDescriptor(listServiceConfigsMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("service_name", String.valueOf(request.getServiceName()));
return builder.build();
})
.build();
GrpcCallSettings<GetServiceConfigRequest, Service> getServiceConfigTransportSettings =
GrpcCallSettings.<GetServiceConfigRequest, Service>newBuilder()
.setMethodDescriptor(getServiceConfigMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("config_id", String.valueOf(request.getConfigId()));
builder.add("service_name", String.valueOf(request.getServiceName()));
return builder.build();
})
.build();
GrpcCallSettings<CreateServiceConfigRequest, Service> createServiceConfigTransportSettings =
GrpcCallSettings.<CreateServiceConfigRequest, Service>newBuilder()
.setMethodDescriptor(createServiceConfigMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("service_name", String.valueOf(request.getServiceName()));
return builder.build();
})
.build();
GrpcCallSettings<SubmitConfigSourceRequest, Operation> submitConfigSourceTransportSettings =
GrpcCallSettings.<SubmitConfigSourceRequest, Operation>newBuilder()
.setMethodDescriptor(submitConfigSourceMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("service_name", String.valueOf(request.getServiceName()));
return builder.build();
})
.build();
GrpcCallSettings<ListServiceRolloutsRequest, ListServiceRolloutsResponse>
listServiceRolloutsTransportSettings =
GrpcCallSettings.<ListServiceRolloutsRequest, ListServiceRolloutsResponse>newBuilder()
.setMethodDescriptor(listServiceRolloutsMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("service_name", String.valueOf(request.getServiceName()));
return builder.build();
})
.build();
GrpcCallSettings<GetServiceRolloutRequest, Rollout> getServiceRolloutTransportSettings =
GrpcCallSettings.<GetServiceRolloutRequest, Rollout>newBuilder()
.setMethodDescriptor(getServiceRolloutMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("rollout_id", String.valueOf(request.getRolloutId()));
builder.add("service_name", String.valueOf(request.getServiceName()));
return builder.build();
})
.build();
GrpcCallSettings<CreateServiceRolloutRequest, Operation> createServiceRolloutTransportSettings =
GrpcCallSettings.<CreateServiceRolloutRequest, Operation>newBuilder()
.setMethodDescriptor(createServiceRolloutMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("service_name", String.valueOf(request.getServiceName()));
return builder.build();
})
.build();
GrpcCallSettings<GenerateConfigReportRequest, GenerateConfigReportResponse>
generateConfigReportTransportSettings =
GrpcCallSettings.<GenerateConfigReportRequest, GenerateConfigReportResponse>newBuilder()
.setMethodDescriptor(generateConfigReportMethodDescriptor)
.build();
GrpcCallSettings<SetIamPolicyRequest, Policy> setIamPolicyTransportSettings =
GrpcCallSettings.<SetIamPolicyRequest, Policy>newBuilder()
.setMethodDescriptor(setIamPolicyMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("resource", String.valueOf(request.getResource()));
return builder.build();
})
.build();
GrpcCallSettings<GetIamPolicyRequest, Policy> getIamPolicyTransportSettings =
GrpcCallSettings.<GetIamPolicyRequest, Policy>newBuilder()
.setMethodDescriptor(getIamPolicyMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("resource", String.valueOf(request.getResource()));
return builder.build();
})
.build();
GrpcCallSettings<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsTransportSettings =
GrpcCallSettings.<TestIamPermissionsRequest, TestIamPermissionsResponse>newBuilder()
.setMethodDescriptor(testIamPermissionsMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("resource", String.valueOf(request.getResource()));
return builder.build();
})
.build();
this.listServicesCallable =
callableFactory.createUnaryCallable(
listServicesTransportSettings, settings.listServicesSettings(), clientContext);
this.listServicesPagedCallable =
callableFactory.createPagedCallable(
listServicesTransportSettings, settings.listServicesSettings(), clientContext);
this.getServiceCallable =
callableFactory.createUnaryCallable(
getServiceTransportSettings, settings.getServiceSettings(), clientContext);
this.createServiceCallable =
callableFactory.createUnaryCallable(
createServiceTransportSettings, settings.createServiceSettings(), clientContext);
this.createServiceOperationCallable =
callableFactory.createOperationCallable(
createServiceTransportSettings,
settings.createServiceOperationSettings(),
clientContext,
operationsStub);
this.deleteServiceCallable =
callableFactory.createUnaryCallable(
deleteServiceTransportSettings, settings.deleteServiceSettings(), clientContext);
this.deleteServiceOperationCallable =
callableFactory.createOperationCallable(
deleteServiceTransportSettings,
settings.deleteServiceOperationSettings(),
clientContext,
operationsStub);
this.undeleteServiceCallable =
callableFactory.createUnaryCallable(
undeleteServiceTransportSettings, settings.undeleteServiceSettings(), clientContext);
this.undeleteServiceOperationCallable =
callableFactory.createOperationCallable(
undeleteServiceTransportSettings,
settings.undeleteServiceOperationSettings(),
clientContext,
operationsStub);
this.listServiceConfigsCallable =
callableFactory.createUnaryCallable(
listServiceConfigsTransportSettings,
settings.listServiceConfigsSettings(),
clientContext);
this.listServiceConfigsPagedCallable =
callableFactory.createPagedCallable(
listServiceConfigsTransportSettings,
settings.listServiceConfigsSettings(),
clientContext);
this.getServiceConfigCallable =
callableFactory.createUnaryCallable(
getServiceConfigTransportSettings, settings.getServiceConfigSettings(), clientContext);
this.createServiceConfigCallable =
callableFactory.createUnaryCallable(
createServiceConfigTransportSettings,
settings.createServiceConfigSettings(),
clientContext);
this.submitConfigSourceCallable =
callableFactory.createUnaryCallable(
submitConfigSourceTransportSettings,
settings.submitConfigSourceSettings(),
clientContext);
this.submitConfigSourceOperationCallable =
callableFactory.createOperationCallable(
submitConfigSourceTransportSettings,
settings.submitConfigSourceOperationSettings(),
clientContext,
operationsStub);
this.listServiceRolloutsCallable =
callableFactory.createUnaryCallable(
listServiceRolloutsTransportSettings,
settings.listServiceRolloutsSettings(),
clientContext);
this.listServiceRolloutsPagedCallable =
callableFactory.createPagedCallable(
listServiceRolloutsTransportSettings,
settings.listServiceRolloutsSettings(),
clientContext);
this.getServiceRolloutCallable =
callableFactory.createUnaryCallable(
getServiceRolloutTransportSettings,
settings.getServiceRolloutSettings(),
clientContext);
this.createServiceRolloutCallable =
callableFactory.createUnaryCallable(
createServiceRolloutTransportSettings,
settings.createServiceRolloutSettings(),
clientContext);
this.createServiceRolloutOperationCallable =
callableFactory.createOperationCallable(
createServiceRolloutTransportSettings,
settings.createServiceRolloutOperationSettings(),
clientContext,
operationsStub);
this.generateConfigReportCallable =
callableFactory.createUnaryCallable(
generateConfigReportTransportSettings,
settings.generateConfigReportSettings(),
clientContext);
this.setIamPolicyCallable =
callableFactory.createUnaryCallable(
setIamPolicyTransportSettings, settings.setIamPolicySettings(), clientContext);
this.getIamPolicyCallable =
callableFactory.createUnaryCallable(
getIamPolicyTransportSettings, settings.getIamPolicySettings(), clientContext);
this.testIamPermissionsCallable =
callableFactory.createUnaryCallable(
testIamPermissionsTransportSettings,
settings.testIamPermissionsSettings(),
clientContext);
this.backgroundResources =
new BackgroundResourceAggregation(clientContext.getBackgroundResources());
}
public GrpcOperationsStub getOperationsStub() {
return operationsStub;
}
@Override
public UnaryCallable<ListServicesRequest, ListServicesResponse> listServicesCallable() {
return listServicesCallable;
}
@Override
public UnaryCallable<ListServicesRequest, ListServicesPagedResponse> listServicesPagedCallable() {
return listServicesPagedCallable;
}
@Override
public UnaryCallable<GetServiceRequest, ManagedService> getServiceCallable() {
return getServiceCallable;
}
@Override
public UnaryCallable<CreateServiceRequest, Operation> createServiceCallable() {
return createServiceCallable;
}
@Override
public OperationCallable<CreateServiceRequest, ManagedService, OperationMetadata>
createServiceOperationCallable() {
return createServiceOperationCallable;
}
@Override
public UnaryCallable<DeleteServiceRequest, Operation> deleteServiceCallable() {
return deleteServiceCallable;
}
@Override
public OperationCallable<DeleteServiceRequest, Empty, OperationMetadata>
deleteServiceOperationCallable() {
return deleteServiceOperationCallable;
}
@Override
public UnaryCallable<UndeleteServiceRequest, Operation> undeleteServiceCallable() {
return undeleteServiceCallable;
}
@Override
public OperationCallable<UndeleteServiceRequest, UndeleteServiceResponse, OperationMetadata>
undeleteServiceOperationCallable() {
return undeleteServiceOperationCallable;
}
@Override
public UnaryCallable<ListServiceConfigsRequest, ListServiceConfigsResponse>
listServiceConfigsCallable() {
return listServiceConfigsCallable;
}
@Override
public UnaryCallable<ListServiceConfigsRequest, ListServiceConfigsPagedResponse>
listServiceConfigsPagedCallable() {
return listServiceConfigsPagedCallable;
}
@Override
public UnaryCallable<GetServiceConfigRequest, Service> getServiceConfigCallable() {
return getServiceConfigCallable;
}
@Override
public UnaryCallable<CreateServiceConfigRequest, Service> createServiceConfigCallable() {
return createServiceConfigCallable;
}
@Override
public UnaryCallable<SubmitConfigSourceRequest, Operation> submitConfigSourceCallable() {
return submitConfigSourceCallable;
}
@Override
public OperationCallable<SubmitConfigSourceRequest, SubmitConfigSourceResponse, OperationMetadata>
submitConfigSourceOperationCallable() {
return submitConfigSourceOperationCallable;
}
@Override
public UnaryCallable<ListServiceRolloutsRequest, ListServiceRolloutsResponse>
listServiceRolloutsCallable() {
return listServiceRolloutsCallable;
}
@Override
public UnaryCallable<ListServiceRolloutsRequest, ListServiceRolloutsPagedResponse>
listServiceRolloutsPagedCallable() {
return listServiceRolloutsPagedCallable;
}
@Override
public UnaryCallable<GetServiceRolloutRequest, Rollout> getServiceRolloutCallable() {
return getServiceRolloutCallable;
}
@Override
public UnaryCallable<CreateServiceRolloutRequest, Operation> createServiceRolloutCallable() {
return createServiceRolloutCallable;
}
@Override
public OperationCallable<CreateServiceRolloutRequest, Rollout, OperationMetadata>
createServiceRolloutOperationCallable() {
return createServiceRolloutOperationCallable;
}
@Override
public UnaryCallable<GenerateConfigReportRequest, GenerateConfigReportResponse>
generateConfigReportCallable() {
return generateConfigReportCallable;
}
@Override
public UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable() {
return setIamPolicyCallable;
}
@Override
public UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable() {
return getIamPolicyCallable;
}
@Override
public UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsCallable() {
return testIamPermissionsCallable;
}
@Override
public final void close() {
try {
backgroundResources.close();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Failed to close resource", e);
}
}
@Override
public void shutdown() {
backgroundResources.shutdown();
}
@Override
public boolean isShutdown() {
return backgroundResources.isShutdown();
}
@Override
public boolean isTerminated() {
return backgroundResources.isTerminated();
}
@Override
public void shutdownNow() {
backgroundResources.shutdownNow();
}
@Override
public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
return backgroundResources.awaitTermination(duration, unit);
}
}
|
googleapis/google-cloud-java | 36,508 | java-beyondcorp-appconnectors/proto-google-cloud-beyondcorp-appconnectors-v1/src/main/java/com/google/cloud/beyondcorp/appconnectors/v1/DeleteAppConnectorRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/beyondcorp/appconnectors/v1/app_connectors_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.beyondcorp.appconnectors.v1;
/**
*
*
* <pre>
* Request message for BeyondCorp.DeleteAppConnector.
* </pre>
*
* Protobuf type {@code google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest}
*/
public final class DeleteAppConnectorRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest)
DeleteAppConnectorRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use DeleteAppConnectorRequest.newBuilder() to construct.
private DeleteAppConnectorRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DeleteAppConnectorRequest() {
name_ = "";
requestId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new DeleteAppConnectorRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.beyondcorp.appconnectors.v1.AppConnectorsServiceProto
.internal_static_google_cloud_beyondcorp_appconnectors_v1_DeleteAppConnectorRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.beyondcorp.appconnectors.v1.AppConnectorsServiceProto
.internal_static_google_cloud_beyondcorp_appconnectors_v1_DeleteAppConnectorRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest.class,
com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object name_ = "";
/**
*
*
* <pre>
* Required. BeyondCorp AppConnector name using the form:
* `projects/{project_id}/locations/{location_id}/appConnectors/{app_connector_id}`
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The name.
*/
@java.lang.Override
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. BeyondCorp AppConnector name using the form:
* `projects/{project_id}/locations/{location_id}/appConnectors/{app_connector_id}`
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for name.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int REQUEST_ID_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object requestId_ = "";
/**
*
*
* <pre>
* Optional. An optional request ID to identify requests. Specify a unique
* request ID so that if you must retry your request, the server will know to
* ignore the request if it has already been completed. The server will
* guarantee that for at least 60 minutes after the first request.
*
* For example, consider a situation where you make an initial request and t
* he request times out. If you make the request again with the same request
* ID, the server can check if original operation with the same request ID
* was received, and if so, will ignore the second request. This prevents
* clients from accidentally creating duplicate commitments.
*
* The request ID must be a valid UUID with the exception that zero UUID is
* not supported (00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The requestId.
*/
@java.lang.Override
public java.lang.String getRequestId() {
java.lang.Object ref = requestId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
requestId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. An optional request ID to identify requests. Specify a unique
* request ID so that if you must retry your request, the server will know to
* ignore the request if it has already been completed. The server will
* guarantee that for at least 60 minutes after the first request.
*
* For example, consider a situation where you make an initial request and t
* he request times out. If you make the request again with the same request
* ID, the server can check if original operation with the same request ID
* was received, and if so, will ignore the second request. This prevents
* clients from accidentally creating duplicate commitments.
*
* The request ID must be a valid UUID with the exception that zero UUID is
* not supported (00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for requestId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRequestIdBytes() {
java.lang.Object ref = requestId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
requestId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VALIDATE_ONLY_FIELD_NUMBER = 3;
private boolean validateOnly_ = false;
/**
*
*
* <pre>
* Optional. If set, validates request by executing a dry-run which would not
* alter the resource in any way.
* </pre>
*
* <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(requestId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, requestId_);
}
if (validateOnly_ != false) {
output.writeBool(3, validateOnly_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(requestId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, requestId_);
}
if (validateOnly_ != false) {
size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, validateOnly_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest)) {
return super.equals(obj);
}
com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest other =
(com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest) obj;
if (!getName().equals(other.getName())) return false;
if (!getRequestId().equals(other.getRequestId())) return false;
if (getValidateOnly() != other.getValidateOnly()) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (37 * hash) + REQUEST_ID_FIELD_NUMBER;
hash = (53 * hash) + getRequestId().hashCode();
hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getValidateOnly());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request message for BeyondCorp.DeleteAppConnector.
* </pre>
*
* Protobuf type {@code google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest)
com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.beyondcorp.appconnectors.v1.AppConnectorsServiceProto
.internal_static_google_cloud_beyondcorp_appconnectors_v1_DeleteAppConnectorRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.beyondcorp.appconnectors.v1.AppConnectorsServiceProto
.internal_static_google_cloud_beyondcorp_appconnectors_v1_DeleteAppConnectorRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest.class,
com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest.Builder.class);
}
// Construct using
// com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
name_ = "";
requestId_ = "";
validateOnly_ = false;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.beyondcorp.appconnectors.v1.AppConnectorsServiceProto
.internal_static_google_cloud_beyondcorp_appconnectors_v1_DeleteAppConnectorRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest
getDefaultInstanceForType() {
return com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest build() {
com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest result =
buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest buildPartial() {
com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest result =
new com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.name_ = name_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.requestId_ = requestId_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.validateOnly_ = validateOnly_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest) {
return mergeFrom(
(com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest other) {
if (other
== com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest
.getDefaultInstance()) return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getRequestId().isEmpty()) {
requestId_ = other.requestId_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.getValidateOnly() != false) {
setValidateOnly(other.getValidateOnly());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
name_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
requestId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 24:
{
validateOnly_ = input.readBool();
bitField0_ |= 0x00000004;
break;
} // case 24
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object name_ = "";
/**
*
*
* <pre>
* Required. BeyondCorp AppConnector name using the form:
* `projects/{project_id}/locations/{location_id}/appConnectors/{app_connector_id}`
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The name.
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. BeyondCorp AppConnector name using the form:
* `projects/{project_id}/locations/{location_id}/appConnectors/{app_connector_id}`
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for name.
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. BeyondCorp AppConnector name using the form:
* `projects/{project_id}/locations/{location_id}/appConnectors/{app_connector_id}`
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The name to set.
* @return This builder for chaining.
*/
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. BeyondCorp AppConnector name using the form:
* `projects/{project_id}/locations/{location_id}/appConnectors/{app_connector_id}`
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. BeyondCorp AppConnector name using the form:
* `projects/{project_id}/locations/{location_id}/appConnectors/{app_connector_id}`
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for name to set.
* @return This builder for chaining.
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object requestId_ = "";
/**
*
*
* <pre>
* Optional. An optional request ID to identify requests. Specify a unique
* request ID so that if you must retry your request, the server will know to
* ignore the request if it has already been completed. The server will
* guarantee that for at least 60 minutes after the first request.
*
* For example, consider a situation where you make an initial request and t
* he request times out. If you make the request again with the same request
* ID, the server can check if original operation with the same request ID
* was received, and if so, will ignore the second request. This prevents
* clients from accidentally creating duplicate commitments.
*
* The request ID must be a valid UUID with the exception that zero UUID is
* not supported (00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The requestId.
*/
public java.lang.String getRequestId() {
java.lang.Object ref = requestId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
requestId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. An optional request ID to identify requests. Specify a unique
* request ID so that if you must retry your request, the server will know to
* ignore the request if it has already been completed. The server will
* guarantee that for at least 60 minutes after the first request.
*
* For example, consider a situation where you make an initial request and t
* he request times out. If you make the request again with the same request
* ID, the server can check if original operation with the same request ID
* was received, and if so, will ignore the second request. This prevents
* clients from accidentally creating duplicate commitments.
*
* The request ID must be a valid UUID with the exception that zero UUID is
* not supported (00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for requestId.
*/
public com.google.protobuf.ByteString getRequestIdBytes() {
java.lang.Object ref = requestId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
requestId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. An optional request ID to identify requests. Specify a unique
* request ID so that if you must retry your request, the server will know to
* ignore the request if it has already been completed. The server will
* guarantee that for at least 60 minutes after the first request.
*
* For example, consider a situation where you make an initial request and t
* he request times out. If you make the request again with the same request
* ID, the server can check if original operation with the same request ID
* was received, and if so, will ignore the second request. This prevents
* clients from accidentally creating duplicate commitments.
*
* The request ID must be a valid UUID with the exception that zero UUID is
* not supported (00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The requestId to set.
* @return This builder for chaining.
*/
public Builder setRequestId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
requestId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. An optional request ID to identify requests. Specify a unique
* request ID so that if you must retry your request, the server will know to
* ignore the request if it has already been completed. The server will
* guarantee that for at least 60 minutes after the first request.
*
* For example, consider a situation where you make an initial request and t
* he request times out. If you make the request again with the same request
* ID, the server can check if original operation with the same request ID
* was received, and if so, will ignore the second request. This prevents
* clients from accidentally creating duplicate commitments.
*
* The request ID must be a valid UUID with the exception that zero UUID is
* not supported (00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearRequestId() {
requestId_ = getDefaultInstance().getRequestId();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. An optional request ID to identify requests. Specify a unique
* request ID so that if you must retry your request, the server will know to
* ignore the request if it has already been completed. The server will
* guarantee that for at least 60 minutes after the first request.
*
* For example, consider a situation where you make an initial request and t
* he request times out. If you make the request again with the same request
* ID, the server can check if original operation with the same request ID
* was received, and if so, will ignore the second request. This prevents
* clients from accidentally creating duplicate commitments.
*
* The request ID must be a valid UUID with the exception that zero UUID is
* not supported (00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for requestId to set.
* @return This builder for chaining.
*/
public Builder setRequestIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
requestId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private boolean validateOnly_;
/**
*
*
* <pre>
* Optional. If set, validates request by executing a dry-run which would not
* alter the resource in any way.
* </pre>
*
* <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
/**
*
*
* <pre>
* Optional. If set, validates request by executing a dry-run which would not
* alter the resource in any way.
* </pre>
*
* <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The validateOnly to set.
* @return This builder for chaining.
*/
public Builder setValidateOnly(boolean value) {
validateOnly_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. If set, validates request by executing a dry-run which would not
* alter the resource in any way.
* </pre>
*
* <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearValidateOnly() {
bitField0_ = (bitField0_ & ~0x00000004);
validateOnly_ = false;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest)
private static final com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest();
}
public static com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DeleteAppConnectorRequest> PARSER =
new com.google.protobuf.AbstractParser<DeleteAppConnectorRequest>() {
@java.lang.Override
public DeleteAppConnectorRequest 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<DeleteAppConnectorRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DeleteAppConnectorRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.beyondcorp.appconnectors.v1.DeleteAppConnectorRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 36,753 | google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/common/CampaignThirdPartyReachIntegrationPartner.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v21/common/third_party_integration_partners.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v21.common;
/**
* <pre>
* Container for third party reach integration data for Campaign.
* Next Id = 4
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner}
*/
public final class CampaignThirdPartyReachIntegrationPartner extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner)
CampaignThirdPartyReachIntegrationPartnerOrBuilder {
private static final long serialVersionUID = 0L;
// Use CampaignThirdPartyReachIntegrationPartner.newBuilder() to construct.
private CampaignThirdPartyReachIntegrationPartner(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CampaignThirdPartyReachIntegrationPartner() {
reachIntegrationPartner_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new CampaignThirdPartyReachIntegrationPartner();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnersProto.internal_static_google_ads_googleads_v21_common_CampaignThirdPartyReachIntegrationPartner_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnersProto.internal_static_google_ads_googleads_v21_common_CampaignThirdPartyReachIntegrationPartner_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner.class, com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner.Builder.class);
}
private int bitField0_;
public static final int REACH_INTEGRATION_PARTNER_FIELD_NUMBER = 1;
private int reachIntegrationPartner_ = 0;
/**
* <pre>
* Allowed third party integration partners for reach verification.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner reach_integration_partner = 1;</code>
* @return The enum numeric value on the wire for reachIntegrationPartner.
*/
@java.lang.Override public int getReachIntegrationPartnerValue() {
return reachIntegrationPartner_;
}
/**
* <pre>
* Allowed third party integration partners for reach verification.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner reach_integration_partner = 1;</code>
* @return The reachIntegrationPartner.
*/
@java.lang.Override public com.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner getReachIntegrationPartner() {
com.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner result = com.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner.forNumber(reachIntegrationPartner_);
return result == null ? com.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner.UNRECOGNIZED : result;
}
public static final int REACH_INTEGRATION_PARTNER_DATA_FIELD_NUMBER = 2;
private com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData reachIntegrationPartnerData_;
/**
* <pre>
* Third party partner data for YouTube Reach verification. This is
* optional metadata for partners to join or attach data to Ads campaigns.
* </pre>
*
* <code>.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData reach_integration_partner_data = 2;</code>
* @return Whether the reachIntegrationPartnerData field is set.
*/
@java.lang.Override
public boolean hasReachIntegrationPartnerData() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* Third party partner data for YouTube Reach verification. This is
* optional metadata for partners to join or attach data to Ads campaigns.
* </pre>
*
* <code>.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData reach_integration_partner_data = 2;</code>
* @return The reachIntegrationPartnerData.
*/
@java.lang.Override
public com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData getReachIntegrationPartnerData() {
return reachIntegrationPartnerData_ == null ? com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData.getDefaultInstance() : reachIntegrationPartnerData_;
}
/**
* <pre>
* Third party partner data for YouTube Reach verification. This is
* optional metadata for partners to join or attach data to Ads campaigns.
* </pre>
*
* <code>.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData reach_integration_partner_data = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerDataOrBuilder getReachIntegrationPartnerDataOrBuilder() {
return reachIntegrationPartnerData_ == null ? com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData.getDefaultInstance() : reachIntegrationPartnerData_;
}
public static final int SHARE_COST_FIELD_NUMBER = 3;
private boolean shareCost_ = false;
/**
* <pre>
* If true, then cost data will be shared with this vendor.
* </pre>
*
* <code>bool share_cost = 3;</code>
* @return The shareCost.
*/
@java.lang.Override
public boolean getShareCost() {
return shareCost_;
}
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 (reachIntegrationPartner_ != com.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner.UNSPECIFIED.getNumber()) {
output.writeEnum(1, reachIntegrationPartner_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getReachIntegrationPartnerData());
}
if (shareCost_ != false) {
output.writeBool(3, shareCost_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (reachIntegrationPartner_ != com.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner.UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(1, reachIntegrationPartner_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, getReachIntegrationPartnerData());
}
if (shareCost_ != false) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(3, shareCost_);
}
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.common.CampaignThirdPartyReachIntegrationPartner)) {
return super.equals(obj);
}
com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner other = (com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner) obj;
if (reachIntegrationPartner_ != other.reachIntegrationPartner_) return false;
if (hasReachIntegrationPartnerData() != other.hasReachIntegrationPartnerData()) return false;
if (hasReachIntegrationPartnerData()) {
if (!getReachIntegrationPartnerData()
.equals(other.getReachIntegrationPartnerData())) return false;
}
if (getShareCost()
!= other.getShareCost()) 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) + REACH_INTEGRATION_PARTNER_FIELD_NUMBER;
hash = (53 * hash) + reachIntegrationPartner_;
if (hasReachIntegrationPartnerData()) {
hash = (37 * hash) + REACH_INTEGRATION_PARTNER_DATA_FIELD_NUMBER;
hash = (53 * hash) + getReachIntegrationPartnerData().hashCode();
}
hash = (37 * hash) + SHARE_COST_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
getShareCost());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner 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.common.CampaignThirdPartyReachIntegrationPartner parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner 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.common.CampaignThirdPartyReachIntegrationPartner parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner 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.common.CampaignThirdPartyReachIntegrationPartner parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner 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.common.CampaignThirdPartyReachIntegrationPartner parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner 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.common.CampaignThirdPartyReachIntegrationPartner 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.common.CampaignThirdPartyReachIntegrationPartner 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.common.CampaignThirdPartyReachIntegrationPartner 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>
* Container for third party reach integration data for Campaign.
* Next Id = 4
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner)
com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartnerOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnersProto.internal_static_google_ads_googleads_v21_common_CampaignThirdPartyReachIntegrationPartner_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnersProto.internal_static_google_ads_googleads_v21_common_CampaignThirdPartyReachIntegrationPartner_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner.class, com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner.Builder.class);
}
// Construct using com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getReachIntegrationPartnerDataFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
reachIntegrationPartner_ = 0;
reachIntegrationPartnerData_ = null;
if (reachIntegrationPartnerDataBuilder_ != null) {
reachIntegrationPartnerDataBuilder_.dispose();
reachIntegrationPartnerDataBuilder_ = null;
}
shareCost_ = false;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnersProto.internal_static_google_ads_googleads_v21_common_CampaignThirdPartyReachIntegrationPartner_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner getDefaultInstanceForType() {
return com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner build() {
com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner buildPartial() {
com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner result = new com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.reachIntegrationPartner_ = reachIntegrationPartner_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.reachIntegrationPartnerData_ = reachIntegrationPartnerDataBuilder_ == null
? reachIntegrationPartnerData_
: reachIntegrationPartnerDataBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.shareCost_ = shareCost_;
}
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.common.CampaignThirdPartyReachIntegrationPartner) {
return mergeFrom((com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner other) {
if (other == com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner.getDefaultInstance()) return this;
if (other.reachIntegrationPartner_ != 0) {
setReachIntegrationPartnerValue(other.getReachIntegrationPartnerValue());
}
if (other.hasReachIntegrationPartnerData()) {
mergeReachIntegrationPartnerData(other.getReachIntegrationPartnerData());
}
if (other.getShareCost() != false) {
setShareCost(other.getShareCost());
}
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: {
reachIntegrationPartner_ = input.readEnum();
bitField0_ |= 0x00000001;
break;
} // case 8
case 18: {
input.readMessage(
getReachIntegrationPartnerDataFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 24: {
shareCost_ = input.readBool();
bitField0_ |= 0x00000004;
break;
} // case 24
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private int reachIntegrationPartner_ = 0;
/**
* <pre>
* Allowed third party integration partners for reach verification.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner reach_integration_partner = 1;</code>
* @return The enum numeric value on the wire for reachIntegrationPartner.
*/
@java.lang.Override public int getReachIntegrationPartnerValue() {
return reachIntegrationPartner_;
}
/**
* <pre>
* Allowed third party integration partners for reach verification.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner reach_integration_partner = 1;</code>
* @param value The enum numeric value on the wire for reachIntegrationPartner to set.
* @return This builder for chaining.
*/
public Builder setReachIntegrationPartnerValue(int value) {
reachIntegrationPartner_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Allowed third party integration partners for reach verification.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner reach_integration_partner = 1;</code>
* @return The reachIntegrationPartner.
*/
@java.lang.Override
public com.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner getReachIntegrationPartner() {
com.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner result = com.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner.forNumber(reachIntegrationPartner_);
return result == null ? com.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner.UNRECOGNIZED : result;
}
/**
* <pre>
* Allowed third party integration partners for reach verification.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner reach_integration_partner = 1;</code>
* @param value The reachIntegrationPartner to set.
* @return This builder for chaining.
*/
public Builder setReachIntegrationPartner(com.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
reachIntegrationPartner_ = value.getNumber();
onChanged();
return this;
}
/**
* <pre>
* Allowed third party integration partners for reach verification.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ThirdPartyReachIntegrationPartnerEnum.ThirdPartyReachIntegrationPartner reach_integration_partner = 1;</code>
* @return This builder for chaining.
*/
public Builder clearReachIntegrationPartner() {
bitField0_ = (bitField0_ & ~0x00000001);
reachIntegrationPartner_ = 0;
onChanged();
return this;
}
private com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData reachIntegrationPartnerData_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData, com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData.Builder, com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerDataOrBuilder> reachIntegrationPartnerDataBuilder_;
/**
* <pre>
* Third party partner data for YouTube Reach verification. This is
* optional metadata for partners to join or attach data to Ads campaigns.
* </pre>
*
* <code>.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData reach_integration_partner_data = 2;</code>
* @return Whether the reachIntegrationPartnerData field is set.
*/
public boolean hasReachIntegrationPartnerData() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* Third party partner data for YouTube Reach verification. This is
* optional metadata for partners to join or attach data to Ads campaigns.
* </pre>
*
* <code>.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData reach_integration_partner_data = 2;</code>
* @return The reachIntegrationPartnerData.
*/
public com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData getReachIntegrationPartnerData() {
if (reachIntegrationPartnerDataBuilder_ == null) {
return reachIntegrationPartnerData_ == null ? com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData.getDefaultInstance() : reachIntegrationPartnerData_;
} else {
return reachIntegrationPartnerDataBuilder_.getMessage();
}
}
/**
* <pre>
* Third party partner data for YouTube Reach verification. This is
* optional metadata for partners to join or attach data to Ads campaigns.
* </pre>
*
* <code>.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData reach_integration_partner_data = 2;</code>
*/
public Builder setReachIntegrationPartnerData(com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData value) {
if (reachIntegrationPartnerDataBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
reachIntegrationPartnerData_ = value;
} else {
reachIntegrationPartnerDataBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Third party partner data for YouTube Reach verification. This is
* optional metadata for partners to join or attach data to Ads campaigns.
* </pre>
*
* <code>.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData reach_integration_partner_data = 2;</code>
*/
public Builder setReachIntegrationPartnerData(
com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData.Builder builderForValue) {
if (reachIntegrationPartnerDataBuilder_ == null) {
reachIntegrationPartnerData_ = builderForValue.build();
} else {
reachIntegrationPartnerDataBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Third party partner data for YouTube Reach verification. This is
* optional metadata for partners to join or attach data to Ads campaigns.
* </pre>
*
* <code>.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData reach_integration_partner_data = 2;</code>
*/
public Builder mergeReachIntegrationPartnerData(com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData value) {
if (reachIntegrationPartnerDataBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0) &&
reachIntegrationPartnerData_ != null &&
reachIntegrationPartnerData_ != com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData.getDefaultInstance()) {
getReachIntegrationPartnerDataBuilder().mergeFrom(value);
} else {
reachIntegrationPartnerData_ = value;
}
} else {
reachIntegrationPartnerDataBuilder_.mergeFrom(value);
}
if (reachIntegrationPartnerData_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
* <pre>
* Third party partner data for YouTube Reach verification. This is
* optional metadata for partners to join or attach data to Ads campaigns.
* </pre>
*
* <code>.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData reach_integration_partner_data = 2;</code>
*/
public Builder clearReachIntegrationPartnerData() {
bitField0_ = (bitField0_ & ~0x00000002);
reachIntegrationPartnerData_ = null;
if (reachIntegrationPartnerDataBuilder_ != null) {
reachIntegrationPartnerDataBuilder_.dispose();
reachIntegrationPartnerDataBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* Third party partner data for YouTube Reach verification. This is
* optional metadata for partners to join or attach data to Ads campaigns.
* </pre>
*
* <code>.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData reach_integration_partner_data = 2;</code>
*/
public com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData.Builder getReachIntegrationPartnerDataBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getReachIntegrationPartnerDataFieldBuilder().getBuilder();
}
/**
* <pre>
* Third party partner data for YouTube Reach verification. This is
* optional metadata for partners to join or attach data to Ads campaigns.
* </pre>
*
* <code>.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData reach_integration_partner_data = 2;</code>
*/
public com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerDataOrBuilder getReachIntegrationPartnerDataOrBuilder() {
if (reachIntegrationPartnerDataBuilder_ != null) {
return reachIntegrationPartnerDataBuilder_.getMessageOrBuilder();
} else {
return reachIntegrationPartnerData_ == null ?
com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData.getDefaultInstance() : reachIntegrationPartnerData_;
}
}
/**
* <pre>
* Third party partner data for YouTube Reach verification. This is
* optional metadata for partners to join or attach data to Ads campaigns.
* </pre>
*
* <code>.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData reach_integration_partner_data = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData, com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData.Builder, com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerDataOrBuilder>
getReachIntegrationPartnerDataFieldBuilder() {
if (reachIntegrationPartnerDataBuilder_ == null) {
reachIntegrationPartnerDataBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData, com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerData.Builder, com.google.ads.googleads.v21.common.ThirdPartyIntegrationPartnerDataOrBuilder>(
getReachIntegrationPartnerData(),
getParentForChildren(),
isClean());
reachIntegrationPartnerData_ = null;
}
return reachIntegrationPartnerDataBuilder_;
}
private boolean shareCost_ ;
/**
* <pre>
* If true, then cost data will be shared with this vendor.
* </pre>
*
* <code>bool share_cost = 3;</code>
* @return The shareCost.
*/
@java.lang.Override
public boolean getShareCost() {
return shareCost_;
}
/**
* <pre>
* If true, then cost data will be shared with this vendor.
* </pre>
*
* <code>bool share_cost = 3;</code>
* @param value The shareCost to set.
* @return This builder for chaining.
*/
public Builder setShareCost(boolean value) {
shareCost_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* If true, then cost data will be shared with this vendor.
* </pre>
*
* <code>bool share_cost = 3;</code>
* @return This builder for chaining.
*/
public Builder clearShareCost() {
bitField0_ = (bitField0_ & ~0x00000004);
shareCost_ = false;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner)
private static final com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner();
}
public static com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CampaignThirdPartyReachIntegrationPartner>
PARSER = new com.google.protobuf.AbstractParser<CampaignThirdPartyReachIntegrationPartner>() {
@java.lang.Override
public CampaignThirdPartyReachIntegrationPartner 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<CampaignThirdPartyReachIntegrationPartner> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CampaignThirdPartyReachIntegrationPartner> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v21.common.CampaignThirdPartyReachIntegrationPartner getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,395 | java-bare-metal-solution/proto-google-cloud-bare-metal-solution-v2/src/main/java/com/google/cloud/baremetalsolution/v2/CreateSSHKeyRequest.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/baremetalsolution/v2/ssh_key.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.baremetalsolution.v2;
/**
*
*
* <pre>
* Message for registering a public SSH key in a project.
* </pre>
*
* Protobuf type {@code google.cloud.baremetalsolution.v2.CreateSSHKeyRequest}
*/
public final class CreateSSHKeyRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.baremetalsolution.v2.CreateSSHKeyRequest)
CreateSSHKeyRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateSSHKeyRequest.newBuilder() to construct.
private CreateSSHKeyRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateSSHKeyRequest() {
parent_ = "";
sshKeyId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateSSHKeyRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.baremetalsolution.v2.SshKeyProto
.internal_static_google_cloud_baremetalsolution_v2_CreateSSHKeyRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.baremetalsolution.v2.SshKeyProto
.internal_static_google_cloud_baremetalsolution_v2_CreateSSHKeyRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest.class,
com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent containing the SSH keys.
* </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 containing the SSH keys.
* </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 SSH_KEY_FIELD_NUMBER = 2;
private com.google.cloud.baremetalsolution.v2.SSHKey sshKey_;
/**
*
*
* <pre>
* Required. The SSH key to register.
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.SSHKey ssh_key = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the sshKey field is set.
*/
@java.lang.Override
public boolean hasSshKey() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The SSH key to register.
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.SSHKey ssh_key = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The sshKey.
*/
@java.lang.Override
public com.google.cloud.baremetalsolution.v2.SSHKey getSshKey() {
return sshKey_ == null
? com.google.cloud.baremetalsolution.v2.SSHKey.getDefaultInstance()
: sshKey_;
}
/**
*
*
* <pre>
* Required. The SSH key to register.
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.SSHKey ssh_key = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.baremetalsolution.v2.SSHKeyOrBuilder getSshKeyOrBuilder() {
return sshKey_ == null
? com.google.cloud.baremetalsolution.v2.SSHKey.getDefaultInstance()
: sshKey_;
}
public static final int SSH_KEY_ID_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object sshKeyId_ = "";
/**
*
*
* <pre>
* Required. The ID to use for the key, which will become the final component
* of the key's resource name.
*
* This value must match the regex:
* [a-zA-Z0-9@.\-_]{1,64}
* </pre>
*
* <code>string ssh_key_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The sshKeyId.
*/
@java.lang.Override
public java.lang.String getSshKeyId() {
java.lang.Object ref = sshKeyId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
sshKeyId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The ID to use for the key, which will become the final component
* of the key's resource name.
*
* This value must match the regex:
* [a-zA-Z0-9@.\-_]{1,64}
* </pre>
*
* <code>string ssh_key_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for sshKeyId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getSshKeyIdBytes() {
java.lang.Object ref = sshKeyId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
sshKeyId_ = 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, getSshKey());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(sshKeyId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, sshKeyId_);
}
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, getSshKey());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(sshKeyId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, sshKeyId_);
}
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.baremetalsolution.v2.CreateSSHKeyRequest)) {
return super.equals(obj);
}
com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest other =
(com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (hasSshKey() != other.hasSshKey()) return false;
if (hasSshKey()) {
if (!getSshKey().equals(other.getSshKey())) return false;
}
if (!getSshKeyId().equals(other.getSshKeyId())) 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 (hasSshKey()) {
hash = (37 * hash) + SSH_KEY_FIELD_NUMBER;
hash = (53 * hash) + getSshKey().hashCode();
}
hash = (37 * hash) + SSH_KEY_ID_FIELD_NUMBER;
hash = (53 * hash) + getSshKeyId().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest 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.baremetalsolution.v2.CreateSSHKeyRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest 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.baremetalsolution.v2.CreateSSHKeyRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest 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.baremetalsolution.v2.CreateSSHKeyRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest 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.baremetalsolution.v2.CreateSSHKeyRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest 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.baremetalsolution.v2.CreateSSHKeyRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Message for registering a public SSH key in a project.
* </pre>
*
* Protobuf type {@code google.cloud.baremetalsolution.v2.CreateSSHKeyRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.baremetalsolution.v2.CreateSSHKeyRequest)
com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.baremetalsolution.v2.SshKeyProto
.internal_static_google_cloud_baremetalsolution_v2_CreateSSHKeyRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.baremetalsolution.v2.SshKeyProto
.internal_static_google_cloud_baremetalsolution_v2_CreateSSHKeyRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest.class,
com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest.Builder.class);
}
// Construct using com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getSshKeyFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
sshKey_ = null;
if (sshKeyBuilder_ != null) {
sshKeyBuilder_.dispose();
sshKeyBuilder_ = null;
}
sshKeyId_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.baremetalsolution.v2.SshKeyProto
.internal_static_google_cloud_baremetalsolution_v2_CreateSSHKeyRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest getDefaultInstanceForType() {
return com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest build() {
com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest buildPartial() {
com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest result =
new com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.sshKey_ = sshKeyBuilder_ == null ? sshKey_ : sshKeyBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.sshKeyId_ = sshKeyId_;
}
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.baremetalsolution.v2.CreateSSHKeyRequest) {
return mergeFrom((com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest other) {
if (other == com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasSshKey()) {
mergeSshKey(other.getSshKey());
}
if (!other.getSshKeyId().isEmpty()) {
sshKeyId_ = other.sshKeyId_;
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(getSshKeyFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
sshKeyId_ = 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 parent containing the SSH keys.
* </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 containing the SSH keys.
* </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 containing the SSH keys.
* </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 containing the SSH keys.
* </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 containing the SSH keys.
* </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.baremetalsolution.v2.SSHKey sshKey_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.baremetalsolution.v2.SSHKey,
com.google.cloud.baremetalsolution.v2.SSHKey.Builder,
com.google.cloud.baremetalsolution.v2.SSHKeyOrBuilder>
sshKeyBuilder_;
/**
*
*
* <pre>
* Required. The SSH key to register.
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.SSHKey ssh_key = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the sshKey field is set.
*/
public boolean hasSshKey() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The SSH key to register.
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.SSHKey ssh_key = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The sshKey.
*/
public com.google.cloud.baremetalsolution.v2.SSHKey getSshKey() {
if (sshKeyBuilder_ == null) {
return sshKey_ == null
? com.google.cloud.baremetalsolution.v2.SSHKey.getDefaultInstance()
: sshKey_;
} else {
return sshKeyBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The SSH key to register.
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.SSHKey ssh_key = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setSshKey(com.google.cloud.baremetalsolution.v2.SSHKey value) {
if (sshKeyBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
sshKey_ = value;
} else {
sshKeyBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The SSH key to register.
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.SSHKey ssh_key = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setSshKey(com.google.cloud.baremetalsolution.v2.SSHKey.Builder builderForValue) {
if (sshKeyBuilder_ == null) {
sshKey_ = builderForValue.build();
} else {
sshKeyBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The SSH key to register.
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.SSHKey ssh_key = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeSshKey(com.google.cloud.baremetalsolution.v2.SSHKey value) {
if (sshKeyBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& sshKey_ != null
&& sshKey_ != com.google.cloud.baremetalsolution.v2.SSHKey.getDefaultInstance()) {
getSshKeyBuilder().mergeFrom(value);
} else {
sshKey_ = value;
}
} else {
sshKeyBuilder_.mergeFrom(value);
}
if (sshKey_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The SSH key to register.
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.SSHKey ssh_key = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearSshKey() {
bitField0_ = (bitField0_ & ~0x00000002);
sshKey_ = null;
if (sshKeyBuilder_ != null) {
sshKeyBuilder_.dispose();
sshKeyBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The SSH key to register.
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.SSHKey ssh_key = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.baremetalsolution.v2.SSHKey.Builder getSshKeyBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getSshKeyFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The SSH key to register.
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.SSHKey ssh_key = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.baremetalsolution.v2.SSHKeyOrBuilder getSshKeyOrBuilder() {
if (sshKeyBuilder_ != null) {
return sshKeyBuilder_.getMessageOrBuilder();
} else {
return sshKey_ == null
? com.google.cloud.baremetalsolution.v2.SSHKey.getDefaultInstance()
: sshKey_;
}
}
/**
*
*
* <pre>
* Required. The SSH key to register.
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.SSHKey ssh_key = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.baremetalsolution.v2.SSHKey,
com.google.cloud.baremetalsolution.v2.SSHKey.Builder,
com.google.cloud.baremetalsolution.v2.SSHKeyOrBuilder>
getSshKeyFieldBuilder() {
if (sshKeyBuilder_ == null) {
sshKeyBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.baremetalsolution.v2.SSHKey,
com.google.cloud.baremetalsolution.v2.SSHKey.Builder,
com.google.cloud.baremetalsolution.v2.SSHKeyOrBuilder>(
getSshKey(), getParentForChildren(), isClean());
sshKey_ = null;
}
return sshKeyBuilder_;
}
private java.lang.Object sshKeyId_ = "";
/**
*
*
* <pre>
* Required. The ID to use for the key, which will become the final component
* of the key's resource name.
*
* This value must match the regex:
* [a-zA-Z0-9@.\-_]{1,64}
* </pre>
*
* <code>string ssh_key_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The sshKeyId.
*/
public java.lang.String getSshKeyId() {
java.lang.Object ref = sshKeyId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
sshKeyId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The ID to use for the key, which will become the final component
* of the key's resource name.
*
* This value must match the regex:
* [a-zA-Z0-9@.\-_]{1,64}
* </pre>
*
* <code>string ssh_key_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for sshKeyId.
*/
public com.google.protobuf.ByteString getSshKeyIdBytes() {
java.lang.Object ref = sshKeyId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
sshKeyId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The ID to use for the key, which will become the final component
* of the key's resource name.
*
* This value must match the regex:
* [a-zA-Z0-9@.\-_]{1,64}
* </pre>
*
* <code>string ssh_key_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The sshKeyId to set.
* @return This builder for chaining.
*/
public Builder setSshKeyId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
sshKeyId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ID to use for the key, which will become the final component
* of the key's resource name.
*
* This value must match the regex:
* [a-zA-Z0-9@.\-_]{1,64}
* </pre>
*
* <code>string ssh_key_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearSshKeyId() {
sshKeyId_ = getDefaultInstance().getSshKeyId();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ID to use for the key, which will become the final component
* of the key's resource name.
*
* This value must match the regex:
* [a-zA-Z0-9@.\-_]{1,64}
* </pre>
*
* <code>string ssh_key_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for sshKeyId to set.
* @return This builder for chaining.
*/
public Builder setSshKeyIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
sshKeyId_ = 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.baremetalsolution.v2.CreateSSHKeyRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.baremetalsolution.v2.CreateSSHKeyRequest)
private static final com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest();
}
public static com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateSSHKeyRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateSSHKeyRequest>() {
@java.lang.Override
public CreateSSHKeyRequest 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<CreateSSHKeyRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateSSHKeyRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.baremetalsolution.v2.CreateSSHKeyRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,407 | java-datalineage/proto-google-cloud-datalineage-v1/src/main/java/com/google/cloud/datacatalog/lineage/v1/ProcessLinkInfo.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/lineage/v1/lineage.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.datacatalog.lineage.v1;
/**
*
*
* <pre>
* Link details.
* </pre>
*
* Protobuf type {@code google.cloud.datacatalog.lineage.v1.ProcessLinkInfo}
*/
public final class ProcessLinkInfo extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.datacatalog.lineage.v1.ProcessLinkInfo)
ProcessLinkInfoOrBuilder {
private static final long serialVersionUID = 0L;
// Use ProcessLinkInfo.newBuilder() to construct.
private ProcessLinkInfo(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ProcessLinkInfo() {
link_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ProcessLinkInfo();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datacatalog.lineage.v1.LineageProto
.internal_static_google_cloud_datacatalog_lineage_v1_ProcessLinkInfo_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datacatalog.lineage.v1.LineageProto
.internal_static_google_cloud_datacatalog_lineage_v1_ProcessLinkInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo.class,
com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo.Builder.class);
}
private int bitField0_;
public static final int LINK_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object link_ = "";
/**
*
*
* <pre>
* The name of the link in the format of
* `projects/{project}/locations/{location}/links/{link}`.
* </pre>
*
* <code>string link = 1;</code>
*
* @return The link.
*/
@java.lang.Override
public java.lang.String getLink() {
java.lang.Object ref = link_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
link_ = s;
return s;
}
}
/**
*
*
* <pre>
* The name of the link in the format of
* `projects/{project}/locations/{location}/links/{link}`.
* </pre>
*
* <code>string link = 1;</code>
*
* @return The bytes for link.
*/
@java.lang.Override
public com.google.protobuf.ByteString getLinkBytes() {
java.lang.Object ref = link_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
link_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int START_TIME_FIELD_NUMBER = 2;
private com.google.protobuf.Timestamp startTime_;
/**
*
*
* <pre>
* The start of the first event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*
* @return Whether the startTime field is set.
*/
@java.lang.Override
public boolean hasStartTime() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The start of the first event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*
* @return The startTime.
*/
@java.lang.Override
public com.google.protobuf.Timestamp getStartTime() {
return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_;
}
/**
*
*
* <pre>
* The start of the first event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder() {
return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_;
}
public static final int END_TIME_FIELD_NUMBER = 3;
private com.google.protobuf.Timestamp endTime_;
/**
*
*
* <pre>
* The end of the last event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp end_time = 3;</code>
*
* @return Whether the endTime field is set.
*/
@java.lang.Override
public boolean hasEndTime() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The end of the last event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp end_time = 3;</code>
*
* @return The endTime.
*/
@java.lang.Override
public com.google.protobuf.Timestamp getEndTime() {
return endTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : endTime_;
}
/**
*
*
* <pre>
* The end of the last event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp end_time = 3;</code>
*/
@java.lang.Override
public com.google.protobuf.TimestampOrBuilder getEndTimeOrBuilder() {
return endTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : endTime_;
}
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(link_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, link_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getStartTime());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(3, getEndTime());
}
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(link_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, link_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getStartTime());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getEndTime());
}
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.lineage.v1.ProcessLinkInfo)) {
return super.equals(obj);
}
com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo other =
(com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo) obj;
if (!getLink().equals(other.getLink())) return false;
if (hasStartTime() != other.hasStartTime()) return false;
if (hasStartTime()) {
if (!getStartTime().equals(other.getStartTime())) return false;
}
if (hasEndTime() != other.hasEndTime()) return false;
if (hasEndTime()) {
if (!getEndTime().equals(other.getEndTime())) 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) + LINK_FIELD_NUMBER;
hash = (53 * hash) + getLink().hashCode();
if (hasStartTime()) {
hash = (37 * hash) + START_TIME_FIELD_NUMBER;
hash = (53 * hash) + getStartTime().hashCode();
}
if (hasEndTime()) {
hash = (37 * hash) + END_TIME_FIELD_NUMBER;
hash = (53 * hash) + getEndTime().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo 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.lineage.v1.ProcessLinkInfo parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo 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.lineage.v1.ProcessLinkInfo parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo 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.lineage.v1.ProcessLinkInfo parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo 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.lineage.v1.ProcessLinkInfo parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo 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.lineage.v1.ProcessLinkInfo 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>
* Link details.
* </pre>
*
* Protobuf type {@code google.cloud.datacatalog.lineage.v1.ProcessLinkInfo}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.datacatalog.lineage.v1.ProcessLinkInfo)
com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfoOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datacatalog.lineage.v1.LineageProto
.internal_static_google_cloud_datacatalog_lineage_v1_ProcessLinkInfo_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datacatalog.lineage.v1.LineageProto
.internal_static_google_cloud_datacatalog_lineage_v1_ProcessLinkInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo.class,
com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo.Builder.class);
}
// Construct using com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo.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();
getEndTimeFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
link_ = "";
startTime_ = null;
if (startTimeBuilder_ != null) {
startTimeBuilder_.dispose();
startTimeBuilder_ = null;
}
endTime_ = null;
if (endTimeBuilder_ != null) {
endTimeBuilder_.dispose();
endTimeBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.datacatalog.lineage.v1.LineageProto
.internal_static_google_cloud_datacatalog_lineage_v1_ProcessLinkInfo_descriptor;
}
@java.lang.Override
public com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo getDefaultInstanceForType() {
return com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo build() {
com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo buildPartial() {
com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo result =
new com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.link_ = link_;
}
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.endTime_ = endTimeBuilder_ == null ? endTime_ : endTimeBuilder_.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.datacatalog.lineage.v1.ProcessLinkInfo) {
return mergeFrom((com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo other) {
if (other == com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo.getDefaultInstance())
return this;
if (!other.getLink().isEmpty()) {
link_ = other.link_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasStartTime()) {
mergeStartTime(other.getStartTime());
}
if (other.hasEndTime()) {
mergeEndTime(other.getEndTime());
}
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:
{
link_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getStartTimeFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
input.readMessage(getEndTimeFieldBuilder().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 link_ = "";
/**
*
*
* <pre>
* The name of the link in the format of
* `projects/{project}/locations/{location}/links/{link}`.
* </pre>
*
* <code>string link = 1;</code>
*
* @return The link.
*/
public java.lang.String getLink() {
java.lang.Object ref = link_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
link_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The name of the link in the format of
* `projects/{project}/locations/{location}/links/{link}`.
* </pre>
*
* <code>string link = 1;</code>
*
* @return The bytes for link.
*/
public com.google.protobuf.ByteString getLinkBytes() {
java.lang.Object ref = link_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
link_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The name of the link in the format of
* `projects/{project}/locations/{location}/links/{link}`.
* </pre>
*
* <code>string link = 1;</code>
*
* @param value The link to set.
* @return This builder for chaining.
*/
public Builder setLink(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
link_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the link in the format of
* `projects/{project}/locations/{location}/links/{link}`.
* </pre>
*
* <code>string link = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearLink() {
link_ = getDefaultInstance().getLink();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the link in the format of
* `projects/{project}/locations/{location}/links/{link}`.
* </pre>
*
* <code>string link = 1;</code>
*
* @param value The bytes for link to set.
* @return This builder for chaining.
*/
public Builder setLinkBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
link_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.protobuf.Timestamp startTime_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
startTimeBuilder_;
/**
*
*
* <pre>
* The start of the first event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*
* @return Whether the startTime field is set.
*/
public boolean hasStartTime() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The start of the first event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*
* @return The startTime.
*/
public com.google.protobuf.Timestamp getStartTime() {
if (startTimeBuilder_ == null) {
return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_;
} else {
return startTimeBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The start of the first event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*/
public Builder setStartTime(com.google.protobuf.Timestamp value) {
if (startTimeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
startTime_ = value;
} else {
startTimeBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The start of the first event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*/
public Builder setStartTime(com.google.protobuf.Timestamp.Builder builderForValue) {
if (startTimeBuilder_ == null) {
startTime_ = builderForValue.build();
} else {
startTimeBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The start of the first event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*/
public Builder mergeStartTime(com.google.protobuf.Timestamp value) {
if (startTimeBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& startTime_ != null
&& startTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) {
getStartTimeBuilder().mergeFrom(value);
} else {
startTime_ = value;
}
} else {
startTimeBuilder_.mergeFrom(value);
}
if (startTime_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The start of the first event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*/
public Builder clearStartTime() {
bitField0_ = (bitField0_ & ~0x00000002);
startTime_ = null;
if (startTimeBuilder_ != null) {
startTimeBuilder_.dispose();
startTimeBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The start of the first event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*/
public com.google.protobuf.Timestamp.Builder getStartTimeBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getStartTimeFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The start of the first event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*/
public com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder() {
if (startTimeBuilder_ != null) {
return startTimeBuilder_.getMessageOrBuilder();
} else {
return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_;
}
}
/**
*
*
* <pre>
* The start of the first event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
getStartTimeFieldBuilder() {
if (startTimeBuilder_ == null) {
startTimeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>(
getStartTime(), getParentForChildren(), isClean());
startTime_ = null;
}
return startTimeBuilder_;
}
private com.google.protobuf.Timestamp endTime_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
endTimeBuilder_;
/**
*
*
* <pre>
* The end of the last event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp end_time = 3;</code>
*
* @return Whether the endTime field is set.
*/
public boolean hasEndTime() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* The end of the last event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp end_time = 3;</code>
*
* @return The endTime.
*/
public com.google.protobuf.Timestamp getEndTime() {
if (endTimeBuilder_ == null) {
return endTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : endTime_;
} else {
return endTimeBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The end of the last event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp end_time = 3;</code>
*/
public Builder setEndTime(com.google.protobuf.Timestamp value) {
if (endTimeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
endTime_ = value;
} else {
endTimeBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The end of the last event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp end_time = 3;</code>
*/
public Builder setEndTime(com.google.protobuf.Timestamp.Builder builderForValue) {
if (endTimeBuilder_ == null) {
endTime_ = builderForValue.build();
} else {
endTimeBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The end of the last event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp end_time = 3;</code>
*/
public Builder mergeEndTime(com.google.protobuf.Timestamp value) {
if (endTimeBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& endTime_ != null
&& endTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) {
getEndTimeBuilder().mergeFrom(value);
} else {
endTime_ = value;
}
} else {
endTimeBuilder_.mergeFrom(value);
}
if (endTime_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The end of the last event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp end_time = 3;</code>
*/
public Builder clearEndTime() {
bitField0_ = (bitField0_ & ~0x00000004);
endTime_ = null;
if (endTimeBuilder_ != null) {
endTimeBuilder_.dispose();
endTimeBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The end of the last event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp end_time = 3;</code>
*/
public com.google.protobuf.Timestamp.Builder getEndTimeBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getEndTimeFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The end of the last event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp end_time = 3;</code>
*/
public com.google.protobuf.TimestampOrBuilder getEndTimeOrBuilder() {
if (endTimeBuilder_ != null) {
return endTimeBuilder_.getMessageOrBuilder();
} else {
return endTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : endTime_;
}
}
/**
*
*
* <pre>
* The end of the last event establishing this link-process tuple.
* </pre>
*
* <code>.google.protobuf.Timestamp end_time = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
getEndTimeFieldBuilder() {
if (endTimeBuilder_ == null) {
endTimeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>(
getEndTime(), getParentForChildren(), isClean());
endTime_ = null;
}
return endTimeBuilder_;
}
@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.lineage.v1.ProcessLinkInfo)
}
// @@protoc_insertion_point(class_scope:google.cloud.datacatalog.lineage.v1.ProcessLinkInfo)
private static final com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo();
}
public static com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ProcessLinkInfo> PARSER =
new com.google.protobuf.AbstractParser<ProcessLinkInfo>() {
@java.lang.Override
public ProcessLinkInfo 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<ProcessLinkInfo> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ProcessLinkInfo> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.datacatalog.lineage.v1.ProcessLinkInfo getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,532 | java-netapp/proto-google-cloud-netapp-v1/src/main/java/com/google/cloud/netapp/v1/UpdateStoragePoolRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/netapp/v1/storage_pool.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.netapp.v1;
/**
*
*
* <pre>
* UpdateStoragePoolRequest updates a Storage Pool.
* </pre>
*
* Protobuf type {@code google.cloud.netapp.v1.UpdateStoragePoolRequest}
*/
public final class UpdateStoragePoolRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.netapp.v1.UpdateStoragePoolRequest)
UpdateStoragePoolRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateStoragePoolRequest.newBuilder() to construct.
private UpdateStoragePoolRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateStoragePoolRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateStoragePoolRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.netapp.v1.StoragePoolProto
.internal_static_google_cloud_netapp_v1_UpdateStoragePoolRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.netapp.v1.StoragePoolProto
.internal_static_google_cloud_netapp_v1_UpdateStoragePoolRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.netapp.v1.UpdateStoragePoolRequest.class,
com.google.cloud.netapp.v1.UpdateStoragePoolRequest.Builder.class);
}
private int bitField0_;
public static final int UPDATE_MASK_FIELD_NUMBER = 1;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Required. Field mask is used to specify the fields to be overwritten in the
* StoragePool resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. Field mask is used to specify the fields to be overwritten in the
* StoragePool resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Required. Field mask is used to specify the fields to be overwritten in the
* StoragePool resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </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 STORAGE_POOL_FIELD_NUMBER = 2;
private com.google.cloud.netapp.v1.StoragePool storagePool_;
/**
*
*
* <pre>
* Required. The pool being updated
* </pre>
*
* <code>
* .google.cloud.netapp.v1.StoragePool storage_pool = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the storagePool field is set.
*/
@java.lang.Override
public boolean hasStoragePool() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The pool being updated
* </pre>
*
* <code>
* .google.cloud.netapp.v1.StoragePool storage_pool = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The storagePool.
*/
@java.lang.Override
public com.google.cloud.netapp.v1.StoragePool getStoragePool() {
return storagePool_ == null
? com.google.cloud.netapp.v1.StoragePool.getDefaultInstance()
: storagePool_;
}
/**
*
*
* <pre>
* Required. The pool being updated
* </pre>
*
* <code>
* .google.cloud.netapp.v1.StoragePool storage_pool = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.netapp.v1.StoragePoolOrBuilder getStoragePoolOrBuilder() {
return storagePool_ == null
? com.google.cloud.netapp.v1.StoragePool.getDefaultInstance()
: storagePool_;
}
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, getStoragePool());
}
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, getStoragePool());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.netapp.v1.UpdateStoragePoolRequest)) {
return super.equals(obj);
}
com.google.cloud.netapp.v1.UpdateStoragePoolRequest other =
(com.google.cloud.netapp.v1.UpdateStoragePoolRequest) obj;
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask().equals(other.getUpdateMask())) return false;
}
if (hasStoragePool() != other.hasStoragePool()) return false;
if (hasStoragePool()) {
if (!getStoragePool().equals(other.getStoragePool())) 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 (hasStoragePool()) {
hash = (37 * hash) + STORAGE_POOL_FIELD_NUMBER;
hash = (53 * hash) + getStoragePool().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.netapp.v1.UpdateStoragePoolRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.netapp.v1.UpdateStoragePoolRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.netapp.v1.UpdateStoragePoolRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.netapp.v1.UpdateStoragePoolRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.netapp.v1.UpdateStoragePoolRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.netapp.v1.UpdateStoragePoolRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.netapp.v1.UpdateStoragePoolRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.netapp.v1.UpdateStoragePoolRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.netapp.v1.UpdateStoragePoolRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.netapp.v1.UpdateStoragePoolRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.netapp.v1.UpdateStoragePoolRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.netapp.v1.UpdateStoragePoolRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.netapp.v1.UpdateStoragePoolRequest 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>
* UpdateStoragePoolRequest updates a Storage Pool.
* </pre>
*
* Protobuf type {@code google.cloud.netapp.v1.UpdateStoragePoolRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.netapp.v1.UpdateStoragePoolRequest)
com.google.cloud.netapp.v1.UpdateStoragePoolRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.netapp.v1.StoragePoolProto
.internal_static_google_cloud_netapp_v1_UpdateStoragePoolRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.netapp.v1.StoragePoolProto
.internal_static_google_cloud_netapp_v1_UpdateStoragePoolRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.netapp.v1.UpdateStoragePoolRequest.class,
com.google.cloud.netapp.v1.UpdateStoragePoolRequest.Builder.class);
}
// Construct using com.google.cloud.netapp.v1.UpdateStoragePoolRequest.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();
getStoragePoolFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
storagePool_ = null;
if (storagePoolBuilder_ != null) {
storagePoolBuilder_.dispose();
storagePoolBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.netapp.v1.StoragePoolProto
.internal_static_google_cloud_netapp_v1_UpdateStoragePoolRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.netapp.v1.UpdateStoragePoolRequest getDefaultInstanceForType() {
return com.google.cloud.netapp.v1.UpdateStoragePoolRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.netapp.v1.UpdateStoragePoolRequest build() {
com.google.cloud.netapp.v1.UpdateStoragePoolRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.netapp.v1.UpdateStoragePoolRequest buildPartial() {
com.google.cloud.netapp.v1.UpdateStoragePoolRequest result =
new com.google.cloud.netapp.v1.UpdateStoragePoolRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.netapp.v1.UpdateStoragePoolRequest 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.storagePool_ =
storagePoolBuilder_ == null ? storagePool_ : storagePoolBuilder_.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.netapp.v1.UpdateStoragePoolRequest) {
return mergeFrom((com.google.cloud.netapp.v1.UpdateStoragePoolRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.netapp.v1.UpdateStoragePoolRequest other) {
if (other == com.google.cloud.netapp.v1.UpdateStoragePoolRequest.getDefaultInstance())
return this;
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
if (other.hasStoragePool()) {
mergeStoragePool(other.getStoragePool());
}
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(getStoragePoolFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
updateMaskBuilder_;
/**
*
*
* <pre>
* Required. Field mask is used to specify the fields to be overwritten in the
* StoragePool resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. Field mask is used to specify the fields to be overwritten in the
* StoragePool resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Field mask is used to specify the fields to be overwritten in the
* StoragePool resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
} else {
updateMaskBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Field mask is used to specify the fields to be overwritten in the
* StoragePool resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Field mask is used to specify the fields to be overwritten in the
* StoragePool resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& updateMask_ != null
&& updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) {
getUpdateMaskBuilder().mergeFrom(value);
} else {
updateMask_ = value;
}
} else {
updateMaskBuilder_.mergeFrom(value);
}
if (updateMask_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Field mask is used to specify the fields to be overwritten in the
* StoragePool resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000001);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Field mask is used to specify the fields to be overwritten in the
* StoragePool resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Field mask is used to specify the fields to be overwritten in the
* StoragePool resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Required. Field mask is used to specify the fields to be overwritten in the
* StoragePool resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </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.netapp.v1.StoragePool storagePool_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.netapp.v1.StoragePool,
com.google.cloud.netapp.v1.StoragePool.Builder,
com.google.cloud.netapp.v1.StoragePoolOrBuilder>
storagePoolBuilder_;
/**
*
*
* <pre>
* Required. The pool being updated
* </pre>
*
* <code>
* .google.cloud.netapp.v1.StoragePool storage_pool = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the storagePool field is set.
*/
public boolean hasStoragePool() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The pool being updated
* </pre>
*
* <code>
* .google.cloud.netapp.v1.StoragePool storage_pool = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The storagePool.
*/
public com.google.cloud.netapp.v1.StoragePool getStoragePool() {
if (storagePoolBuilder_ == null) {
return storagePool_ == null
? com.google.cloud.netapp.v1.StoragePool.getDefaultInstance()
: storagePool_;
} else {
return storagePoolBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The pool being updated
* </pre>
*
* <code>
* .google.cloud.netapp.v1.StoragePool storage_pool = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setStoragePool(com.google.cloud.netapp.v1.StoragePool value) {
if (storagePoolBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
storagePool_ = value;
} else {
storagePoolBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The pool being updated
* </pre>
*
* <code>
* .google.cloud.netapp.v1.StoragePool storage_pool = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setStoragePool(com.google.cloud.netapp.v1.StoragePool.Builder builderForValue) {
if (storagePoolBuilder_ == null) {
storagePool_ = builderForValue.build();
} else {
storagePoolBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The pool being updated
* </pre>
*
* <code>
* .google.cloud.netapp.v1.StoragePool storage_pool = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeStoragePool(com.google.cloud.netapp.v1.StoragePool value) {
if (storagePoolBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& storagePool_ != null
&& storagePool_ != com.google.cloud.netapp.v1.StoragePool.getDefaultInstance()) {
getStoragePoolBuilder().mergeFrom(value);
} else {
storagePool_ = value;
}
} else {
storagePoolBuilder_.mergeFrom(value);
}
if (storagePool_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The pool being updated
* </pre>
*
* <code>
* .google.cloud.netapp.v1.StoragePool storage_pool = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearStoragePool() {
bitField0_ = (bitField0_ & ~0x00000002);
storagePool_ = null;
if (storagePoolBuilder_ != null) {
storagePoolBuilder_.dispose();
storagePoolBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The pool being updated
* </pre>
*
* <code>
* .google.cloud.netapp.v1.StoragePool storage_pool = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.netapp.v1.StoragePool.Builder getStoragePoolBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getStoragePoolFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The pool being updated
* </pre>
*
* <code>
* .google.cloud.netapp.v1.StoragePool storage_pool = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.netapp.v1.StoragePoolOrBuilder getStoragePoolOrBuilder() {
if (storagePoolBuilder_ != null) {
return storagePoolBuilder_.getMessageOrBuilder();
} else {
return storagePool_ == null
? com.google.cloud.netapp.v1.StoragePool.getDefaultInstance()
: storagePool_;
}
}
/**
*
*
* <pre>
* Required. The pool being updated
* </pre>
*
* <code>
* .google.cloud.netapp.v1.StoragePool storage_pool = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.netapp.v1.StoragePool,
com.google.cloud.netapp.v1.StoragePool.Builder,
com.google.cloud.netapp.v1.StoragePoolOrBuilder>
getStoragePoolFieldBuilder() {
if (storagePoolBuilder_ == null) {
storagePoolBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.netapp.v1.StoragePool,
com.google.cloud.netapp.v1.StoragePool.Builder,
com.google.cloud.netapp.v1.StoragePoolOrBuilder>(
getStoragePool(), getParentForChildren(), isClean());
storagePool_ = null;
}
return storagePoolBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.netapp.v1.UpdateStoragePoolRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.netapp.v1.UpdateStoragePoolRequest)
private static final com.google.cloud.netapp.v1.UpdateStoragePoolRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.netapp.v1.UpdateStoragePoolRequest();
}
public static com.google.cloud.netapp.v1.UpdateStoragePoolRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateStoragePoolRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateStoragePoolRequest>() {
@java.lang.Override
public UpdateStoragePoolRequest 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<UpdateStoragePoolRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateStoragePoolRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.netapp.v1.UpdateStoragePoolRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,410 | java-retail/proto-google-cloud-retail-v2beta/src/main/java/com/google/cloud/retail/v2beta/PurgeProductsMetadata.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/v2beta/purge_config.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.retail.v2beta;
/**
*
*
* <pre>
* Metadata related to the progress of the PurgeProducts operation.
* This will be returned by the google.longrunning.Operation.metadata field.
* </pre>
*
* Protobuf type {@code google.cloud.retail.v2beta.PurgeProductsMetadata}
*/
public final class PurgeProductsMetadata extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.retail.v2beta.PurgeProductsMetadata)
PurgeProductsMetadataOrBuilder {
private static final long serialVersionUID = 0L;
// Use PurgeProductsMetadata.newBuilder() to construct.
private PurgeProductsMetadata(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private PurgeProductsMetadata() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new PurgeProductsMetadata();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.retail.v2beta.PurgeConfigProto
.internal_static_google_cloud_retail_v2beta_PurgeProductsMetadata_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.retail.v2beta.PurgeConfigProto
.internal_static_google_cloud_retail_v2beta_PurgeProductsMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.retail.v2beta.PurgeProductsMetadata.class,
com.google.cloud.retail.v2beta.PurgeProductsMetadata.Builder.class);
}
private int bitField0_;
public static final int CREATE_TIME_FIELD_NUMBER = 1;
private com.google.protobuf.Timestamp createTime_;
/**
*
*
* <pre>
* Operation create time.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 1;</code>
*
* @return Whether the createTime field is set.
*/
@java.lang.Override
public boolean hasCreateTime() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Operation create time.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 1;</code>
*
* @return The createTime.
*/
@java.lang.Override
public com.google.protobuf.Timestamp getCreateTime() {
return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_;
}
/**
*
*
* <pre>
* Operation create time.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 1;</code>
*/
@java.lang.Override
public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() {
return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_;
}
public static final int UPDATE_TIME_FIELD_NUMBER = 2;
private com.google.protobuf.Timestamp updateTime_;
/**
*
*
* <pre>
* Operation last update time. If the operation is done, this is also the
* finish time.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 2;</code>
*
* @return Whether the updateTime field is set.
*/
@java.lang.Override
public boolean hasUpdateTime() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Operation last update time. If the operation is done, this is also the
* finish time.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 2;</code>
*
* @return The updateTime.
*/
@java.lang.Override
public com.google.protobuf.Timestamp getUpdateTime() {
return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_;
}
/**
*
*
* <pre>
* Operation last update time. If the operation is done, this is also the
* finish time.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.TimestampOrBuilder getUpdateTimeOrBuilder() {
return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_;
}
public static final int SUCCESS_COUNT_FIELD_NUMBER = 3;
private long successCount_ = 0L;
/**
*
*
* <pre>
* Count of entries that were deleted successfully.
* </pre>
*
* <code>int64 success_count = 3;</code>
*
* @return The successCount.
*/
@java.lang.Override
public long getSuccessCount() {
return successCount_;
}
public static final int FAILURE_COUNT_FIELD_NUMBER = 4;
private long failureCount_ = 0L;
/**
*
*
* <pre>
* Count of entries that encountered errors while processing.
* </pre>
*
* <code>int64 failure_count = 4;</code>
*
* @return The failureCount.
*/
@java.lang.Override
public long getFailureCount() {
return failureCount_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getCreateTime());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getUpdateTime());
}
if (successCount_ != 0L) {
output.writeInt64(3, successCount_);
}
if (failureCount_ != 0L) {
output.writeInt64(4, failureCount_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getCreateTime());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateTime());
}
if (successCount_ != 0L) {
size += com.google.protobuf.CodedOutputStream.computeInt64Size(3, successCount_);
}
if (failureCount_ != 0L) {
size += com.google.protobuf.CodedOutputStream.computeInt64Size(4, failureCount_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.retail.v2beta.PurgeProductsMetadata)) {
return super.equals(obj);
}
com.google.cloud.retail.v2beta.PurgeProductsMetadata other =
(com.google.cloud.retail.v2beta.PurgeProductsMetadata) obj;
if (hasCreateTime() != other.hasCreateTime()) return false;
if (hasCreateTime()) {
if (!getCreateTime().equals(other.getCreateTime())) return false;
}
if (hasUpdateTime() != other.hasUpdateTime()) return false;
if (hasUpdateTime()) {
if (!getUpdateTime().equals(other.getUpdateTime())) return false;
}
if (getSuccessCount() != other.getSuccessCount()) return false;
if (getFailureCount() != other.getFailureCount()) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasCreateTime()) {
hash = (37 * hash) + CREATE_TIME_FIELD_NUMBER;
hash = (53 * hash) + getCreateTime().hashCode();
}
if (hasUpdateTime()) {
hash = (37 * hash) + UPDATE_TIME_FIELD_NUMBER;
hash = (53 * hash) + getUpdateTime().hashCode();
}
hash = (37 * hash) + SUCCESS_COUNT_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getSuccessCount());
hash = (37 * hash) + FAILURE_COUNT_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getFailureCount());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.retail.v2beta.PurgeProductsMetadata parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.retail.v2beta.PurgeProductsMetadata 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.v2beta.PurgeProductsMetadata parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.retail.v2beta.PurgeProductsMetadata 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.v2beta.PurgeProductsMetadata parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.retail.v2beta.PurgeProductsMetadata parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.retail.v2beta.PurgeProductsMetadata parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.retail.v2beta.PurgeProductsMetadata 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.v2beta.PurgeProductsMetadata parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.retail.v2beta.PurgeProductsMetadata 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.v2beta.PurgeProductsMetadata parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.retail.v2beta.PurgeProductsMetadata 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.v2beta.PurgeProductsMetadata prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Metadata related to the progress of the PurgeProducts operation.
* This will be returned by the google.longrunning.Operation.metadata field.
* </pre>
*
* Protobuf type {@code google.cloud.retail.v2beta.PurgeProductsMetadata}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.retail.v2beta.PurgeProductsMetadata)
com.google.cloud.retail.v2beta.PurgeProductsMetadataOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.retail.v2beta.PurgeConfigProto
.internal_static_google_cloud_retail_v2beta_PurgeProductsMetadata_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.retail.v2beta.PurgeConfigProto
.internal_static_google_cloud_retail_v2beta_PurgeProductsMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.retail.v2beta.PurgeProductsMetadata.class,
com.google.cloud.retail.v2beta.PurgeProductsMetadata.Builder.class);
}
// Construct using com.google.cloud.retail.v2beta.PurgeProductsMetadata.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getCreateTimeFieldBuilder();
getUpdateTimeFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
createTime_ = null;
if (createTimeBuilder_ != null) {
createTimeBuilder_.dispose();
createTimeBuilder_ = null;
}
updateTime_ = null;
if (updateTimeBuilder_ != null) {
updateTimeBuilder_.dispose();
updateTimeBuilder_ = null;
}
successCount_ = 0L;
failureCount_ = 0L;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.retail.v2beta.PurgeConfigProto
.internal_static_google_cloud_retail_v2beta_PurgeProductsMetadata_descriptor;
}
@java.lang.Override
public com.google.cloud.retail.v2beta.PurgeProductsMetadata getDefaultInstanceForType() {
return com.google.cloud.retail.v2beta.PurgeProductsMetadata.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.retail.v2beta.PurgeProductsMetadata build() {
com.google.cloud.retail.v2beta.PurgeProductsMetadata result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.retail.v2beta.PurgeProductsMetadata buildPartial() {
com.google.cloud.retail.v2beta.PurgeProductsMetadata result =
new com.google.cloud.retail.v2beta.PurgeProductsMetadata(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.retail.v2beta.PurgeProductsMetadata result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.createTime_ = createTimeBuilder_ == null ? createTime_ : createTimeBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.updateTime_ = updateTimeBuilder_ == null ? updateTime_ : updateTimeBuilder_.build();
to_bitField0_ |= 0x00000002;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.successCount_ = successCount_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.failureCount_ = failureCount_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.retail.v2beta.PurgeProductsMetadata) {
return mergeFrom((com.google.cloud.retail.v2beta.PurgeProductsMetadata) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.retail.v2beta.PurgeProductsMetadata other) {
if (other == com.google.cloud.retail.v2beta.PurgeProductsMetadata.getDefaultInstance())
return this;
if (other.hasCreateTime()) {
mergeCreateTime(other.getCreateTime());
}
if (other.hasUpdateTime()) {
mergeUpdateTime(other.getUpdateTime());
}
if (other.getSuccessCount() != 0L) {
setSuccessCount(other.getSuccessCount());
}
if (other.getFailureCount() != 0L) {
setFailureCount(other.getFailureCount());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(getCreateTimeFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getUpdateTimeFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 24:
{
successCount_ = input.readInt64();
bitField0_ |= 0x00000004;
break;
} // case 24
case 32:
{
failureCount_ = input.readInt64();
bitField0_ |= 0x00000008;
break;
} // case 32
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.protobuf.Timestamp createTime_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
createTimeBuilder_;
/**
*
*
* <pre>
* Operation create time.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 1;</code>
*
* @return Whether the createTime field is set.
*/
public boolean hasCreateTime() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Operation create time.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 1;</code>
*
* @return The createTime.
*/
public com.google.protobuf.Timestamp getCreateTime() {
if (createTimeBuilder_ == null) {
return createTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: createTime_;
} else {
return createTimeBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Operation create time.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 1;</code>
*/
public Builder setCreateTime(com.google.protobuf.Timestamp value) {
if (createTimeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
createTime_ = value;
} else {
createTimeBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Operation create time.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 1;</code>
*/
public Builder setCreateTime(com.google.protobuf.Timestamp.Builder builderForValue) {
if (createTimeBuilder_ == null) {
createTime_ = builderForValue.build();
} else {
createTimeBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Operation create time.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 1;</code>
*/
public Builder mergeCreateTime(com.google.protobuf.Timestamp value) {
if (createTimeBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& createTime_ != null
&& createTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) {
getCreateTimeBuilder().mergeFrom(value);
} else {
createTime_ = value;
}
} else {
createTimeBuilder_.mergeFrom(value);
}
if (createTime_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Operation create time.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 1;</code>
*/
public Builder clearCreateTime() {
bitField0_ = (bitField0_ & ~0x00000001);
createTime_ = null;
if (createTimeBuilder_ != null) {
createTimeBuilder_.dispose();
createTimeBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Operation create time.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 1;</code>
*/
public com.google.protobuf.Timestamp.Builder getCreateTimeBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getCreateTimeFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Operation create time.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 1;</code>
*/
public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() {
if (createTimeBuilder_ != null) {
return createTimeBuilder_.getMessageOrBuilder();
} else {
return createTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: createTime_;
}
}
/**
*
*
* <pre>
* Operation create time.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
getCreateTimeFieldBuilder() {
if (createTimeBuilder_ == null) {
createTimeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>(
getCreateTime(), getParentForChildren(), isClean());
createTime_ = null;
}
return createTimeBuilder_;
}
private com.google.protobuf.Timestamp updateTime_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
updateTimeBuilder_;
/**
*
*
* <pre>
* Operation last update time. If the operation is done, this is also the
* finish time.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 2;</code>
*
* @return Whether the updateTime field is set.
*/
public boolean hasUpdateTime() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Operation last update time. If the operation is done, this is also the
* finish time.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 2;</code>
*
* @return The updateTime.
*/
public com.google.protobuf.Timestamp getUpdateTime() {
if (updateTimeBuilder_ == null) {
return updateTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: updateTime_;
} else {
return updateTimeBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Operation last update time. If the operation is done, this is also the
* finish time.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 2;</code>
*/
public Builder setUpdateTime(com.google.protobuf.Timestamp value) {
if (updateTimeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateTime_ = value;
} else {
updateTimeBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Operation last update time. If the operation is done, this is also the
* finish time.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 2;</code>
*/
public Builder setUpdateTime(com.google.protobuf.Timestamp.Builder builderForValue) {
if (updateTimeBuilder_ == null) {
updateTime_ = builderForValue.build();
} else {
updateTimeBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Operation last update time. If the operation is done, this is also the
* finish time.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 2;</code>
*/
public Builder mergeUpdateTime(com.google.protobuf.Timestamp value) {
if (updateTimeBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& updateTime_ != null
&& updateTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) {
getUpdateTimeBuilder().mergeFrom(value);
} else {
updateTime_ = value;
}
} else {
updateTimeBuilder_.mergeFrom(value);
}
if (updateTime_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Operation last update time. If the operation is done, this is also the
* finish time.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 2;</code>
*/
public Builder clearUpdateTime() {
bitField0_ = (bitField0_ & ~0x00000002);
updateTime_ = null;
if (updateTimeBuilder_ != null) {
updateTimeBuilder_.dispose();
updateTimeBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Operation last update time. If the operation is done, this is also the
* finish time.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 2;</code>
*/
public com.google.protobuf.Timestamp.Builder getUpdateTimeBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateTimeFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Operation last update time. If the operation is done, this is also the
* finish time.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 2;</code>
*/
public com.google.protobuf.TimestampOrBuilder getUpdateTimeOrBuilder() {
if (updateTimeBuilder_ != null) {
return updateTimeBuilder_.getMessageOrBuilder();
} else {
return updateTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: updateTime_;
}
}
/**
*
*
* <pre>
* Operation last update time. If the operation is done, this is also the
* finish time.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
getUpdateTimeFieldBuilder() {
if (updateTimeBuilder_ == null) {
updateTimeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>(
getUpdateTime(), getParentForChildren(), isClean());
updateTime_ = null;
}
return updateTimeBuilder_;
}
private long successCount_;
/**
*
*
* <pre>
* Count of entries that were deleted successfully.
* </pre>
*
* <code>int64 success_count = 3;</code>
*
* @return The successCount.
*/
@java.lang.Override
public long getSuccessCount() {
return successCount_;
}
/**
*
*
* <pre>
* Count of entries that were deleted successfully.
* </pre>
*
* <code>int64 success_count = 3;</code>
*
* @param value The successCount to set.
* @return This builder for chaining.
*/
public Builder setSuccessCount(long value) {
successCount_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Count of entries that were deleted successfully.
* </pre>
*
* <code>int64 success_count = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearSuccessCount() {
bitField0_ = (bitField0_ & ~0x00000004);
successCount_ = 0L;
onChanged();
return this;
}
private long failureCount_;
/**
*
*
* <pre>
* Count of entries that encountered errors while processing.
* </pre>
*
* <code>int64 failure_count = 4;</code>
*
* @return The failureCount.
*/
@java.lang.Override
public long getFailureCount() {
return failureCount_;
}
/**
*
*
* <pre>
* Count of entries that encountered errors while processing.
* </pre>
*
* <code>int64 failure_count = 4;</code>
*
* @param value The failureCount to set.
* @return This builder for chaining.
*/
public Builder setFailureCount(long value) {
failureCount_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Count of entries that encountered errors while processing.
* </pre>
*
* <code>int64 failure_count = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearFailureCount() {
bitField0_ = (bitField0_ & ~0x00000008);
failureCount_ = 0L;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.retail.v2beta.PurgeProductsMetadata)
}
// @@protoc_insertion_point(class_scope:google.cloud.retail.v2beta.PurgeProductsMetadata)
private static final com.google.cloud.retail.v2beta.PurgeProductsMetadata DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.retail.v2beta.PurgeProductsMetadata();
}
public static com.google.cloud.retail.v2beta.PurgeProductsMetadata getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<PurgeProductsMetadata> PARSER =
new com.google.protobuf.AbstractParser<PurgeProductsMetadata>() {
@java.lang.Override
public PurgeProductsMetadata 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<PurgeProductsMetadata> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<PurgeProductsMetadata> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.retail.v2beta.PurgeProductsMetadata getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,751 | java-bigquery-data-exchange/google-cloud-bigquery-data-exchange/src/main/java/com/google/cloud/bigquery/dataexchange/v1beta1/stub/GrpcAnalyticsHubServiceStub.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.bigquery.dataexchange.v1beta1.stub;
import static com.google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubServiceClient.ListDataExchangesPagedResponse;
import static com.google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubServiceClient.ListListingsPagedResponse;
import static com.google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubServiceClient.ListLocationsPagedResponse;
import static com.google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubServiceClient.ListOrgDataExchangesPagedResponse;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.core.BackgroundResourceAggregation;
import com.google.api.gax.grpc.GrpcCallSettings;
import com.google.api.gax.grpc.GrpcStubCallableFactory;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.RequestParamsBuilder;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.bigquery.dataexchange.v1beta1.CreateDataExchangeRequest;
import com.google.cloud.bigquery.dataexchange.v1beta1.CreateListingRequest;
import com.google.cloud.bigquery.dataexchange.v1beta1.DataExchange;
import com.google.cloud.bigquery.dataexchange.v1beta1.DeleteDataExchangeRequest;
import com.google.cloud.bigquery.dataexchange.v1beta1.DeleteListingRequest;
import com.google.cloud.bigquery.dataexchange.v1beta1.GetDataExchangeRequest;
import com.google.cloud.bigquery.dataexchange.v1beta1.GetListingRequest;
import com.google.cloud.bigquery.dataexchange.v1beta1.ListDataExchangesRequest;
import com.google.cloud.bigquery.dataexchange.v1beta1.ListDataExchangesResponse;
import com.google.cloud.bigquery.dataexchange.v1beta1.ListListingsRequest;
import com.google.cloud.bigquery.dataexchange.v1beta1.ListListingsResponse;
import com.google.cloud.bigquery.dataexchange.v1beta1.ListOrgDataExchangesRequest;
import com.google.cloud.bigquery.dataexchange.v1beta1.ListOrgDataExchangesResponse;
import com.google.cloud.bigquery.dataexchange.v1beta1.Listing;
import com.google.cloud.bigquery.dataexchange.v1beta1.SubscribeListingRequest;
import com.google.cloud.bigquery.dataexchange.v1beta1.SubscribeListingResponse;
import com.google.cloud.bigquery.dataexchange.v1beta1.UpdateDataExchangeRequest;
import com.google.cloud.bigquery.dataexchange.v1beta1.UpdateListingRequest;
import com.google.cloud.location.GetLocationRequest;
import com.google.cloud.location.ListLocationsRequest;
import com.google.cloud.location.ListLocationsResponse;
import com.google.cloud.location.Location;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.iam.v1.TestIamPermissionsRequest;
import com.google.iam.v1.TestIamPermissionsResponse;
import com.google.longrunning.stub.GrpcOperationsStub;
import com.google.protobuf.Empty;
import io.grpc.MethodDescriptor;
import io.grpc.protobuf.ProtoUtils;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* gRPC stub implementation for the AnalyticsHubService service API.
*
* <p>This class is for advanced usage and reflects the underlying API directly.
*/
@BetaApi
@Generated("by gapic-generator-java")
public class GrpcAnalyticsHubServiceStub extends AnalyticsHubServiceStub {
private static final MethodDescriptor<ListDataExchangesRequest, ListDataExchangesResponse>
listDataExchangesMethodDescriptor =
MethodDescriptor.<ListDataExchangesRequest, ListDataExchangesResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubService/ListDataExchanges")
.setRequestMarshaller(
ProtoUtils.marshaller(ListDataExchangesRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(ListDataExchangesResponse.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<ListOrgDataExchangesRequest, ListOrgDataExchangesResponse>
listOrgDataExchangesMethodDescriptor =
MethodDescriptor.<ListOrgDataExchangesRequest, ListOrgDataExchangesResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubService/ListOrgDataExchanges")
.setRequestMarshaller(
ProtoUtils.marshaller(ListOrgDataExchangesRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(ListOrgDataExchangesResponse.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<GetDataExchangeRequest, DataExchange>
getDataExchangeMethodDescriptor =
MethodDescriptor.<GetDataExchangeRequest, DataExchange>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubService/GetDataExchange")
.setRequestMarshaller(
ProtoUtils.marshaller(GetDataExchangeRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(DataExchange.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<CreateDataExchangeRequest, DataExchange>
createDataExchangeMethodDescriptor =
MethodDescriptor.<CreateDataExchangeRequest, DataExchange>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubService/CreateDataExchange")
.setRequestMarshaller(
ProtoUtils.marshaller(CreateDataExchangeRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(DataExchange.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<UpdateDataExchangeRequest, DataExchange>
updateDataExchangeMethodDescriptor =
MethodDescriptor.<UpdateDataExchangeRequest, DataExchange>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubService/UpdateDataExchange")
.setRequestMarshaller(
ProtoUtils.marshaller(UpdateDataExchangeRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(DataExchange.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<DeleteDataExchangeRequest, Empty>
deleteDataExchangeMethodDescriptor =
MethodDescriptor.<DeleteDataExchangeRequest, Empty>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubService/DeleteDataExchange")
.setRequestMarshaller(
ProtoUtils.marshaller(DeleteDataExchangeRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<ListListingsRequest, ListListingsResponse>
listListingsMethodDescriptor =
MethodDescriptor.<ListListingsRequest, ListListingsResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubService/ListListings")
.setRequestMarshaller(ProtoUtils.marshaller(ListListingsRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(ListListingsResponse.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<GetListingRequest, Listing> getListingMethodDescriptor =
MethodDescriptor.<GetListingRequest, Listing>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubService/GetListing")
.setRequestMarshaller(ProtoUtils.marshaller(GetListingRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Listing.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<CreateListingRequest, Listing>
createListingMethodDescriptor =
MethodDescriptor.<CreateListingRequest, Listing>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubService/CreateListing")
.setRequestMarshaller(
ProtoUtils.marshaller(CreateListingRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Listing.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<UpdateListingRequest, Listing>
updateListingMethodDescriptor =
MethodDescriptor.<UpdateListingRequest, Listing>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubService/UpdateListing")
.setRequestMarshaller(
ProtoUtils.marshaller(UpdateListingRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Listing.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<DeleteListingRequest, Empty> deleteListingMethodDescriptor =
MethodDescriptor.<DeleteListingRequest, Empty>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubService/DeleteListing")
.setRequestMarshaller(ProtoUtils.marshaller(DeleteListingRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<SubscribeListingRequest, SubscribeListingResponse>
subscribeListingMethodDescriptor =
MethodDescriptor.<SubscribeListingRequest, SubscribeListingResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubService/SubscribeListing")
.setRequestMarshaller(
ProtoUtils.marshaller(SubscribeListingRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(SubscribeListingResponse.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<GetIamPolicyRequest, Policy> getIamPolicyMethodDescriptor =
MethodDescriptor.<GetIamPolicyRequest, Policy>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubService/GetIamPolicy")
.setRequestMarshaller(ProtoUtils.marshaller(GetIamPolicyRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<SetIamPolicyRequest, Policy> setIamPolicyMethodDescriptor =
MethodDescriptor.<SetIamPolicyRequest, Policy>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubService/SetIamPolicy")
.setRequestMarshaller(ProtoUtils.marshaller(SetIamPolicyRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsMethodDescriptor =
MethodDescriptor.<TestIamPermissionsRequest, TestIamPermissionsResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.cloud.bigquery.dataexchange.v1beta1.AnalyticsHubService/TestIamPermissions")
.setRequestMarshaller(
ProtoUtils.marshaller(TestIamPermissionsRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(TestIamPermissionsResponse.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<ListLocationsRequest, ListLocationsResponse>
listLocationsMethodDescriptor =
MethodDescriptor.<ListLocationsRequest, ListLocationsResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.cloud.location.Locations/ListLocations")
.setRequestMarshaller(
ProtoUtils.marshaller(ListLocationsRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(ListLocationsResponse.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private static final MethodDescriptor<GetLocationRequest, Location> getLocationMethodDescriptor =
MethodDescriptor.<GetLocationRequest, Location>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.cloud.location.Locations/GetLocation")
.setRequestMarshaller(ProtoUtils.marshaller(GetLocationRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Location.getDefaultInstance()))
.setSampledToLocalTracing(true)
.build();
private final UnaryCallable<ListDataExchangesRequest, ListDataExchangesResponse>
listDataExchangesCallable;
private final UnaryCallable<ListDataExchangesRequest, ListDataExchangesPagedResponse>
listDataExchangesPagedCallable;
private final UnaryCallable<ListOrgDataExchangesRequest, ListOrgDataExchangesResponse>
listOrgDataExchangesCallable;
private final UnaryCallable<ListOrgDataExchangesRequest, ListOrgDataExchangesPagedResponse>
listOrgDataExchangesPagedCallable;
private final UnaryCallable<GetDataExchangeRequest, DataExchange> getDataExchangeCallable;
private final UnaryCallable<CreateDataExchangeRequest, DataExchange> createDataExchangeCallable;
private final UnaryCallable<UpdateDataExchangeRequest, DataExchange> updateDataExchangeCallable;
private final UnaryCallable<DeleteDataExchangeRequest, Empty> deleteDataExchangeCallable;
private final UnaryCallable<ListListingsRequest, ListListingsResponse> listListingsCallable;
private final UnaryCallable<ListListingsRequest, ListListingsPagedResponse>
listListingsPagedCallable;
private final UnaryCallable<GetListingRequest, Listing> getListingCallable;
private final UnaryCallable<CreateListingRequest, Listing> createListingCallable;
private final UnaryCallable<UpdateListingRequest, Listing> updateListingCallable;
private final UnaryCallable<DeleteListingRequest, Empty> deleteListingCallable;
private final UnaryCallable<SubscribeListingRequest, SubscribeListingResponse>
subscribeListingCallable;
private final UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable;
private final UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable;
private final UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsCallable;
private final UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable;
private final UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse>
listLocationsPagedCallable;
private final UnaryCallable<GetLocationRequest, Location> getLocationCallable;
private final BackgroundResource backgroundResources;
private final GrpcOperationsStub operationsStub;
private final GrpcStubCallableFactory callableFactory;
public static final GrpcAnalyticsHubServiceStub create(AnalyticsHubServiceStubSettings settings)
throws IOException {
return new GrpcAnalyticsHubServiceStub(settings, ClientContext.create(settings));
}
public static final GrpcAnalyticsHubServiceStub create(ClientContext clientContext)
throws IOException {
return new GrpcAnalyticsHubServiceStub(
AnalyticsHubServiceStubSettings.newBuilder().build(), clientContext);
}
public static final GrpcAnalyticsHubServiceStub create(
ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException {
return new GrpcAnalyticsHubServiceStub(
AnalyticsHubServiceStubSettings.newBuilder().build(), clientContext, callableFactory);
}
/**
* Constructs an instance of GrpcAnalyticsHubServiceStub, 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 GrpcAnalyticsHubServiceStub(
AnalyticsHubServiceStubSettings settings, ClientContext clientContext) throws IOException {
this(settings, clientContext, new GrpcAnalyticsHubServiceCallableFactory());
}
/**
* Constructs an instance of GrpcAnalyticsHubServiceStub, 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 GrpcAnalyticsHubServiceStub(
AnalyticsHubServiceStubSettings settings,
ClientContext clientContext,
GrpcStubCallableFactory callableFactory)
throws IOException {
this.callableFactory = callableFactory;
this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory);
GrpcCallSettings<ListDataExchangesRequest, ListDataExchangesResponse>
listDataExchangesTransportSettings =
GrpcCallSettings.<ListDataExchangesRequest, ListDataExchangesResponse>newBuilder()
.setMethodDescriptor(listDataExchangesMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
GrpcCallSettings<ListOrgDataExchangesRequest, ListOrgDataExchangesResponse>
listOrgDataExchangesTransportSettings =
GrpcCallSettings.<ListOrgDataExchangesRequest, ListOrgDataExchangesResponse>newBuilder()
.setMethodDescriptor(listOrgDataExchangesMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("organization", String.valueOf(request.getOrganization()));
return builder.build();
})
.build();
GrpcCallSettings<GetDataExchangeRequest, DataExchange> getDataExchangeTransportSettings =
GrpcCallSettings.<GetDataExchangeRequest, DataExchange>newBuilder()
.setMethodDescriptor(getDataExchangeMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
GrpcCallSettings<CreateDataExchangeRequest, DataExchange> createDataExchangeTransportSettings =
GrpcCallSettings.<CreateDataExchangeRequest, DataExchange>newBuilder()
.setMethodDescriptor(createDataExchangeMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
GrpcCallSettings<UpdateDataExchangeRequest, DataExchange> updateDataExchangeTransportSettings =
GrpcCallSettings.<UpdateDataExchangeRequest, DataExchange>newBuilder()
.setMethodDescriptor(updateDataExchangeMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add(
"data_exchange.name", String.valueOf(request.getDataExchange().getName()));
return builder.build();
})
.build();
GrpcCallSettings<DeleteDataExchangeRequest, Empty> deleteDataExchangeTransportSettings =
GrpcCallSettings.<DeleteDataExchangeRequest, Empty>newBuilder()
.setMethodDescriptor(deleteDataExchangeMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
GrpcCallSettings<ListListingsRequest, ListListingsResponse> listListingsTransportSettings =
GrpcCallSettings.<ListListingsRequest, ListListingsResponse>newBuilder()
.setMethodDescriptor(listListingsMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
GrpcCallSettings<GetListingRequest, Listing> getListingTransportSettings =
GrpcCallSettings.<GetListingRequest, Listing>newBuilder()
.setMethodDescriptor(getListingMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
GrpcCallSettings<CreateListingRequest, Listing> createListingTransportSettings =
GrpcCallSettings.<CreateListingRequest, Listing>newBuilder()
.setMethodDescriptor(createListingMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
GrpcCallSettings<UpdateListingRequest, Listing> updateListingTransportSettings =
GrpcCallSettings.<UpdateListingRequest, Listing>newBuilder()
.setMethodDescriptor(updateListingMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("listing.name", String.valueOf(request.getListing().getName()));
return builder.build();
})
.build();
GrpcCallSettings<DeleteListingRequest, Empty> deleteListingTransportSettings =
GrpcCallSettings.<DeleteListingRequest, Empty>newBuilder()
.setMethodDescriptor(deleteListingMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
GrpcCallSettings<SubscribeListingRequest, SubscribeListingResponse>
subscribeListingTransportSettings =
GrpcCallSettings.<SubscribeListingRequest, SubscribeListingResponse>newBuilder()
.setMethodDescriptor(subscribeListingMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
GrpcCallSettings<GetIamPolicyRequest, Policy> getIamPolicyTransportSettings =
GrpcCallSettings.<GetIamPolicyRequest, Policy>newBuilder()
.setMethodDescriptor(getIamPolicyMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("resource", String.valueOf(request.getResource()));
return builder.build();
})
.build();
GrpcCallSettings<SetIamPolicyRequest, Policy> setIamPolicyTransportSettings =
GrpcCallSettings.<SetIamPolicyRequest, Policy>newBuilder()
.setMethodDescriptor(setIamPolicyMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("resource", String.valueOf(request.getResource()));
return builder.build();
})
.build();
GrpcCallSettings<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsTransportSettings =
GrpcCallSettings.<TestIamPermissionsRequest, TestIamPermissionsResponse>newBuilder()
.setMethodDescriptor(testIamPermissionsMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("resource", String.valueOf(request.getResource()));
return builder.build();
})
.build();
GrpcCallSettings<ListLocationsRequest, ListLocationsResponse> listLocationsTransportSettings =
GrpcCallSettings.<ListLocationsRequest, ListLocationsResponse>newBuilder()
.setMethodDescriptor(listLocationsMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
GrpcCallSettings<GetLocationRequest, Location> getLocationTransportSettings =
GrpcCallSettings.<GetLocationRequest, Location>newBuilder()
.setMethodDescriptor(getLocationMethodDescriptor)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
this.listDataExchangesCallable =
callableFactory.createUnaryCallable(
listDataExchangesTransportSettings,
settings.listDataExchangesSettings(),
clientContext);
this.listDataExchangesPagedCallable =
callableFactory.createPagedCallable(
listDataExchangesTransportSettings,
settings.listDataExchangesSettings(),
clientContext);
this.listOrgDataExchangesCallable =
callableFactory.createUnaryCallable(
listOrgDataExchangesTransportSettings,
settings.listOrgDataExchangesSettings(),
clientContext);
this.listOrgDataExchangesPagedCallable =
callableFactory.createPagedCallable(
listOrgDataExchangesTransportSettings,
settings.listOrgDataExchangesSettings(),
clientContext);
this.getDataExchangeCallable =
callableFactory.createUnaryCallable(
getDataExchangeTransportSettings, settings.getDataExchangeSettings(), clientContext);
this.createDataExchangeCallable =
callableFactory.createUnaryCallable(
createDataExchangeTransportSettings,
settings.createDataExchangeSettings(),
clientContext);
this.updateDataExchangeCallable =
callableFactory.createUnaryCallable(
updateDataExchangeTransportSettings,
settings.updateDataExchangeSettings(),
clientContext);
this.deleteDataExchangeCallable =
callableFactory.createUnaryCallable(
deleteDataExchangeTransportSettings,
settings.deleteDataExchangeSettings(),
clientContext);
this.listListingsCallable =
callableFactory.createUnaryCallable(
listListingsTransportSettings, settings.listListingsSettings(), clientContext);
this.listListingsPagedCallable =
callableFactory.createPagedCallable(
listListingsTransportSettings, settings.listListingsSettings(), clientContext);
this.getListingCallable =
callableFactory.createUnaryCallable(
getListingTransportSettings, settings.getListingSettings(), clientContext);
this.createListingCallable =
callableFactory.createUnaryCallable(
createListingTransportSettings, settings.createListingSettings(), clientContext);
this.updateListingCallable =
callableFactory.createUnaryCallable(
updateListingTransportSettings, settings.updateListingSettings(), clientContext);
this.deleteListingCallable =
callableFactory.createUnaryCallable(
deleteListingTransportSettings, settings.deleteListingSettings(), clientContext);
this.subscribeListingCallable =
callableFactory.createUnaryCallable(
subscribeListingTransportSettings, settings.subscribeListingSettings(), clientContext);
this.getIamPolicyCallable =
callableFactory.createUnaryCallable(
getIamPolicyTransportSettings, settings.getIamPolicySettings(), clientContext);
this.setIamPolicyCallable =
callableFactory.createUnaryCallable(
setIamPolicyTransportSettings, settings.setIamPolicySettings(), clientContext);
this.testIamPermissionsCallable =
callableFactory.createUnaryCallable(
testIamPermissionsTransportSettings,
settings.testIamPermissionsSettings(),
clientContext);
this.listLocationsCallable =
callableFactory.createUnaryCallable(
listLocationsTransportSettings, settings.listLocationsSettings(), clientContext);
this.listLocationsPagedCallable =
callableFactory.createPagedCallable(
listLocationsTransportSettings, settings.listLocationsSettings(), clientContext);
this.getLocationCallable =
callableFactory.createUnaryCallable(
getLocationTransportSettings, settings.getLocationSettings(), clientContext);
this.backgroundResources =
new BackgroundResourceAggregation(clientContext.getBackgroundResources());
}
public GrpcOperationsStub getOperationsStub() {
return operationsStub;
}
@Override
public UnaryCallable<ListDataExchangesRequest, ListDataExchangesResponse>
listDataExchangesCallable() {
return listDataExchangesCallable;
}
@Override
public UnaryCallable<ListDataExchangesRequest, ListDataExchangesPagedResponse>
listDataExchangesPagedCallable() {
return listDataExchangesPagedCallable;
}
@Override
public UnaryCallable<ListOrgDataExchangesRequest, ListOrgDataExchangesResponse>
listOrgDataExchangesCallable() {
return listOrgDataExchangesCallable;
}
@Override
public UnaryCallable<ListOrgDataExchangesRequest, ListOrgDataExchangesPagedResponse>
listOrgDataExchangesPagedCallable() {
return listOrgDataExchangesPagedCallable;
}
@Override
public UnaryCallable<GetDataExchangeRequest, DataExchange> getDataExchangeCallable() {
return getDataExchangeCallable;
}
@Override
public UnaryCallable<CreateDataExchangeRequest, DataExchange> createDataExchangeCallable() {
return createDataExchangeCallable;
}
@Override
public UnaryCallable<UpdateDataExchangeRequest, DataExchange> updateDataExchangeCallable() {
return updateDataExchangeCallable;
}
@Override
public UnaryCallable<DeleteDataExchangeRequest, Empty> deleteDataExchangeCallable() {
return deleteDataExchangeCallable;
}
@Override
public UnaryCallable<ListListingsRequest, ListListingsResponse> listListingsCallable() {
return listListingsCallable;
}
@Override
public UnaryCallable<ListListingsRequest, ListListingsPagedResponse> listListingsPagedCallable() {
return listListingsPagedCallable;
}
@Override
public UnaryCallable<GetListingRequest, Listing> getListingCallable() {
return getListingCallable;
}
@Override
public UnaryCallable<CreateListingRequest, Listing> createListingCallable() {
return createListingCallable;
}
@Override
public UnaryCallable<UpdateListingRequest, Listing> updateListingCallable() {
return updateListingCallable;
}
@Override
public UnaryCallable<DeleteListingRequest, Empty> deleteListingCallable() {
return deleteListingCallable;
}
@Override
public UnaryCallable<SubscribeListingRequest, SubscribeListingResponse>
subscribeListingCallable() {
return subscribeListingCallable;
}
@Override
public UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable() {
return getIamPolicyCallable;
}
@Override
public UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable() {
return setIamPolicyCallable;
}
@Override
public UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsCallable() {
return testIamPermissionsCallable;
}
@Override
public UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable() {
return listLocationsCallable;
}
@Override
public UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse>
listLocationsPagedCallable() {
return listLocationsPagedCallable;
}
@Override
public UnaryCallable<GetLocationRequest, Location> getLocationCallable() {
return getLocationCallable;
}
@Override
public final void close() {
try {
backgroundResources.close();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Failed to close resource", e);
}
}
@Override
public void shutdown() {
backgroundResources.shutdown();
}
@Override
public boolean isShutdown() {
return backgroundResources.isShutdown();
}
@Override
public boolean isTerminated() {
return backgroundResources.isTerminated();
}
@Override
public void shutdownNow() {
backgroundResources.shutdownNow();
}
@Override
public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
return backgroundResources.awaitTermination(duration, unit);
}
}
|
apache/jena | 35,770 | jena-core/src/test/java/org/apache/jena/mem2/AbstractGraphMem2Test.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.mem2;
import static org.apache.jena.testing_framework.GraphHelper.node;
import static org.apache.jena.testing_framework.GraphHelper.triple;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.apache.jena.datatypes.xsd.impl.XSDDouble;
import org.apache.jena.graph.NodeFactory;
import org.apache.jena.graph.Triple;
import org.hamcrest.collection.IsEmptyCollection;
import org.hamcrest.collection.IsIterableContainingInAnyOrder;
public abstract class AbstractGraphMem2Test {
protected GraphMem2 sut;
protected abstract GraphMem2 createGraph();
@Before
public void setUp() throws Exception {
sut = createGraph();
}
@Test
public void testClear() {
sut.add(triple("x R y"));
assertEquals(1, sut.size());
sut.clear();
assertEquals(0, sut.size());
assertTrue(sut.isEmpty());
}
@Test
public void testDelete() {
sut.add(triple("x R y"));
assertEquals(1, sut.size());
sut.delete(triple("x R y"));
assertEquals(0, sut.size());
assertTrue(sut.isEmpty());
}
@Test
public void testFind() {
sut.add(triple("x R y"));
assertEquals(1, sut.find(triple("x R y")).toList().size());
assertEquals(0, sut.find(triple("x R z")).toList().size());
}
@Test
public void testFind1() {
sut.add(triple("x R y"));
assertEquals(1, sut.find(null, null, null).toList().size());
assertEquals(1, sut.find(null, null, node("y")).toList().size());
assertEquals(1, sut.find(null, node("R"), null).toList().size());
assertEquals(1, sut.find(null, node("R"), node("y")).toList().size());
assertEquals(1, sut.find(node("x"), null, null).toList().size());
assertEquals(1, sut.find(node("x"), null, node("y")).toList().size());
assertEquals(1, sut.find(node("x"), node("R"), null).toList().size());
assertEquals(1, sut.find(node("x"), node("R"), node("y")).toList().size());
}
@Test
public void testFind2() {
sut.add(triple("x R y"));
assertEquals(1, sut.find(null, null, null).toList().size());
assertEquals(0, sut.find(null, null, node("z")).toList().size());
assertEquals(0, sut.find(null, node("S"), null).toList().size());
assertEquals(0, sut.find(null, node("S"), node("y")).toList().size());
assertEquals(0, sut.find(node("y"), null, null).toList().size());
assertEquals(0, sut.find(node("y"), null, node("y")).toList().size());
assertEquals(0, sut.find(node("y"), node("R"), null).toList().size());
assertEquals(0, sut.find(node("y"), node("R"), node("y")).toList().size());
}
@Test
public void testFindWithIteratorHasNextNext() {
sut.add(triple("x R y"));
var iter = sut.find(triple("x R y"));
assertTrue(iter.hasNext());
assertEquals(triple("x R y"), iter.next());
assertFalse(iter.hasNext());
}
@Test
public void testFindSPO() {
sut.add(triple("x R y"));
assertEquals(1, sut.find(node("x"), node("R"), node("y")).toList().size());
assertEquals(0, sut.find(node("x"), node("R"), node("z")).toList().size());
}
@Test
public void testFind___() {
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
var findings = sut.find(null, null, null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAa, aAb, aAc, bAa, bAb, bAc, cBa, cBb, cBc));
}
@Test
public void testFindS__() {
assertFalse(sut.find(node("a"), null, null).hasNext());
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
var findings = sut.find(node("a"), null, null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAa, aAb, aAc));
findings = sut.find(node("b"), null, null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(bAa, bAb, bAc));
findings = sut.find(node("c"), null, null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(cBa, cBb, cBc));
findings = sut.find(node("d"), null, null).toList();
assertThat(findings, IsEmptyCollection.empty());
}
@Test
public void testFind_P_() {
assertFalse(sut.find(null, node("A"), null).hasNext());
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
var findings = sut.find(null, node("A"), null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAa, aAb, aAc, bAa, bAb, bAc));
findings = sut.find(null, node("B"), null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(cBa, cBb, cBc));
findings = sut.find(null, node("C"), null).toList();
assertThat(findings, IsEmptyCollection.empty());
}
@Test
public void testFind__O() {
assertFalse(sut.find(null, null, node("a")).hasNext());
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
var findings = sut.find(null, null, node("a")).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAa, bAa, cBa));
findings = sut.find(null, null, node("b")).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAb, bAb, cBb));
findings = sut.find(null, null, node("c")).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAc, bAc, cBc));
findings = sut.find(null, null, node("d")).toList();
assertThat(findings, IsEmptyCollection.empty());
}
@Test
public void testFindSP_() {
assertFalse(sut.find(node("a"), node("A"), null).hasNext());
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
var findings = sut.find(node("a"), node("A"), null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAa, aAb, aAc));
findings = sut.find(node("b"), node("A"), null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(bAa, bAb, bAc));
findings = sut.find(node("c"), node("B"), null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(cBa, cBb, cBc));
findings = sut.find(node("d"), node("C"), null).toList();
assertThat(findings, IsEmptyCollection.empty());
findings = sut.find(node("a"), node("B"), null).toList();
assertThat(findings, IsEmptyCollection.empty());
}
@Test
public void testFindS_O() {
assertFalse(sut.find(node("a"), null, node("a")).hasNext());
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
var findings = sut.find(node("a"), null, node("a")).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAa));
findings = sut.find(node("b"), null, node("a")).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(bAa));
findings = sut.find(node("c"), null, node("a")).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(cBa));
findings = sut.find(node("d"), null, node("a")).toList();
assertThat(findings, IsEmptyCollection.empty());
findings = sut.find(node("a"), null, node("d")).toList();
assertThat(findings, IsEmptyCollection.empty());
}
@Test
public void testFind_PO() {
assertFalse(sut.find(null, node("A"), node("a")).hasNext());
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
var findings = sut.find(null, node("A"), node("a")).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAa, bAa));
findings = sut.find(null, node("B"), node("a")).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(cBa));
findings = sut.find(null, node("C"), node("a")).toList();
assertThat(findings, IsEmptyCollection.empty());
findings = sut.find(null, node("A"), node("d")).toList();
assertThat(findings, IsEmptyCollection.empty());
}
@Test
public void testStream() {
sut.add(triple("x R y"));
assertEquals(1, sut.stream().count());
}
@Test
public void testStreamEmpty() {
assertEquals(0, sut.stream().count());
}
@Test
public void testStreamSPO() {
assertEquals(0, sut.stream(node("x"), node("R"), node("y")).count());
var t = triple("x R y");
sut.add(t);
var findings = sut.stream(t.getSubject(), t.getPredicate(), t.getObject()).toList();
assertEquals(1, findings.size());
assertEquals(findings.get(0), t);
}
@Test
public void testStream___() {
assertEquals(0, sut.stream(null, null, null).count());
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
var findings = sut.stream(null, null, null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAa, aAb, aAc, bAa, bAb, bAc, cBa, cBb, cBc));
}
@Test
public void testStreamS__() {
assertEquals(0, sut.stream(node("a"), null, null).count());
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
var findings = sut.stream(aAa.getSubject(), null, null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAa, aAb, aAc));
findings = sut.stream(bAa.getSubject(), null, null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(bAa, bAb, bAc));
findings = sut.stream(cBa.getSubject(), null, null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(cBa, cBb, cBc));
findings = sut.stream(node("d"), null, null).toList();
assertThat(findings, IsEmptyCollection.empty());
}
@Test
public void testStream_P_() {
assertEquals(0, sut.stream(null, node("A"), null).count());
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
var findings = sut.stream(null, aAa.getPredicate(), null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAa, aAb, aAc, bAa, bAb, bAc));
findings = sut.stream(null, cBa.getPredicate(), null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(cBa, cBb, cBc));
findings = sut.stream(null, node("C"), null).toList();
assertThat(findings, IsEmptyCollection.empty());
}
@Test
public void testStream__O() {
assertEquals(0, sut.stream(null, null, node("a")).count());
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
var findings = sut.stream(null, null, aAa.getObject()).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAa, bAa, cBa));
findings = sut.stream(null, null, aAb.getObject()).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAb, bAb, cBb));
findings = sut.stream(null, null, aAc.getObject()).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAc, bAc, cBc));
findings = sut.stream(null, null, node("d")).toList();
assertThat(findings, IsEmptyCollection.empty());
}
@Test
public void testStreamSP_() {
assertEquals(0, sut.stream(node("a"), node("A"), null).count());
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
var findings = sut.stream(aAa.getSubject(), aAa.getPredicate(), null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAa, aAb, aAc));
findings = sut.stream(bAa.getSubject(), bAa.getPredicate(), null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(bAa, bAb, bAc));
findings = sut.stream(cBa.getSubject(), cBa.getPredicate(), null).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(cBa, cBb, cBc));
findings = sut.stream(node("a"), node("C"), null).toList();
assertThat(findings, IsEmptyCollection.empty());
findings = sut.stream(node("d"), node("D"), null).toList();
assertThat(findings, IsEmptyCollection.empty());
}
@Test
public void testStreamS_O() {
assertEquals(0, sut.stream(node("a"), null, node("a")).count());
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
var findings = sut.stream(aAa.getSubject(), null, aAa.getObject()).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAa));
findings = sut.stream(bAa.getSubject(), null, bAa.getObject()).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(bAa));
findings = sut.stream(cBa.getSubject(), null, cBa.getObject()).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(cBa));
findings = sut.stream(node("d"), null, node("d")).toList();
assertThat(findings, IsEmptyCollection.empty());
findings = sut.stream(node("d"), null, node("a")).toList();
assertThat(findings, IsEmptyCollection.empty());
findings = sut.stream(node("a"), null, node("d")).toList();
assertThat(findings, IsEmptyCollection.empty());
}
@Test
public void testStream_PO() {
assertEquals(0, sut.stream(null, node("A"), node("a")).count());
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
var findings = sut.stream(null, aAa.getPredicate(), aAa.getObject()).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAa, bAa));
findings = sut.stream(null, bAa.getPredicate(), bAa.getObject()).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(aAa, bAa));
findings = sut.stream(null, cBa.getPredicate(), cBa.getObject()).toList();
assertThat(findings, IsIterableContainingInAnyOrder.containsInAnyOrder(cBa));
findings = sut.stream(null, node("C"), node("a")).toList();
assertThat(findings, IsEmptyCollection.empty());
findings = sut.stream(null, node("A"), node("d")).toList();
assertThat(findings, IsEmptyCollection.empty());
findings = sut.stream(null, node("D"), node("d")).toList();
assertThat(findings, IsEmptyCollection.empty());
}
@Test
public void testContains() {
sut.add(triple("x R y"));
assertTrue(sut.contains(triple("x R y")));
assertFalse(sut.contains(triple("x R z")));
}
@Test
public void testContains1() {
sut.add(triple("x R y"));
sut.add(triple("y S z"));
sut.add(triple("z T a"));
assertTrue(sut.contains(null, null, null));
assertTrue(sut.contains(null, null, node("y")));
assertTrue(sut.contains(null, node("R"), null));
assertTrue(sut.contains(null, node("R"), node("y")));
assertTrue(sut.contains(node("x"), null, null));
assertTrue(sut.contains(node("x"), null, node("y")));
assertTrue(sut.contains(node("x"), node("R"), null));
assertTrue(sut.contains(node("x"), node("R"), node("y")));
}
@Test
public void testContains2() {
sut.add(triple("x R y"));
sut.add(triple("y S z"));
sut.add(triple("z T a"));
assertTrue(sut.contains(null, null, null));
assertFalse(sut.contains(null, null, node("x")));
assertFalse(sut.contains(null, node("U"), null));
assertFalse(sut.contains(null, node("R"), node("z")));
assertFalse(sut.contains(node("a"), null, null));
assertFalse(sut.contains(node("x"), null, node("x")));
assertFalse(sut.contains(node("y"), node("R"), null));
assertFalse(sut.contains(node("y"), node("T"), node("a")));
}
@Test
public void testContainsSPO() {
assertFalse(sut.contains(node("a"), node("A"), node("a")));
var t = triple("a A a");
sut.add(t);
assertTrue(sut.contains(t.getSubject(), t.getPredicate(), t.getObject()));
assertFalse(sut.contains(t.getSubject(), t.getPredicate(), node("b")));
assertFalse(sut.contains(t.getSubject(), node("B"), t.getObject()));
assertFalse(sut.contains(node("b"), t.getPredicate(), t.getObject()));
}
@Test
public void testContains___() {
assertFalse(sut.contains(null, null, null));
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
assertTrue(sut.contains(null, null, null));
}
@Test
public void testContainsS__() {
assertFalse(sut.contains(node("a"), null, null));
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
assertTrue(sut.contains(aAa.getSubject(), null, null));
assertTrue(sut.contains(bAa.getSubject(), null, null));
assertTrue(sut.contains(cBa.getSubject(), null, null));
assertFalse(sut.contains(node("d"), null, null));
}
@Test
public void testContains_P_() {
assertFalse(sut.contains(null, node("A"), null));
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
assertTrue(sut.contains(null, aAa.getPredicate(), null));
assertTrue(sut.contains(null, cBa.getPredicate(), null));
assertFalse(sut.contains(null, node("C"), null));
}
@Test
public void testContains__O() {
assertFalse(sut.contains(null, null, node("a")));
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
assertTrue(sut.contains(null, null, aAa.getObject()));
assertTrue(sut.contains(null, null, aAb.getObject()));
assertTrue(sut.contains(null, null, aAc.getObject()));
assertFalse(sut.contains(null, null, node("d")));
}
@Test
public void testContainsSP_() {
assertFalse(sut.contains(node("a"), node("A"), null));
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
assertTrue(sut.contains(aAa.getSubject(), aAa.getPredicate(), null));
assertTrue(sut.contains(bAa.getSubject(), bAa.getPredicate(), null));
assertTrue(sut.contains(cBa.getSubject(), cBa.getPredicate(), null));
assertFalse(sut.contains(node("a"), node("C"), null));
assertFalse(sut.contains(node("d"), node("D"), null));
}
@Test
public void testContainsS_O() {
assertFalse(sut.contains(node("a"), null, node("a")));
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
assertTrue(sut.contains(aAa.getSubject(), null, aAa.getObject()));
assertTrue(sut.contains(bAa.getSubject(), null, bAa.getObject()));
assertTrue(sut.contains(cBa.getSubject(), null, cBa.getObject()));
assertFalse(sut.contains(node("d"), null, node("d")));
assertFalse(sut.contains(node("d"), null, node("a")));
assertFalse(sut.contains(node("a"), null, node("d")));
}
@Test
public void testContains_PO() {
assertFalse(sut.contains(null, node("A"), node("a")));
final var aAa = triple("a A a");
final var aAb = triple("a A b");
final var aAc = triple("a A c");
final var bAa = triple("b A a");
final var bAb = triple("b A b");
final var bAc = triple("b A c");
final var cBa = triple("c B a");
final var cBb = triple("c B b");
final var cBc = triple("c B c");
sut.add(aAa);
sut.add(aAb);
sut.add(aAc);
sut.add(bAa);
sut.add(bAb);
sut.add(bAc);
sut.add(cBa);
sut.add(cBb);
sut.add(cBc);
assertTrue(sut.contains(null, aAa.getPredicate(), aAa.getObject()));
assertTrue(sut.contains(null, bAa.getPredicate(), bAa.getObject()));
assertTrue(sut.contains(null, cBa.getPredicate(), cBa.getObject()));
assertFalse(sut.contains(null, node("C"), node("a")));
assertFalse(sut.contains(null, node("A"), node("d")));
assertFalse(sut.contains(null, node("D"), node("d")));
}
@Test
public void testContainsValueObject() {
sut.add(Triple.create(
NodeFactory.createURI("x"),
NodeFactory.createURI("R"),
NodeFactory.createLiteralDT("0.1", XSDDouble.XSDdouble)));
assertTrue(sut.contains(Triple.create(
NodeFactory.createURI("x"),
NodeFactory.createURI("R"),
NodeFactory.createLiteralDT("0.1", XSDDouble.XSDdouble))));
assertFalse(sut.contains(Triple.create(
NodeFactory.createURI("x"),
NodeFactory.createURI("R"),
NodeFactory.createLiteralDT("0.10", XSDDouble.XSDdouble))));
assertFalse(sut.contains(Triple.create(
NodeFactory.createURI("x"),
NodeFactory.createURI("R"),
NodeFactory.createLiteralDT("0.11", XSDDouble.XSDdouble))));
}
@Test
public void testContainsValueSubject() {
var containedTriple = Triple.create(
NodeFactory.createLiteralDT("0.1", XSDDouble.XSDdouble),
NodeFactory.createURI("x"),
NodeFactory.createURI("R"));
sut.add(containedTriple);
var match = Triple.create(
NodeFactory.createLiteralDT("0.1", XSDDouble.XSDdouble),
NodeFactory.createURI("x"),
NodeFactory.createURI("R"));
assertTrue(sut.contains(match));
assertEquals(containedTriple, sut.find(match).next());
match = Triple.create(
NodeFactory.createLiteralDT("0.10", XSDDouble.XSDdouble),
NodeFactory.createURI("x"),
NodeFactory.createURI("R"));
assertFalse(sut.contains(match));
assertFalse(sut.find(match).hasNext());
match = Triple.create(
NodeFactory.createLiteralDT("0.11", XSDDouble.XSDdouble),
NodeFactory.createURI("x"),
NodeFactory.createURI("R"));
assertFalse(sut.contains(match));
assertFalse(sut.find(match).hasNext());
}
@Test
public void testContainsValuePredicate() {
sut.add(Triple.create(
NodeFactory.createURI("x"),
NodeFactory.createLiteralDT("0.1", XSDDouble.XSDdouble),
NodeFactory.createURI("R")));
assertTrue(sut.contains(Triple.create(
NodeFactory.createURI("x"),
NodeFactory.createLiteralDT("0.1", XSDDouble.XSDdouble),
NodeFactory.createURI("R"))));
assertFalse(sut.contains(Triple.create(
NodeFactory.createURI("x"),
NodeFactory.createLiteralDT("0.10", XSDDouble.XSDdouble),
NodeFactory.createURI("R"))));
assertFalse(sut.contains(Triple.create(
NodeFactory.createURI("x"),
NodeFactory.createLiteralDT("0.11", XSDDouble.XSDdouble),
NodeFactory.createURI("R"))));
}
@Test
public void testCopy() {
sut.add(triple("s p o"));
sut.add(triple("s1 p1 o1"));
sut.add(triple("s2 p2 o2"));
assertEquals(3, sut.size());
var copy = sut.copy();
assertEquals(3, copy.size());
assertTrue(copy.contains(triple("s p o")));
assertTrue(copy.contains(triple("s1 p1 o1")));
assertTrue(copy.contains(triple("s2 p2 o2")));
assertFalse(copy.contains(triple("s3 p3 o3")));
}
@Test
public void testCopyHasNoSideEffects() {
sut.add(triple("s p o"));
sut.add(triple("s1 p1 o1"));
sut.add(triple("s2 p2 o2"));
assertEquals(3, sut.size());
var copy = sut.copy();
copy.delete(triple("s1 p1 o1"));
copy.add(triple("s3 p3 o3"));
copy.add(triple("s4 p4 o4"));
assertEquals(4, copy.size());
assertTrue(copy.contains(triple("s p o")));
assertFalse(copy.contains(triple("s1 p1 o1")));
assertTrue(copy.contains(triple("s2 p2 o2")));
assertTrue(copy.contains(triple("s3 p3 o3")));
assertTrue(copy.contains(triple("s4 p4 o4")));
assertEquals(3, sut.size());
assertTrue(sut.contains(triple("s p o")));
assertTrue(sut.contains(triple("s1 p1 o1")));
assertTrue(sut.contains(triple("s2 p2 o2")));
assertFalse(sut.contains(triple("s3 p3 o3")));
}
}
|
apache/ozone | 36,873 | hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/dn/checksum/TestContainerCommandReconciliation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.ozone.dn.checksum;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION;
import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_BLOCK_TOKEN_ENABLED;
import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_CONTAINER_REPORT_INTERVAL;
import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_CONTAINER_TOKEN_ENABLED;
import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_DATANODE_KERBEROS_KEYTAB_FILE_KEY;
import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_DATANODE_KERBEROS_PRINCIPAL_KEY;
import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_HEARTBEAT_INTERVAL;
import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_NODE_REPORT_INTERVAL;
import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_SECRET_KEY_EXPIRY_DURATION;
import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_SECRET_KEY_ROTATE_CHECK_DURATION;
import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_SECRET_KEY_ROTATE_DURATION;
import static org.apache.hadoop.hdds.HddsConfigKeys.OZONE_METADATA_DIRS;
import static org.apache.hadoop.hdds.client.ReplicationFactor.THREE;
import static org.apache.hadoop.hdds.client.ReplicationType.RATIS;
import static org.apache.hadoop.hdds.scm.ScmConfig.ConfigStrings.HDDS_SCM_KERBEROS_KEYTAB_FILE_KEY;
import static org.apache.hadoop.hdds.scm.ScmConfig.ConfigStrings.HDDS_SCM_KERBEROS_PRINCIPAL_KEY;
import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_CHUNK_SIZE_KEY;
import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_CLIENT_ADDRESS_KEY;
import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_DEADNODE_INTERVAL;
import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_HEARTBEAT_PROCESS_INTERVAL;
import static org.apache.hadoop.hdds.scm.ScmConfigKeys.OZONE_SCM_STALENODE_INTERVAL;
import static org.apache.hadoop.hdds.scm.server.SCMHTTPServerConfig.ConfigStrings.HDDS_SCM_HTTP_KERBEROS_KEYTAB_FILE_KEY;
import static org.apache.hadoop.hdds.scm.server.SCMHTTPServerConfig.ConfigStrings.HDDS_SCM_HTTP_KERBEROS_PRINCIPAL_KEY;
import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_ADMINISTRATORS;
import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_SCM_BLOCK_SIZE;
import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_SECURITY_ENABLED_KEY;
import static org.apache.hadoop.ozone.container.checksum.ContainerChecksumTreeManager.getContainerChecksumFile;
import static org.apache.hadoop.ozone.container.checksum.ContainerMerkleTreeTestUtils.assertTreesSortedAndMatch;
import static org.apache.hadoop.ozone.container.checksum.ContainerMerkleTreeTestUtils.buildTestTree;
import static org.apache.hadoop.ozone.container.checksum.ContainerMerkleTreeTestUtils.readChecksumFile;
import static org.apache.hadoop.ozone.om.OMConfigKeys.DELEGATION_REMOVER_SCAN_INTERVAL_KEY;
import static org.apache.hadoop.ozone.om.OMConfigKeys.DELEGATION_TOKEN_MAX_LIFETIME_KEY;
import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_HTTP_KERBEROS_KEYTAB_FILE;
import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_HTTP_KERBEROS_PRINCIPAL_KEY;
import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_KERBEROS_KEYTAB_FILE_KEY;
import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_KERBEROS_PRINCIPAL_KEY;
import static org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod.KERBEROS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.hdds.conf.StorageUnit;
import org.apache.hadoop.hdds.protocol.DatanodeDetails;
import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
import org.apache.hadoop.hdds.scm.ScmConfig;
import org.apache.hadoop.hdds.scm.container.ContainerID;
import org.apache.hadoop.hdds.scm.container.ContainerReplica;
import org.apache.hadoop.hdds.scm.container.common.helpers.StorageContainerException;
import org.apache.hadoop.hdds.scm.protocolPB.StorageContainerLocationProtocolClientSideTranslatorPB;
import org.apache.hadoop.hdds.scm.server.SCMHTTPServerConfig;
import org.apache.hadoop.hdds.scm.server.StorageContainerManager;
import org.apache.hadoop.hdds.security.symmetric.SecretKeyClient;
import org.apache.hadoop.hdds.security.x509.certificate.client.CertificateClient;
import org.apache.hadoop.hdds.utils.db.BatchOperation;
import org.apache.hadoop.minikdc.MiniKdc;
import org.apache.hadoop.ozone.ClientVersion;
import org.apache.hadoop.ozone.HddsDatanodeService;
import org.apache.hadoop.ozone.MiniOzoneCluster;
import org.apache.hadoop.ozone.MiniOzoneHAClusterImpl;
import org.apache.hadoop.ozone.client.ObjectStore;
import org.apache.hadoop.ozone.client.OzoneBucket;
import org.apache.hadoop.ozone.client.OzoneClient;
import org.apache.hadoop.ozone.client.OzoneClientFactory;
import org.apache.hadoop.ozone.client.OzoneVolume;
import org.apache.hadoop.ozone.client.io.OzoneOutputStream;
import org.apache.hadoop.ozone.container.TestHelper;
import org.apache.hadoop.ozone.container.checksum.ContainerChecksumTreeManager;
import org.apache.hadoop.ozone.container.checksum.ContainerMerkleTreeWriter;
import org.apache.hadoop.ozone.container.checksum.DNContainerOperationClient;
import org.apache.hadoop.ozone.container.common.helpers.BlockData;
import org.apache.hadoop.ozone.container.common.interfaces.Container;
import org.apache.hadoop.ozone.container.common.interfaces.DBHandle;
import org.apache.hadoop.ozone.container.common.statemachine.DatanodeStateMachine;
import org.apache.hadoop.ozone.container.keyvalue.KeyValueContainer;
import org.apache.hadoop.ozone.container.keyvalue.KeyValueContainerData;
import org.apache.hadoop.ozone.container.keyvalue.KeyValueHandler;
import org.apache.hadoop.ozone.container.keyvalue.TestContainerCorruptions;
import org.apache.hadoop.ozone.container.keyvalue.helpers.BlockUtils;
import org.apache.hadoop.ozone.container.keyvalue.interfaces.BlockManager;
import org.apache.hadoop.ozone.om.OzoneManager;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.ozone.test.GenericTestUtils;
import org.apache.ozone.test.tag.Flaky;
import org.apache.ratis.thirdparty.com.google.protobuf.InvalidProtocolBufferException;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class tests container commands for reconciliation.
*/
public class TestContainerCommandReconciliation {
private static MiniOzoneHAClusterImpl cluster;
private static OzoneClient rpcClient;
private static ObjectStore store;
private static OzoneConfiguration conf;
private static DNContainerOperationClient dnClient;
private static final String KEY_NAME = "testkey";
private static final Logger LOG = LoggerFactory.getLogger(TestContainerCommandReconciliation.class);
private static final String TEST_SCAN = "Test Scan";
@TempDir
private static File testDir;
@TempDir
private static File workDir;
private static MiniKdc miniKdc;
private static File ozoneKeytab;
private static File spnegoKeytab;
private static File testUserKeytab;
private static String testUserPrincipal;
@BeforeAll
public static void init() throws Exception {
conf = new OzoneConfiguration();
conf.set(OZONE_SCM_CLIENT_ADDRESS_KEY, "localhost");
conf.set(OZONE_METADATA_DIRS, testDir.getAbsolutePath());
conf.setStorageSize(OZONE_SCM_CHUNK_SIZE_KEY, 128 * 1024, StorageUnit.BYTES);
conf.setStorageSize(OZONE_SCM_BLOCK_SIZE, 512 * 1024, StorageUnit.BYTES);
// Support restarting datanodes and SCM in a rolling fashion to test checksum reporting after restart.
// Datanodes need to heartbeat more frequently, because they will not know that SCM was restarted until they
// heartbeat and SCM indicates they need to re-register.
conf.set(OZONE_SCM_HEARTBEAT_PROCESS_INTERVAL, "200ms");
conf.set(HDDS_HEARTBEAT_INTERVAL, "1s");
conf.set(OZONE_SCM_STALENODE_INTERVAL, "3s");
conf.set(OZONE_SCM_DEADNODE_INTERVAL, "6s");
conf.set(HDDS_NODE_REPORT_INTERVAL, "5s");
conf.set(HDDS_CONTAINER_REPORT_INTERVAL, "5s");
startMiniKdc();
setSecureConfig();
createCredentialsInKDC();
setSecretKeysConfig();
startCluster();
}
@AfterAll
public static void stop() throws IOException {
if (rpcClient != null) {
rpcClient.close();
}
if (dnClient != null) {
dnClient.close();
}
if (miniKdc != null) {
miniKdc.stop();
}
if (cluster != null) {
cluster.stop();
}
}
/**
* Container checksum trees are only generated for non-open containers.
* Calling the API on a non-open container should fail.
*/
@Test
public void testGetChecksumInfoOpenReplica() throws Exception {
String volume = UUID.randomUUID().toString();
String bucket = UUID.randomUUID().toString();
long containerID = writeDataAndGetContainer(false, volume, bucket);
HddsDatanodeService targetDN = cluster.getHddsDatanodes().get(0);
StorageContainerException ex = assertThrows(StorageContainerException.class,
() -> dnClient.getContainerChecksumInfo(containerID, targetDN.getDatanodeDetails()));
assertEquals(ex.getResult(), ContainerProtos.Result.UNCLOSED_CONTAINER_IO);
}
/**
* Tests reading the container checksum info file from a datanode who does not have a replica for the requested
* container.
*/
@Test
public void testGetChecksumInfoNonexistentReplica() {
HddsDatanodeService targetDN = cluster.getHddsDatanodes().get(0);
// Find a container ID that does not exist in the cluster. For a small test this should be a good starting
// point, but modify it just in case.
long badIDCheck = 1_000_000;
while (cluster.getStorageContainerManager().getContainerManager()
.containerExist(ContainerID.valueOf(badIDCheck))) {
badIDCheck++;
}
final long nonexistentContainerID = badIDCheck;
StorageContainerException ex = assertThrows(StorageContainerException.class,
() -> dnClient.getContainerChecksumInfo(nonexistentContainerID, targetDN.getDatanodeDetails()));
assertEquals(ex.getResult(), ContainerProtos.Result.CONTAINER_NOT_FOUND);
}
/**
* Tests container checksum file creation if it doesn't exist during getContainerChecksumInfo call.
*/
@Test
public void testMerkleTreeCreationDuringGetChecksumInfo() throws Exception {
String volume = UUID.randomUUID().toString();
String bucket = UUID.randomUUID().toString();
long containerID = writeDataAndGetContainer(true, volume, bucket);
// Pick a datanode and remove its checksum file.
HddsDatanodeService targetDN = cluster.getHddsDatanodes().get(0);
Container<?> container = targetDN.getDatanodeStateMachine().getContainer()
.getContainerSet().getContainer(containerID);
File treeFile = getContainerChecksumFile(container.getContainerData());
// Closing the container should have generated the tree file.
ContainerProtos.ContainerChecksumInfo srcChecksumInfo = ContainerChecksumTreeManager.readChecksumInfo(
container.getContainerData());
assertTrue(treeFile.exists());
assertTrue(treeFile.delete());
ContainerProtos.ContainerChecksumInfo destChecksumInfo = dnClient.getContainerChecksumInfo(
containerID, targetDN.getDatanodeDetails());
assertNotNull(destChecksumInfo);
assertTreesSortedAndMatch(srcChecksumInfo.getContainerMerkleTree(), destChecksumInfo.getContainerMerkleTree());
}
/**
* Tests reading the container checksum info file from a datanode where there's an IO error
* that's not related to file not found (e.g., permission error). Such errors should not
* trigger fallback to building from metadata.
*/
@Test
public void testGetChecksumInfoIOError() throws Exception {
String volume = UUID.randomUUID().toString();
String bucket = UUID.randomUUID().toString();
long containerID = writeDataAndGetContainer(true, volume, bucket);
// Pick a datanode and make its checksum file unreadable to simulate permission error.
HddsDatanodeService targetDN = cluster.getHddsDatanodes().get(0);
Container<?> container = targetDN.getDatanodeStateMachine().getContainer()
.getContainerSet().getContainer(containerID);
File treeFile = getContainerChecksumFile(container.getContainerData());
assertTrue(treeFile.exists());
// Make the server unable to read the file (permission error, not file not found).
assertTrue(treeFile.setReadable(false));
StorageContainerException ex = assertThrows(StorageContainerException.class, () ->
dnClient.getContainerChecksumInfo(containerID, targetDN.getDatanodeDetails()));
assertEquals(ContainerProtos.Result.IO_EXCEPTION, ex.getResult());
}
/**
* Tests reading the container checksum info file from a datanode where the datanode fails to read the file from
* the disk.
*/
@Test
public void testGetChecksumInfoServerIOError() throws Exception {
String volume = UUID.randomUUID().toString();
String bucket = UUID.randomUUID().toString();
long containerID = writeDataAndGetContainer(true, volume, bucket);
// Pick a datanode and remove its checksum file.
HddsDatanodeService targetDN = cluster.getHddsDatanodes().get(0);
Container<?> container = targetDN.getDatanodeStateMachine().getContainer()
.getContainerSet().getContainer(containerID);
File treeFile = getContainerChecksumFile(container.getContainerData());
assertTrue(treeFile.exists());
// Make the server unable to read the file.
assertTrue(treeFile.setReadable(false));
StorageContainerException ex = assertThrows(StorageContainerException.class, () ->
dnClient.getContainerChecksumInfo(containerID, targetDN.getDatanodeDetails()));
assertEquals(ContainerProtos.Result.IO_EXCEPTION, ex.getResult());
}
/**
* Tests reading the container checksum info file from a datanode where the file is corrupt.
* The datanode does not deserialize the file before sending it, so there should be no error on the server side
* when sending the file. The client should raise an error trying to deserialize it.
*/
@Test
public void testGetCorruptChecksumInfo() throws Exception {
String volume = UUID.randomUUID().toString();
String bucket = UUID.randomUUID().toString();
long containerID = writeDataAndGetContainer(true, volume, bucket);
// Pick a datanode and corrupt its checksum file.
HddsDatanodeService targetDN = cluster.getHddsDatanodes().get(0);
Container<?> container = targetDN.getDatanodeStateMachine().getContainer()
.getContainerSet().getContainer(containerID);
File treeFile = getContainerChecksumFile(container.getContainerData());
Files.write(treeFile.toPath(), new byte[]{1, 2, 3},
StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.SYNC);
// Reading the file from the replica should fail when the client tries to deserialize it.
assertThrows(InvalidProtocolBufferException.class, () -> dnClient.getContainerChecksumInfo(containerID,
targetDN.getDatanodeDetails()));
}
@Test
public void testGetEmptyChecksumInfo() throws Exception {
String volume = UUID.randomUUID().toString();
String bucket = UUID.randomUUID().toString();
long containerID = writeDataAndGetContainer(true, volume, bucket);
// Pick a datanode and truncate its checksum file to zero length.
HddsDatanodeService targetDN = cluster.getHddsDatanodes().get(0);
Container<?> container = targetDN.getDatanodeStateMachine().getContainer()
.getContainerSet().getContainer(containerID);
File treeFile = getContainerChecksumFile(container.getContainerData());
assertTrue(treeFile.exists());
Files.write(treeFile.toPath(), new byte[]{},
StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.SYNC);
assertEquals(0, treeFile.length());
// The client will get an empty byte string back. It should raise this as an error instead of returning a default
// protobuf object.
StorageContainerException ex = assertThrows(StorageContainerException.class, () ->
dnClient.getContainerChecksumInfo(containerID, targetDN.getDatanodeDetails()));
assertEquals(ContainerProtos.Result.IO_EXCEPTION, ex.getResult());
}
@Test
public void testGetChecksumInfoSuccess() throws Exception {
String volume = UUID.randomUUID().toString();
String bucket = UUID.randomUUID().toString();
long containerID = writeDataAndGetContainer(true, volume, bucket);
// Overwrite the existing tree with a custom one for testing. We will check that it is returned properly from the
// API.
ContainerMerkleTreeWriter tree = buildTestTree(conf);
writeChecksumFileToDatanodes(containerID, tree);
// Verify trees match on all replicas.
// This test is expecting Ratis 3 data written on a 3 node cluster, so every node has a replica.
assertEquals(3, cluster.getHddsDatanodes().size());
List<DatanodeDetails> datanodeDetails = cluster.getHddsDatanodes().stream()
.map(HddsDatanodeService::getDatanodeDetails).collect(Collectors.toList());
for (DatanodeDetails dn: datanodeDetails) {
ContainerProtos.ContainerChecksumInfo containerChecksumInfo =
dnClient.getContainerChecksumInfo(containerID, dn);
assertTreesSortedAndMatch(tree.toProto(), containerChecksumInfo.getContainerMerkleTree());
}
}
@Test
@Flaky("HDDS-13401")
public void testContainerChecksumWithBlockMissing() throws Exception {
// 1. Write data to a container.
// Read the key back and check its hash.
String volume = UUID.randomUUID().toString();
String bucket = UUID.randomUUID().toString();
Pair<Long, byte[]> containerAndData = getDataAndContainer(true, 20 * 1024 * 1024, volume, bucket);
long containerID = containerAndData.getLeft();
byte[] data = containerAndData.getRight();
// Get the datanodes where the container replicas are stored.
List<DatanodeDetails> dataNodeDetails = cluster.getStorageContainerManager().getContainerManager()
.getContainerReplicas(ContainerID.valueOf(containerID))
.stream().map(ContainerReplica::getDatanodeDetails)
.collect(Collectors.toList());
assertEquals(3, dataNodeDetails.size());
HddsDatanodeService hddsDatanodeService = cluster.getHddsDatanode(dataNodeDetails.get(0));
DatanodeStateMachine datanodeStateMachine = hddsDatanodeService.getDatanodeStateMachine();
Container<?> container = datanodeStateMachine.getContainer().getContainerSet().getContainer(containerID);
KeyValueContainerData containerData = (KeyValueContainerData) container.getContainerData();
ContainerProtos.ContainerChecksumInfo oldContainerChecksumInfo = readChecksumFile(container.getContainerData());
KeyValueHandler kvHandler = (KeyValueHandler) datanodeStateMachine.getContainer().getDispatcher()
.getHandler(ContainerProtos.ContainerType.KeyValueContainer);
BlockManager blockManager = kvHandler.getBlockManager();
List<BlockData> blockDataList = blockManager.listBlock(container, -1, 100);
String chunksPath = container.getContainerData().getChunksPath();
long oldDataChecksum = oldContainerChecksumInfo.getContainerMerkleTree().getDataChecksum();
// 2. Delete some blocks to simulate missing blocks.
try (DBHandle db = BlockUtils.getDB(containerData, conf);
BatchOperation op = db.getStore().getBatchHandler().initBatchOperation()) {
for (int i = 0; i < blockDataList.size(); i += 2) {
BlockData blockData = blockDataList.get(i);
// Delete the block metadata from the container db
db.getStore().getBlockDataTable().deleteWithBatch(op, containerData.getBlockKey(blockData.getLocalID()));
// Delete the block file.
Files.deleteIfExists(Paths.get(chunksPath + "/" + blockData.getBlockID().getLocalID() + ".block"));
}
db.getStore().getBatchHandler().commitBatchOperation(op);
db.getStore().flushDB();
}
datanodeStateMachine.getContainer().getContainerSet().scanContainerWithoutGap(containerID, TEST_SCAN);
waitForDataChecksumsAtSCM(containerID, 2);
ContainerProtos.ContainerChecksumInfo containerChecksumAfterBlockDelete =
readChecksumFile(container.getContainerData());
long dataChecksumAfterBlockDelete = containerChecksumAfterBlockDelete.getContainerMerkleTree().getDataChecksum();
// Checksum should have changed after block delete.
assertNotEquals(oldDataChecksum, dataChecksumAfterBlockDelete);
// 3. Reconcile the container.
cluster.getStorageContainerLocationClient().reconcileContainer(containerID);
// Compare and check if dataChecksum is same on all replicas.
waitForDataChecksumsAtSCM(containerID, 1);
ContainerProtos.ContainerChecksumInfo newContainerChecksumInfo = readChecksumFile(container.getContainerData());
assertTreesSortedAndMatch(oldContainerChecksumInfo.getContainerMerkleTree(),
newContainerChecksumInfo.getContainerMerkleTree());
TestHelper.validateData(KEY_NAME, data, store, volume, bucket);
}
@Test
public void testContainerChecksumChunkCorruption() throws Exception {
// 1. Write data to a container.
String volume = UUID.randomUUID().toString();
String bucket = UUID.randomUUID().toString();
Pair<Long, byte[]> containerAndData = getDataAndContainer(true, 20 * 1024 * 1024, volume, bucket);
long containerID = containerAndData.getLeft();
byte[] data = containerAndData.getRight();
// Get the datanodes where the container replicas are stored.
List<DatanodeDetails> dataNodeDetails = cluster.getStorageContainerManager().getContainerManager()
.getContainerReplicas(ContainerID.valueOf(containerID))
.stream().map(ContainerReplica::getDatanodeDetails)
.collect(Collectors.toList());
assertEquals(3, dataNodeDetails.size());
HddsDatanodeService hddsDatanodeService = cluster.getHddsDatanode(dataNodeDetails.get(0));
DatanodeStateMachine datanodeStateMachine = hddsDatanodeService.getDatanodeStateMachine();
Container<?> container = datanodeStateMachine.getContainer().getContainerSet().getContainer(containerID);
ContainerProtos.ContainerChecksumInfo oldContainerChecksumInfo = readChecksumFile(container.getContainerData());
KeyValueHandler kvHandler = (KeyValueHandler) datanodeStateMachine.getContainer().getDispatcher()
.getHandler(ContainerProtos.ContainerType.KeyValueContainer);
BlockManager blockManager = kvHandler.getBlockManager();
List<BlockData> blockDatas = blockManager.listBlock(container, -1, 100);
long oldDataChecksum = oldContainerChecksumInfo.getContainerMerkleTree().getDataChecksum();
// 2. Corrupt every block in one replica.
for (BlockData blockData : blockDatas) {
long blockID = blockData.getLocalID();
TestContainerCorruptions.CORRUPT_BLOCK.applyTo(container, blockID);
}
datanodeStateMachine.getContainer().getContainerSet().scanContainerWithoutGap(containerID, TEST_SCAN);
waitForDataChecksumsAtSCM(containerID, 2);
ContainerProtos.ContainerChecksumInfo containerChecksumAfterChunkCorruption =
readChecksumFile(container.getContainerData());
long dataChecksumAfterAfterChunkCorruption = containerChecksumAfterChunkCorruption
.getContainerMerkleTree().getDataChecksum();
// Checksum should have changed after chunk corruption.
assertNotEquals(oldDataChecksum, dataChecksumAfterAfterChunkCorruption);
// 4. Reconcile the container.
cluster.getStorageContainerLocationClient().reconcileContainer(containerID);
// Compare and check if dataChecksum is same on all replicas.
waitForDataChecksumsAtSCM(containerID, 1);
ContainerProtos.ContainerChecksumInfo newContainerChecksumInfo = readChecksumFile(container.getContainerData());
assertTreesSortedAndMatch(oldContainerChecksumInfo.getContainerMerkleTree(),
newContainerChecksumInfo.getContainerMerkleTree());
assertEquals(oldDataChecksum, newContainerChecksumInfo.getContainerMerkleTree().getDataChecksum());
TestHelper.validateData(KEY_NAME, data, store, volume, bucket);
}
@Test
@Flaky("HDDS-13401")
public void testDataChecksumReportedAtSCM() throws Exception {
// 1. Write data to a container.
// Read the key back and check its hash.
String volume = UUID.randomUUID().toString();
String bucket = UUID.randomUUID().toString();
Pair<Long, byte[]> containerAndData = getDataAndContainer(true, 20 * 1024 * 1024, volume, bucket);
long containerID = containerAndData.getLeft();
byte[] data = containerAndData.getRight();
// Get the datanodes where the container replicas are stored.
List<DatanodeDetails> dataNodeDetails = cluster.getStorageContainerManager().getContainerManager()
.getContainerReplicas(ContainerID.valueOf(containerID))
.stream().map(ContainerReplica::getDatanodeDetails)
.collect(Collectors.toList());
assertEquals(3, dataNodeDetails.size());
HddsDatanodeService hddsDatanodeService = cluster.getHddsDatanode(dataNodeDetails.get(0));
DatanodeStateMachine datanodeStateMachine = hddsDatanodeService.getDatanodeStateMachine();
Container<?> container = datanodeStateMachine.getContainer().getContainerSet().getContainer(containerID);
KeyValueContainerData containerData = (KeyValueContainerData) container.getContainerData();
ContainerProtos.ContainerChecksumInfo oldContainerChecksumInfo = readChecksumFile(container.getContainerData());
KeyValueHandler kvHandler = (KeyValueHandler) datanodeStateMachine.getContainer().getDispatcher()
.getHandler(ContainerProtos.ContainerType.KeyValueContainer);
long oldDataChecksum = oldContainerChecksumInfo.getContainerMerkleTree().getDataChecksum();
// Check non-zero checksum after container close
StorageContainerLocationProtocolClientSideTranslatorPB scmClient = cluster.getStorageContainerLocationClient();
List<HddsProtos.SCMContainerReplicaProto> containerReplicas = scmClient.getContainerReplicas(containerID,
ClientVersion.CURRENT_VERSION);
assertEquals(3, containerReplicas.size());
for (HddsProtos.SCMContainerReplicaProto containerReplica: containerReplicas) {
assertNotEquals(0, containerReplica.getDataChecksum());
}
// 2. Delete some blocks to simulate missing blocks.
BlockManager blockManager = kvHandler.getBlockManager();
List<BlockData> blockDataList = blockManager.listBlock(container, -1, 100);
String chunksPath = container.getContainerData().getChunksPath();
try (DBHandle db = BlockUtils.getDB(containerData, conf);
BatchOperation op = db.getStore().getBatchHandler().initBatchOperation()) {
for (int i = 0; i < blockDataList.size(); i += 2) {
BlockData blockData = blockDataList.get(i);
// Delete the block metadata from the container db
db.getStore().getBlockDataTable().deleteWithBatch(op, containerData.getBlockKey(blockData.getLocalID()));
// Delete the block file.
Files.deleteIfExists(Paths.get(chunksPath + "/" + blockData.getBlockID().getLocalID() + ".block"));
}
db.getStore().getBatchHandler().commitBatchOperation(op);
db.getStore().flushDB();
}
datanodeStateMachine.getContainer().getContainerSet().scanContainerWithoutGap(containerID, TEST_SCAN);
waitForDataChecksumsAtSCM(containerID, 2);
ContainerProtos.ContainerChecksumInfo containerChecksumAfterBlockDelete =
readChecksumFile(container.getContainerData());
long dataChecksumAfterBlockDelete = containerChecksumAfterBlockDelete.getContainerMerkleTree().getDataChecksum();
// Checksum should have changed after block delete.
assertNotEquals(oldDataChecksum, dataChecksumAfterBlockDelete);
scmClient.reconcileContainer(containerID);
waitForDataChecksumsAtSCM(containerID, 1);
// Check non-zero checksum after container reconciliation
containerReplicas = scmClient.getContainerReplicas(containerID, ClientVersion.CURRENT_VERSION);
assertEquals(3, containerReplicas.size());
for (HddsProtos.SCMContainerReplicaProto containerReplica: containerReplicas) {
assertNotEquals(0, containerReplica.getDataChecksum());
}
// Check non-zero checksum after datanode restart
// Restarting all the nodes take more time in mini ozone cluster, so restarting only one node
cluster.restartHddsDatanode(0, true);
for (StorageContainerManager scm : cluster.getStorageContainerManagers()) {
cluster.restartStorageContainerManager(scm, false);
}
cluster.waitForClusterToBeReady();
waitForDataChecksumsAtSCM(containerID, 1);
containerReplicas = scmClient.getContainerReplicas(containerID, ClientVersion.CURRENT_VERSION);
assertEquals(3, containerReplicas.size());
for (HddsProtos.SCMContainerReplicaProto containerReplica: containerReplicas) {
assertNotEquals(0, containerReplica.getDataChecksum());
}
TestHelper.validateData(KEY_NAME, data, store, volume, bucket);
}
private void waitForDataChecksumsAtSCM(long containerID, int expectedSize) throws Exception {
GenericTestUtils.waitFor(() -> {
try {
Set<Long> dataChecksums = cluster.getStorageContainerLocationClient().getContainerReplicas(containerID,
ClientVersion.CURRENT_VERSION).stream()
.map(HddsProtos.SCMContainerReplicaProto::getDataChecksum)
.collect(Collectors.toSet());
LOG.info("Waiting for {} total unique checksums from container {} to be reported to SCM. Currently {} unique" +
"checksums are reported.", expectedSize, containerID, dataChecksums.size());
return dataChecksums.size() == expectedSize;
} catch (Exception ex) {
return false;
}
}, 1000, 20000);
}
private Pair<Long, byte[]> getDataAndContainer(boolean close, int dataLen, String volumeName, String bucketName)
throws Exception {
store.createVolume(volumeName);
OzoneVolume volume = store.getVolume(volumeName);
volume.createBucket(bucketName);
OzoneBucket bucket = volume.getBucket(bucketName);
byte[] data = randomAlphabetic(dataLen).getBytes(UTF_8);
// Write Key
try (OzoneOutputStream os = TestHelper.createKey(KEY_NAME, RATIS, THREE, dataLen, store, volumeName, bucketName)) {
IOUtils.write(data, os);
}
long containerID = bucket.getKey(KEY_NAME).getOzoneKeyLocations().stream()
.findFirst().get().getContainerID();
if (close) {
TestHelper.waitForContainerClose(cluster, containerID);
TestHelper.waitForScmContainerState(cluster, containerID, HddsProtos.LifeCycleState.CLOSED);
}
return Pair.of(containerID, data);
}
private long writeDataAndGetContainer(boolean close, String volume, String bucket) throws Exception {
return getDataAndContainer(close, 5, volume, bucket).getLeft();
}
public static void writeChecksumFileToDatanodes(long containerID, ContainerMerkleTreeWriter tree) throws Exception {
// Write Container Merkle Tree
for (HddsDatanodeService dn : cluster.getHddsDatanodes()) {
KeyValueHandler keyValueHandler =
(KeyValueHandler) dn.getDatanodeStateMachine().getContainer().getDispatcher()
.getHandler(ContainerProtos.ContainerType.KeyValueContainer);
KeyValueContainer keyValueContainer =
(KeyValueContainer) dn.getDatanodeStateMachine().getContainer().getController()
.getContainer(containerID);
if (keyValueContainer != null) {
keyValueHandler.getChecksumManager().updateTree(keyValueContainer.getContainerData(), tree);
}
}
}
private static void setSecretKeysConfig() {
// Secret key lifecycle configs.
conf.set(HDDS_SECRET_KEY_ROTATE_CHECK_DURATION, "1s");
conf.set(HDDS_SECRET_KEY_ROTATE_DURATION, "100s");
conf.set(HDDS_SECRET_KEY_EXPIRY_DURATION, "500s");
conf.set(DELEGATION_TOKEN_MAX_LIFETIME_KEY, "300s");
conf.set(DELEGATION_REMOVER_SCAN_INTERVAL_KEY, "1s");
// enable tokens
conf.setBoolean(HDDS_BLOCK_TOKEN_ENABLED, true);
conf.setBoolean(HDDS_CONTAINER_TOKEN_ENABLED, true);
}
private static void createCredentialsInKDC() throws Exception {
ScmConfig scmConfig = conf.getObject(ScmConfig.class);
SCMHTTPServerConfig httpServerConfig =
conf.getObject(SCMHTTPServerConfig.class);
createPrincipal(ozoneKeytab, scmConfig.getKerberosPrincipal());
createPrincipal(spnegoKeytab, httpServerConfig.getKerberosPrincipal());
createPrincipal(testUserKeytab, testUserPrincipal);
}
private static void createPrincipal(File keytab, String... principal)
throws Exception {
miniKdc.createPrincipal(keytab, principal);
}
private static void startMiniKdc() throws Exception {
Properties securityProperties = MiniKdc.createConf();
miniKdc = new MiniKdc(securityProperties, workDir);
miniKdc.start();
}
private static void setSecureConfig() throws IOException {
conf.setBoolean(OZONE_SECURITY_ENABLED_KEY, true);
String host = InetAddress.getLocalHost().getCanonicalHostName()
.toLowerCase();
conf.set(HADOOP_SECURITY_AUTHENTICATION, KERBEROS.name());
String curUser = UserGroupInformation.getCurrentUser().getUserName();
conf.set(OZONE_ADMINISTRATORS, curUser);
String realm = miniKdc.getRealm();
String hostAndRealm = host + "@" + realm;
conf.set(HDDS_SCM_KERBEROS_PRINCIPAL_KEY, "scm/" + hostAndRealm);
conf.set(HDDS_SCM_HTTP_KERBEROS_PRINCIPAL_KEY, "HTTP_SCM/" + hostAndRealm);
conf.set(OZONE_OM_KERBEROS_PRINCIPAL_KEY, "scm/" + hostAndRealm);
conf.set(OZONE_OM_HTTP_KERBEROS_PRINCIPAL_KEY, "HTTP_OM/" + hostAndRealm);
conf.set(HDDS_DATANODE_KERBEROS_PRINCIPAL_KEY, "scm/" + hostAndRealm);
ozoneKeytab = new File(workDir, "scm.keytab");
spnegoKeytab = new File(workDir, "http.keytab");
testUserKeytab = new File(workDir, "testuser.keytab");
testUserPrincipal = "test@" + realm;
conf.set(HDDS_SCM_KERBEROS_KEYTAB_FILE_KEY, ozoneKeytab.getAbsolutePath());
conf.set(HDDS_SCM_HTTP_KERBEROS_KEYTAB_FILE_KEY, spnegoKeytab.getAbsolutePath());
conf.set(OZONE_OM_KERBEROS_KEYTAB_FILE_KEY, ozoneKeytab.getAbsolutePath());
conf.set(OZONE_OM_HTTP_KERBEROS_KEYTAB_FILE, spnegoKeytab.getAbsolutePath());
conf.set(HDDS_DATANODE_KERBEROS_KEYTAB_FILE_KEY, ozoneKeytab.getAbsolutePath());
}
private static void startCluster() throws Exception {
OzoneManager.setTestSecureOmFlag(true);
cluster = MiniOzoneCluster.newHABuilder(conf)
.setSCMServiceId("SecureSCM")
.setNumOfStorageContainerManagers(3)
.setNumOfOzoneManagers(1)
.build();
cluster.waitForClusterToBeReady();
rpcClient = OzoneClientFactory.getRpcClient(conf);
store = rpcClient.getObjectStore();
SecretKeyClient secretKeyClient = cluster.getStorageContainerManager().getSecretKeyManager();
CertificateClient certClient = cluster.getStorageContainerManager().getScmCertificateClient();
dnClient = new DNContainerOperationClient(conf, certClient, secretKeyClient);
}
}
|
apache/flink | 36,625 | flink-runtime/src/test/java/org/apache/flink/streaming/api/operators/co/IntervalJoinOperatorTest.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.co;
import org.apache.flink.api.common.serialization.SerializerConfigImpl;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.runtime.checkpoint.OperatorSubtaskState;
import org.apache.flink.streaming.api.functions.co.ProcessJoinFunction;
import org.apache.flink.streaming.api.operators.TwoInputStreamOperator;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import org.apache.flink.streaming.util.KeyedTwoInputStreamOperatorTestHarness;
import org.apache.flink.streaming.util.TestHarnessUtil;
import org.apache.flink.testutils.junit.extensions.parameterized.ParameterizedTestExtension;
import org.apache.flink.testutils.junit.extensions.parameterized.Parameters;
import org.apache.flink.util.Collector;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.OutputTag;
import org.apache.flink.shaded.guava33.com.google.common.collect.Iterables;
import org.apache.flink.shaded.guava33.com.google.common.collect.Lists;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for {@link IntervalJoinOperator}. Those tests cover correctness and cleaning of state */
@ExtendWith(ParameterizedTestExtension.class)
class IntervalJoinOperatorTest {
private final boolean lhsFasterThanRhs;
@Parameters(name = "lhs faster than rhs: {0}")
private static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {{true}, {false}});
}
public IntervalJoinOperatorTest(boolean lhsFasterThanRhs) {
this.lhsFasterThanRhs = lhsFasterThanRhs;
}
@TestTemplate
void testImplementationMirrorsCorrectly() throws Exception {
long lowerBound = 1;
long upperBound = 3;
boolean lowerBoundInclusive = true;
boolean upperBoundInclusive = false;
setupHarness(lowerBound, lowerBoundInclusive, upperBound, upperBoundInclusive)
.processElementsAndWatermarks(1, 4)
.andExpect(
streamRecordOf(1, 2),
streamRecordOf(1, 3),
streamRecordOf(2, 3),
streamRecordOf(2, 4),
streamRecordOf(3, 4))
.noLateRecords()
.close();
setupHarness(-1 * upperBound, upperBoundInclusive, -1 * lowerBound, lowerBoundInclusive)
.processElementsAndWatermarks(1, 4)
.andExpect(
streamRecordOf(2, 1),
streamRecordOf(3, 1),
streamRecordOf(3, 2),
streamRecordOf(4, 2),
streamRecordOf(4, 3))
.noLateRecords()
.close();
}
@TestTemplate // lhs - 2 <= rhs <= rhs + 2
void testNegativeInclusiveAndNegativeInclusive() throws Exception {
setupHarness(-2, true, -1, true)
.processElementsAndWatermarks(1, 4)
.andExpect(
streamRecordOf(2, 1),
streamRecordOf(3, 1),
streamRecordOf(3, 2),
streamRecordOf(4, 2),
streamRecordOf(4, 3))
.noLateRecords()
.close();
}
@TestTemplate // lhs - 1 <= rhs <= rhs + 1
void testNegativeInclusiveAndPositiveInclusive() throws Exception {
setupHarness(-1, true, 1, true)
.processElementsAndWatermarks(1, 4)
.andExpect(
streamRecordOf(1, 1),
streamRecordOf(1, 2),
streamRecordOf(2, 1),
streamRecordOf(2, 2),
streamRecordOf(2, 3),
streamRecordOf(3, 2),
streamRecordOf(3, 3),
streamRecordOf(3, 4),
streamRecordOf(4, 3),
streamRecordOf(4, 4))
.noLateRecords()
.close();
}
@TestTemplate // lhs + 1 <= rhs <= lhs + 2
void testPositiveInclusiveAndPositiveInclusive() throws Exception {
setupHarness(1, true, 2, true)
.processElementsAndWatermarks(1, 4)
.andExpect(
streamRecordOf(1, 2),
streamRecordOf(1, 3),
streamRecordOf(2, 3),
streamRecordOf(2, 4),
streamRecordOf(3, 4))
.noLateRecords()
.close();
}
@TestTemplate
void testNegativeExclusiveAndNegativeExlusive() throws Exception {
setupHarness(-3, false, -1, false)
.processElementsAndWatermarks(1, 4)
.andExpect(streamRecordOf(3, 1), streamRecordOf(4, 2))
.noLateRecords()
.close();
}
@TestTemplate
void testNegativeExclusiveAndPositiveExlusive() throws Exception {
setupHarness(-1, false, 1, false)
.processElementsAndWatermarks(1, 4)
.andExpect(
streamRecordOf(1, 1),
streamRecordOf(2, 2),
streamRecordOf(3, 3),
streamRecordOf(4, 4))
.noLateRecords()
.close();
}
@TestTemplate
void testPositiveExclusiveAndPositiveExlusive() throws Exception {
setupHarness(1, false, 3, false)
.processElementsAndWatermarks(1, 4)
.andExpect(streamRecordOf(1, 3), streamRecordOf(2, 4))
.noLateRecords()
.close();
}
@TestTemplate
void testStateCleanupNegativeInclusiveNegativeInclusive() throws Exception {
setupHarness(-1, true, 0, true)
.processElement1(1)
.processElement1(2)
.processElement1(3)
.processElement1(4)
.processElement1(5)
.processElement2(1)
.processElement2(2)
.processElement2(3)
.processElement2(4)
.processElement2(5) // fill both buffers with values
.processWatermark1(1)
.processWatermark2(1) // set common watermark to 1 and check that data is cleaned
.assertLeftBufferContainsOnly(2, 3, 4, 5)
.assertRightBufferContainsOnly(1, 2, 3, 4, 5)
.processWatermark1(4) // set common watermark to 4 and check that data is cleaned
.processWatermark2(4)
.assertLeftBufferContainsOnly(5)
.assertRightBufferContainsOnly(4, 5)
.processWatermark1(
6) // set common watermark to 6 and check that data all buffers are empty
.processWatermark2(6)
.assertLeftBufferEmpty()
.assertRightBufferEmpty()
.close();
}
@TestTemplate
void testStateCleanupNegativePositiveNegativeExlusive() throws Exception {
setupHarness(-2, false, 1, false)
.processElement1(1)
.processElement1(2)
.processElement1(3)
.processElement1(4)
.processElement1(5)
.processElement2(1)
.processElement2(2)
.processElement2(3)
.processElement2(4)
.processElement2(5) // fill both buffers with values
.processWatermark1(1)
.processWatermark2(1) // set common watermark to 1 and check that data is cleaned
.assertLeftBufferContainsOnly(2, 3, 4, 5)
.assertRightBufferContainsOnly(1, 2, 3, 4, 5)
.processWatermark1(4) // set common watermark to 4 and check that data is cleaned
.processWatermark2(4)
.assertLeftBufferContainsOnly(5)
.assertRightBufferContainsOnly(4, 5)
.processWatermark1(
6) // set common watermark to 6 and check that data all buffers are empty
.processWatermark2(6)
.assertLeftBufferEmpty()
.assertRightBufferEmpty()
.close();
}
@TestTemplate
void testStateCleanupPositiveInclusivePositiveInclusive() throws Exception {
setupHarness(0, true, 1, true)
.processElement1(1)
.processElement1(2)
.processElement1(3)
.processElement1(4)
.processElement1(5)
.processElement2(1)
.processElement2(2)
.processElement2(3)
.processElement2(4)
.processElement2(5) // fill both buffers with values
.processWatermark1(1)
.processWatermark2(1) // set common watermark to 1 and check that data is cleaned
.assertLeftBufferContainsOnly(1, 2, 3, 4, 5)
.assertRightBufferContainsOnly(2, 3, 4, 5)
.processWatermark1(4) // set common watermark to 4 and check that data is cleaned
.processWatermark2(4)
.assertLeftBufferContainsOnly(4, 5)
.assertRightBufferContainsOnly(5)
.processWatermark1(
6) // set common watermark to 6 and check that data all buffers are empty
.processWatermark2(6)
.assertLeftBufferEmpty()
.assertRightBufferEmpty()
.close();
}
@TestTemplate
void testStateCleanupPositiveExlusivePositiveExclusive() throws Exception {
setupHarness(-1, false, 2, false)
.processElement1(1)
.processElement1(2)
.processElement1(3)
.processElement1(4)
.processElement1(5)
.processElement2(1)
.processElement2(2)
.processElement2(3)
.processElement2(4)
.processElement2(5) // fill both buffers with values
.processWatermark1(1)
.processWatermark2(1) // set common watermark to 1 and check that data is cleaned
.assertLeftBufferContainsOnly(1, 2, 3, 4, 5)
.assertRightBufferContainsOnly(2, 3, 4, 5)
.processWatermark1(4) // set common watermark to 4 and check that data is cleaned
.processWatermark2(4)
.assertLeftBufferContainsOnly(4, 5)
.assertRightBufferContainsOnly(5)
.processWatermark1(
6) // set common watermark to 6 and check that data all buffers are empty
.processWatermark2(6)
.assertLeftBufferEmpty()
.assertRightBufferEmpty()
.close();
}
@TestTemplate
void testRestoreFromSnapshot() throws Exception {
// config
int lowerBound = -1;
boolean lowerBoundInclusive = true;
int upperBound = 1;
boolean upperBoundInclusive = true;
// create first test harness
OperatorSubtaskState handles;
List<StreamRecord<Tuple2<TestElem, TestElem>>> expectedOutput;
try (TestHarness testHarness =
createTestHarness(
lowerBound, lowerBoundInclusive, upperBound, upperBoundInclusive)) {
testHarness.setup();
testHarness.open();
// process elements with first test harness
testHarness.processElement1(createStreamRecord(1, "lhs"));
testHarness.processWatermark1(new Watermark(1));
testHarness.processElement2(createStreamRecord(1, "rhs"));
testHarness.processWatermark2(new Watermark(1));
testHarness.processElement1(createStreamRecord(2, "lhs"));
testHarness.processWatermark1(new Watermark(2));
testHarness.processElement2(createStreamRecord(2, "rhs"));
testHarness.processWatermark2(new Watermark(2));
testHarness.processElement1(createStreamRecord(3, "lhs"));
testHarness.processWatermark1(new Watermark(3));
testHarness.processElement2(createStreamRecord(3, "rhs"));
testHarness.processWatermark2(new Watermark(3));
// snapshot and validate output
handles = testHarness.snapshot(0, 0);
testHarness.close();
expectedOutput =
Lists.newArrayList(
streamRecordOf(1, 1),
streamRecordOf(1, 2),
streamRecordOf(2, 1),
streamRecordOf(2, 2),
streamRecordOf(2, 3),
streamRecordOf(3, 2),
streamRecordOf(3, 3));
TestHarnessUtil.assertNoLateRecords(testHarness.getOutput());
assertOutput(expectedOutput, testHarness.getOutput());
}
try (TestHarness newTestHarness =
createTestHarness(
lowerBound, lowerBoundInclusive, upperBound, upperBoundInclusive)) {
// create new test harness from snapshpt
newTestHarness.setup();
newTestHarness.initializeState(handles);
newTestHarness.open();
// process elements
newTestHarness.processElement1(createStreamRecord(4, "lhs"));
newTestHarness.processWatermark1(new Watermark(4));
newTestHarness.processElement2(createStreamRecord(4, "rhs"));
newTestHarness.processWatermark2(new Watermark(4));
// assert expected output
expectedOutput =
Lists.newArrayList(
streamRecordOf(3, 4), streamRecordOf(4, 3), streamRecordOf(4, 4));
TestHarnessUtil.assertNoLateRecords(newTestHarness.getOutput());
assertOutput(expectedOutput, newTestHarness.getOutput());
}
}
@TestTemplate
void testContextCorrectLeftTimestamp() throws Exception {
IntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> op =
new IntervalJoinOperator<>(
-1,
1,
true,
true,
null,
null,
TestElem.serializer(),
TestElem.serializer(),
new ProcessJoinFunction<TestElem, TestElem, Tuple2<TestElem, TestElem>>() {
@Override
public void processElement(
TestElem left,
TestElem right,
Context ctx,
Collector<Tuple2<TestElem, TestElem>> out)
throws Exception {
assertThat(ctx.getLeftTimestamp()).isEqualTo(left.ts);
}
});
try (TestHarness testHarness =
new TestHarness(
op,
(elem) -> elem.key,
(elem) -> elem.key,
TypeInformation.of(String.class))) {
testHarness.setup();
testHarness.open();
processElementsAndWatermarks(testHarness);
}
}
@TestTemplate
void testReturnsCorrectTimestamp() throws Exception {
IntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> op =
new IntervalJoinOperator<>(
-1,
1,
true,
true,
null,
null,
TestElem.serializer(),
TestElem.serializer(),
new ProcessJoinFunction<TestElem, TestElem, Tuple2<TestElem, TestElem>>() {
private static final long serialVersionUID = 1L;
@Override
public void processElement(
TestElem left,
TestElem right,
Context ctx,
Collector<Tuple2<TestElem, TestElem>> out)
throws Exception {
assertThat(ctx.getTimestamp())
.isEqualTo(Math.max(left.ts, right.ts));
}
});
try (TestHarness testHarness =
new TestHarness(
op,
(elem) -> elem.key,
(elem) -> elem.key,
TypeInformation.of(String.class))) {
testHarness.setup();
testHarness.open();
processElementsAndWatermarks(testHarness);
}
}
@TestTemplate
void testContextCorrectRightTimestamp() throws Exception {
IntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> op =
new IntervalJoinOperator<>(
-1,
1,
true,
true,
null,
null,
TestElem.serializer(),
TestElem.serializer(),
new ProcessJoinFunction<TestElem, TestElem, Tuple2<TestElem, TestElem>>() {
@Override
public void processElement(
TestElem left,
TestElem right,
Context ctx,
Collector<Tuple2<TestElem, TestElem>> out)
throws Exception {
assertThat(ctx.getRightTimestamp()).isEqualTo(right.ts);
}
});
try (TestHarness testHarness =
new TestHarness(
op,
(elem) -> elem.key,
(elem) -> elem.key,
TypeInformation.of(String.class))) {
testHarness.setup();
testHarness.open();
processElementsAndWatermarks(testHarness);
}
}
@TestTemplate
void testFailsWithNoTimestampsLeft() throws Exception {
try (TestHarness newTestHarness = createTestHarness(0L, true, 0L, true)) {
newTestHarness.setup();
newTestHarness.open();
// note that the StreamRecord has no timestamp in constructor
assertThatThrownBy(
() ->
newTestHarness.processElement1(
new StreamRecord<>(new TestElem(0, "lhs"))))
.isInstanceOf(FlinkException.class);
}
}
@TestTemplate // (expected = FlinkException.class)
void testFailsWithNoTimestampsRight() throws Exception {
try (TestHarness newTestHarness = createTestHarness(0L, true, 0L, true)) {
newTestHarness.setup();
newTestHarness.open();
// note that the StreamRecord has no timestamp in constructor
assertThatThrownBy(
() ->
newTestHarness.processElement2(
new StreamRecord<>(new TestElem(0, "rhs"))))
.isInstanceOf(FlinkException.class);
}
}
@TestTemplate
void testDiscardsLateData() throws Exception {
setupHarness(-1, true, 1, true)
.processElement1(1)
.processElement2(1)
.processElement1(2)
.processElement2(2)
.processElement1(3)
.processElement2(3)
.processWatermark1(3)
.processWatermark2(3)
.processElement1(1) // this element is late and should not be joined again
.processElement1(4)
.processElement2(4)
.processElement1(5)
.processElement2(5)
.andExpect(
streamRecordOf(1, 1),
streamRecordOf(1, 2),
streamRecordOf(2, 1),
streamRecordOf(2, 2),
streamRecordOf(2, 3),
streamRecordOf(3, 2),
streamRecordOf(3, 3),
streamRecordOf(3, 4),
streamRecordOf(4, 3),
streamRecordOf(4, 4),
streamRecordOf(4, 5),
streamRecordOf(5, 4),
streamRecordOf(5, 5))
.noLateRecords()
.close();
}
@TestTemplate
void testLateData() throws Exception {
OutputTag<TestElem> leftLateTag = new OutputTag<TestElem>("left_late") {};
OutputTag<TestElem> rightLateTag = new OutputTag<TestElem>("right_late") {};
setupHarness(-1, true, 1, true, leftLateTag, rightLateTag)
.processElement1(3)
.processElement2(3)
.processWatermark1(3)
.processWatermark2(3)
.processElement1(4)
.processElement2(4)
.processElement1(1) // the left side element is late
.processElement2(2) // the right side element is late
.processElement1(5)
.processElement2(5)
.andExpect(
streamRecordOf(3, 3),
streamRecordOf(3, 4),
streamRecordOf(4, 3),
streamRecordOf(4, 4),
streamRecordOf(4, 5),
streamRecordOf(5, 4),
streamRecordOf(5, 5))
.expectLateRecords(leftLateTag, createStreamRecord(1, "lhs"))
.expectLateRecords(rightLateTag, createStreamRecord(2, "rhs"))
.close();
}
private void assertEmpty(MapState<Long, ?> state) throws Exception {
assertThat(state.keys()).isEmpty();
}
private void assertContainsOnly(MapState<Long, ?> state, long... ts) throws Exception {
for (long t : ts) {
String message =
"Keys not found in state. \n Expected: "
+ Arrays.toString(ts)
+ "\n Actual: "
+ state.keys();
assertThat(state.contains(t)).as(message).isTrue();
}
String message =
"Too many objects in state. \n Expected: "
+ Arrays.toString(ts)
+ "\n Actual: "
+ state.keys();
assertThat(state.keys()).as(message).hasSize(ts.length);
}
private <T1, T2> void assertOutput(
Iterable<StreamRecord<T1>> expectedOutput, Queue<T2> actualOutput) {
int actualSize =
actualOutput.stream()
.filter(elem -> elem instanceof StreamRecord)
.collect(Collectors.toList())
.size();
int expectedSize = Iterables.size(expectedOutput);
assertThat(actualSize)
.as("Expected and actual size of stream records different")
.isEqualTo(expectedSize);
for (StreamRecord<T1> record : expectedOutput) {
assertThat(actualOutput.contains(record)).isTrue();
}
}
private TestHarness createTestHarness(
long lowerBound,
boolean lowerBoundInclusive,
long upperBound,
boolean upperBoundInclusive)
throws Exception {
IntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> operator =
new IntervalJoinOperator<>(
lowerBound,
upperBound,
lowerBoundInclusive,
upperBoundInclusive,
null,
null,
TestElem.serializer(),
TestElem.serializer(),
new PassthroughFunction());
return new TestHarness(
operator,
(elem) -> elem.key, // key
(elem) -> elem.key, // key
TypeInformation.of(String.class));
}
private JoinTestBuilder setupHarness(
long lowerBound,
boolean lowerBoundInclusive,
long upperBound,
boolean upperBoundInclusive,
OutputTag<TestElem> leftLateDataOutputTag,
OutputTag<TestElem> rightLateDataOutputTag)
throws Exception {
IntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>> operator =
new IntervalJoinOperator<>(
lowerBound,
upperBound,
lowerBoundInclusive,
upperBoundInclusive,
leftLateDataOutputTag,
rightLateDataOutputTag,
TestElem.serializer(),
TestElem.serializer(),
new PassthroughFunction());
TestHarness t =
new TestHarness(
operator,
(elem) -> elem.key, // key
(elem) -> elem.key, // key
TypeInformation.of(String.class));
return new JoinTestBuilder(t, operator);
}
private JoinTestBuilder setupHarness(
long lowerBound,
boolean lowerBoundInclusive,
long upperBound,
boolean upperBoundInclusive)
throws Exception {
return setupHarness(
lowerBound, lowerBoundInclusive, upperBound, upperBoundInclusive, null, null);
}
private class JoinTestBuilder {
private IntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>>
operator;
private TestHarness testHarness;
public JoinTestBuilder(
TestHarness t,
IntervalJoinOperator<String, TestElem, TestElem, Tuple2<TestElem, TestElem>>
operator)
throws Exception {
this.testHarness = t;
this.operator = operator;
t.open();
t.setup();
}
public TestHarness get() {
return testHarness;
}
public JoinTestBuilder processElement1(int ts) throws Exception {
testHarness.processElement1(createStreamRecord(ts, "lhs"));
return this;
}
public JoinTestBuilder processElement2(int ts) throws Exception {
testHarness.processElement2(createStreamRecord(ts, "rhs"));
return this;
}
public JoinTestBuilder processWatermark1(int ts) throws Exception {
testHarness.processWatermark1(new Watermark(ts));
return this;
}
public JoinTestBuilder processWatermark2(int ts) throws Exception {
testHarness.processWatermark2(new Watermark(ts));
return this;
}
public JoinTestBuilder processElementsAndWatermarks(int from, int to) throws Exception {
if (lhsFasterThanRhs) {
// add to lhs
for (int i = from; i <= to; i++) {
testHarness.processElement1(createStreamRecord(i, "lhs"));
testHarness.processWatermark1(new Watermark(i));
}
// add to rhs
for (int i = from; i <= to; i++) {
testHarness.processElement2(createStreamRecord(i, "rhs"));
testHarness.processWatermark2(new Watermark(i));
}
} else {
// add to rhs
for (int i = from; i <= to; i++) {
testHarness.processElement2(createStreamRecord(i, "rhs"));
testHarness.processWatermark2(new Watermark(i));
}
// add to lhs
for (int i = from; i <= to; i++) {
testHarness.processElement1(createStreamRecord(i, "lhs"));
testHarness.processWatermark1(new Watermark(i));
}
}
return this;
}
@SafeVarargs
public final JoinTestBuilder andExpect(StreamRecord<Tuple2<TestElem, TestElem>>... elems) {
assertOutput(Lists.newArrayList(elems), testHarness.getOutput());
return this;
}
public JoinTestBuilder assertLeftBufferContainsOnly(long... timestamps) {
try {
assertContainsOnly(operator.getLeftBuffer(), timestamps);
} catch (Exception e) {
throw new RuntimeException(e);
}
return this;
}
public JoinTestBuilder assertRightBufferContainsOnly(long... timestamps) {
try {
assertContainsOnly(operator.getRightBuffer(), timestamps);
} catch (Exception e) {
throw new RuntimeException(e);
}
return this;
}
public JoinTestBuilder assertLeftBufferEmpty() {
try {
assertEmpty(operator.getLeftBuffer());
} catch (Exception e) {
throw new RuntimeException(e);
}
return this;
}
public JoinTestBuilder assertRightBufferEmpty() {
try {
assertEmpty(operator.getRightBuffer());
} catch (Exception e) {
throw new RuntimeException(e);
}
return this;
}
@SafeVarargs
public final JoinTestBuilder expectLateRecords(
OutputTag<TestElem> tag, StreamRecord<TestElem>... elems) {
assertOutput(Lists.newArrayList(elems), testHarness.getSideOutput(tag));
return this;
}
public JoinTestBuilder noLateRecords() {
TestHarnessUtil.assertNoLateRecords(this.testHarness.getOutput());
return this;
}
public void close() throws Exception {
testHarness.close();
}
}
private static class PassthroughFunction
extends ProcessJoinFunction<TestElem, TestElem, Tuple2<TestElem, TestElem>> {
@Override
public void processElement(
TestElem left,
TestElem right,
Context ctx,
Collector<Tuple2<TestElem, TestElem>> out)
throws Exception {
out.collect(Tuple2.of(left, right));
}
}
private StreamRecord<Tuple2<TestElem, TestElem>> streamRecordOf(long lhsTs, long rhsTs) {
TestElem lhs = new TestElem(lhsTs, "lhs");
TestElem rhs = new TestElem(rhsTs, "rhs");
long ts = Math.max(lhsTs, rhsTs);
return new StreamRecord<>(Tuple2.of(lhs, rhs), ts);
}
private static class TestElem {
String key;
long ts;
String source;
public TestElem(long ts, String source) {
this.key = "key";
this.ts = ts;
this.source = source;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TestElem testElem = (TestElem) o;
if (ts != testElem.ts) {
return false;
}
if (key != null ? !key.equals(testElem.key) : testElem.key != null) {
return false;
}
return source != null ? source.equals(testElem.source) : testElem.source == null;
}
@Override
public int hashCode() {
int result = key != null ? key.hashCode() : 0;
result = 31 * result + (int) (ts ^ (ts >>> 32));
result = 31 * result + (source != null ? source.hashCode() : 0);
return result;
}
@Override
public String toString() {
return this.source + ":" + this.ts;
}
public static TypeSerializer<TestElem> serializer() {
return TypeInformation.of(new TypeHint<TestElem>() {})
.createSerializer(new SerializerConfigImpl());
}
}
private static StreamRecord<TestElem> createStreamRecord(long ts, String source) {
TestElem testElem = new TestElem(ts, source);
return new StreamRecord<>(testElem, ts);
}
private void processElementsAndWatermarks(TestHarness testHarness) throws Exception {
if (lhsFasterThanRhs) {
// add to lhs
for (int i = 1; i <= 4; i++) {
testHarness.processElement1(createStreamRecord(i, "lhs"));
testHarness.processWatermark1(new Watermark(i));
}
// add to rhs
for (int i = 1; i <= 4; i++) {
testHarness.processElement2(createStreamRecord(i, "rhs"));
testHarness.processWatermark2(new Watermark(i));
}
} else {
// add to rhs
for (int i = 1; i <= 4; i++) {
testHarness.processElement2(createStreamRecord(i, "rhs"));
testHarness.processWatermark2(new Watermark(i));
}
// add to lhs
for (int i = 1; i <= 4; i++) {
testHarness.processElement1(createStreamRecord(i, "lhs"));
testHarness.processWatermark1(new Watermark(i));
}
}
}
/** Custom test harness to avoid endless generics in all of the test code. */
private static class TestHarness
extends KeyedTwoInputStreamOperatorTestHarness<
String, TestElem, TestElem, Tuple2<TestElem, TestElem>> {
TestHarness(
TwoInputStreamOperator<TestElem, TestElem, Tuple2<TestElem, TestElem>> operator,
KeySelector<TestElem, String> keySelector1,
KeySelector<TestElem, String> keySelector2,
TypeInformation<String> keyType)
throws Exception {
super(operator, keySelector1, keySelector2, keyType);
}
}
}
|
googleapis/google-cloud-java | 36,445 | java-cloudquotas/proto-google-cloud-cloudquotas-v1beta/src/main/java/com/google/api/cloudquotas/v1beta/ListQuotaInfosResponse.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/cloudquotas/v1beta/cloudquotas.proto
// Protobuf Java Version: 3.25.8
package com.google.api.cloudquotas.v1beta;
/**
*
*
* <pre>
* Message for response to listing QuotaInfos
* </pre>
*
* Protobuf type {@code google.api.cloudquotas.v1beta.ListQuotaInfosResponse}
*/
public final class ListQuotaInfosResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.api.cloudquotas.v1beta.ListQuotaInfosResponse)
ListQuotaInfosResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListQuotaInfosResponse.newBuilder() to construct.
private ListQuotaInfosResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListQuotaInfosResponse() {
quotaInfos_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListQuotaInfosResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.api.cloudquotas.v1beta.CloudquotasProto
.internal_static_google_api_cloudquotas_v1beta_ListQuotaInfosResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.api.cloudquotas.v1beta.CloudquotasProto
.internal_static_google_api_cloudquotas_v1beta_ListQuotaInfosResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse.class,
com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse.Builder.class);
}
public static final int QUOTA_INFOS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.api.cloudquotas.v1beta.QuotaInfo> quotaInfos_;
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.api.cloudquotas.v1beta.QuotaInfo> getQuotaInfosList() {
return quotaInfos_;
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.api.cloudquotas.v1beta.QuotaInfoOrBuilder>
getQuotaInfosOrBuilderList() {
return quotaInfos_;
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
@java.lang.Override
public int getQuotaInfosCount() {
return quotaInfos_.size();
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
@java.lang.Override
public com.google.api.cloudquotas.v1beta.QuotaInfo getQuotaInfos(int index) {
return quotaInfos_.get(index);
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
@java.lang.Override
public com.google.api.cloudquotas.v1beta.QuotaInfoOrBuilder getQuotaInfosOrBuilder(int index) {
return quotaInfos_.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 < quotaInfos_.size(); i++) {
output.writeMessage(1, quotaInfos_.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 < quotaInfos_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, quotaInfos_.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.api.cloudquotas.v1beta.ListQuotaInfosResponse)) {
return super.equals(obj);
}
com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse other =
(com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse) obj;
if (!getQuotaInfosList().equals(other.getQuotaInfosList())) 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 (getQuotaInfosCount() > 0) {
hash = (37 * hash) + QUOTA_INFOS_FIELD_NUMBER;
hash = (53 * hash) + getQuotaInfosList().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.api.cloudquotas.v1beta.ListQuotaInfosResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse 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.cloudquotas.v1beta.ListQuotaInfosResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse 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.cloudquotas.v1beta.ListQuotaInfosResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse 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.cloudquotas.v1beta.ListQuotaInfosResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse 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.cloudquotas.v1beta.ListQuotaInfosResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse 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.cloudquotas.v1beta.ListQuotaInfosResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Message for response to listing QuotaInfos
* </pre>
*
* Protobuf type {@code google.api.cloudquotas.v1beta.ListQuotaInfosResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.api.cloudquotas.v1beta.ListQuotaInfosResponse)
com.google.api.cloudquotas.v1beta.ListQuotaInfosResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.api.cloudquotas.v1beta.CloudquotasProto
.internal_static_google_api_cloudquotas_v1beta_ListQuotaInfosResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.api.cloudquotas.v1beta.CloudquotasProto
.internal_static_google_api_cloudquotas_v1beta_ListQuotaInfosResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse.class,
com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse.Builder.class);
}
// Construct using com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (quotaInfosBuilder_ == null) {
quotaInfos_ = java.util.Collections.emptyList();
} else {
quotaInfos_ = null;
quotaInfosBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.api.cloudquotas.v1beta.CloudquotasProto
.internal_static_google_api_cloudquotas_v1beta_ListQuotaInfosResponse_descriptor;
}
@java.lang.Override
public com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse getDefaultInstanceForType() {
return com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse build() {
com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse buildPartial() {
com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse result =
new com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse result) {
if (quotaInfosBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
quotaInfos_ = java.util.Collections.unmodifiableList(quotaInfos_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.quotaInfos_ = quotaInfos_;
} else {
result.quotaInfos_ = quotaInfosBuilder_.build();
}
}
private void buildPartial0(com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse 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.api.cloudquotas.v1beta.ListQuotaInfosResponse) {
return mergeFrom((com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse other) {
if (other == com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse.getDefaultInstance())
return this;
if (quotaInfosBuilder_ == null) {
if (!other.quotaInfos_.isEmpty()) {
if (quotaInfos_.isEmpty()) {
quotaInfos_ = other.quotaInfos_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureQuotaInfosIsMutable();
quotaInfos_.addAll(other.quotaInfos_);
}
onChanged();
}
} else {
if (!other.quotaInfos_.isEmpty()) {
if (quotaInfosBuilder_.isEmpty()) {
quotaInfosBuilder_.dispose();
quotaInfosBuilder_ = null;
quotaInfos_ = other.quotaInfos_;
bitField0_ = (bitField0_ & ~0x00000001);
quotaInfosBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getQuotaInfosFieldBuilder()
: null;
} else {
quotaInfosBuilder_.addAllMessages(other.quotaInfos_);
}
}
}
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.api.cloudquotas.v1beta.QuotaInfo m =
input.readMessage(
com.google.api.cloudquotas.v1beta.QuotaInfo.parser(), extensionRegistry);
if (quotaInfosBuilder_ == null) {
ensureQuotaInfosIsMutable();
quotaInfos_.add(m);
} else {
quotaInfosBuilder_.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.api.cloudquotas.v1beta.QuotaInfo> quotaInfos_ =
java.util.Collections.emptyList();
private void ensureQuotaInfosIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
quotaInfos_ =
new java.util.ArrayList<com.google.api.cloudquotas.v1beta.QuotaInfo>(quotaInfos_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.api.cloudquotas.v1beta.QuotaInfo,
com.google.api.cloudquotas.v1beta.QuotaInfo.Builder,
com.google.api.cloudquotas.v1beta.QuotaInfoOrBuilder>
quotaInfosBuilder_;
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public java.util.List<com.google.api.cloudquotas.v1beta.QuotaInfo> getQuotaInfosList() {
if (quotaInfosBuilder_ == null) {
return java.util.Collections.unmodifiableList(quotaInfos_);
} else {
return quotaInfosBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public int getQuotaInfosCount() {
if (quotaInfosBuilder_ == null) {
return quotaInfos_.size();
} else {
return quotaInfosBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public com.google.api.cloudquotas.v1beta.QuotaInfo getQuotaInfos(int index) {
if (quotaInfosBuilder_ == null) {
return quotaInfos_.get(index);
} else {
return quotaInfosBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public Builder setQuotaInfos(int index, com.google.api.cloudquotas.v1beta.QuotaInfo value) {
if (quotaInfosBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureQuotaInfosIsMutable();
quotaInfos_.set(index, value);
onChanged();
} else {
quotaInfosBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public Builder setQuotaInfos(
int index, com.google.api.cloudquotas.v1beta.QuotaInfo.Builder builderForValue) {
if (quotaInfosBuilder_ == null) {
ensureQuotaInfosIsMutable();
quotaInfos_.set(index, builderForValue.build());
onChanged();
} else {
quotaInfosBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public Builder addQuotaInfos(com.google.api.cloudquotas.v1beta.QuotaInfo value) {
if (quotaInfosBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureQuotaInfosIsMutable();
quotaInfos_.add(value);
onChanged();
} else {
quotaInfosBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public Builder addQuotaInfos(int index, com.google.api.cloudquotas.v1beta.QuotaInfo value) {
if (quotaInfosBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureQuotaInfosIsMutable();
quotaInfos_.add(index, value);
onChanged();
} else {
quotaInfosBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public Builder addQuotaInfos(
com.google.api.cloudquotas.v1beta.QuotaInfo.Builder builderForValue) {
if (quotaInfosBuilder_ == null) {
ensureQuotaInfosIsMutable();
quotaInfos_.add(builderForValue.build());
onChanged();
} else {
quotaInfosBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public Builder addQuotaInfos(
int index, com.google.api.cloudquotas.v1beta.QuotaInfo.Builder builderForValue) {
if (quotaInfosBuilder_ == null) {
ensureQuotaInfosIsMutable();
quotaInfos_.add(index, builderForValue.build());
onChanged();
} else {
quotaInfosBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public Builder addAllQuotaInfos(
java.lang.Iterable<? extends com.google.api.cloudquotas.v1beta.QuotaInfo> values) {
if (quotaInfosBuilder_ == null) {
ensureQuotaInfosIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, quotaInfos_);
onChanged();
} else {
quotaInfosBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public Builder clearQuotaInfos() {
if (quotaInfosBuilder_ == null) {
quotaInfos_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
quotaInfosBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public Builder removeQuotaInfos(int index) {
if (quotaInfosBuilder_ == null) {
ensureQuotaInfosIsMutable();
quotaInfos_.remove(index);
onChanged();
} else {
quotaInfosBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public com.google.api.cloudquotas.v1beta.QuotaInfo.Builder getQuotaInfosBuilder(int index) {
return getQuotaInfosFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public com.google.api.cloudquotas.v1beta.QuotaInfoOrBuilder getQuotaInfosOrBuilder(int index) {
if (quotaInfosBuilder_ == null) {
return quotaInfos_.get(index);
} else {
return quotaInfosBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public java.util.List<? extends com.google.api.cloudquotas.v1beta.QuotaInfoOrBuilder>
getQuotaInfosOrBuilderList() {
if (quotaInfosBuilder_ != null) {
return quotaInfosBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(quotaInfos_);
}
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public com.google.api.cloudquotas.v1beta.QuotaInfo.Builder addQuotaInfosBuilder() {
return getQuotaInfosFieldBuilder()
.addBuilder(com.google.api.cloudquotas.v1beta.QuotaInfo.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public com.google.api.cloudquotas.v1beta.QuotaInfo.Builder addQuotaInfosBuilder(int index) {
return getQuotaInfosFieldBuilder()
.addBuilder(index, com.google.api.cloudquotas.v1beta.QuotaInfo.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of QuotaInfo
* </pre>
*
* <code>repeated .google.api.cloudquotas.v1beta.QuotaInfo quota_infos = 1;</code>
*/
public java.util.List<com.google.api.cloudquotas.v1beta.QuotaInfo.Builder>
getQuotaInfosBuilderList() {
return getQuotaInfosFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.api.cloudquotas.v1beta.QuotaInfo,
com.google.api.cloudquotas.v1beta.QuotaInfo.Builder,
com.google.api.cloudquotas.v1beta.QuotaInfoOrBuilder>
getQuotaInfosFieldBuilder() {
if (quotaInfosBuilder_ == null) {
quotaInfosBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.api.cloudquotas.v1beta.QuotaInfo,
com.google.api.cloudquotas.v1beta.QuotaInfo.Builder,
com.google.api.cloudquotas.v1beta.QuotaInfoOrBuilder>(
quotaInfos_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
quotaInfos_ = null;
}
return quotaInfosBuilder_;
}
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.api.cloudquotas.v1beta.ListQuotaInfosResponse)
}
// @@protoc_insertion_point(class_scope:google.api.cloudquotas.v1beta.ListQuotaInfosResponse)
private static final com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse();
}
public static com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListQuotaInfosResponse> PARSER =
new com.google.protobuf.AbstractParser<ListQuotaInfosResponse>() {
@java.lang.Override
public ListQuotaInfosResponse 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<ListQuotaInfosResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListQuotaInfosResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.api.cloudquotas.v1beta.ListQuotaInfosResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
oracle/graal | 36,825 | compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/nodes/loop/CountedLoopInfo.java | /*
* Copyright (c) 2012, 2021, 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 jdk.graal.compiler.nodes.loop;
import jdk.graal.compiler.core.common.type.IntegerStamp;
import jdk.graal.compiler.core.common.type.Stamp;
import jdk.graal.compiler.core.common.type.StampFactory;
import jdk.graal.compiler.core.common.util.UnsignedLong;
import jdk.graal.compiler.debug.Assertions;
import jdk.graal.compiler.debug.DebugCloseable;
import jdk.graal.compiler.debug.GraalError;
import jdk.graal.compiler.graph.Node;
import jdk.graal.compiler.nodes.AbstractBeginNode;
import jdk.graal.compiler.nodes.ConstantNode;
import jdk.graal.compiler.nodes.FixedGuardNode;
import jdk.graal.compiler.nodes.GuardNode;
import jdk.graal.compiler.nodes.IfNode;
import jdk.graal.compiler.nodes.LogicConstantNode;
import jdk.graal.compiler.nodes.LogicNode;
import jdk.graal.compiler.nodes.LoopBeginNode;
import jdk.graal.compiler.nodes.NodeView;
import jdk.graal.compiler.nodes.PiNode;
import jdk.graal.compiler.nodes.StructuredGraph;
import jdk.graal.compiler.nodes.ValueNode;
import jdk.graal.compiler.nodes.calc.BinaryArithmeticNode;
import jdk.graal.compiler.nodes.calc.CompareNode;
import jdk.graal.compiler.nodes.calc.ConditionalNode;
import jdk.graal.compiler.nodes.calc.NegateNode;
import jdk.graal.compiler.nodes.cfg.ControlFlowGraph;
import jdk.graal.compiler.nodes.cfg.HIRBlock;
import jdk.graal.compiler.nodes.extended.GuardingNode;
import jdk.graal.compiler.nodes.loop.InductionVariable.Direction;
import jdk.graal.compiler.nodes.util.IntegerHelper;
import jdk.graal.compiler.nodes.util.SignedIntegerHelper;
import jdk.graal.compiler.nodes.util.UnsignedIntegerHelper;
import jdk.graal.compiler.phases.common.util.LoopUtility;
import jdk.vm.ci.meta.DeoptimizationAction;
import jdk.vm.ci.meta.DeoptimizationReason;
import jdk.vm.ci.meta.JavaKind;
import jdk.vm.ci.meta.SpeculationLog;
/**
* Class representing meta information about a counted loop.
*
* Comments on the nomenclature for {@link #getLimit()}, {@link #getBody()},
* {@link #getLimitCheckedIV()} and {@link #getBodyIV()}:
*
* A regular head counted loop like
*
* <pre>
* for (int i = 0; i < end; i++) {
* // body
* }
* </pre>
*
* has a limit (end) that is compared against the {@link InductionVariable} (iv) returned by
* getLimitCheckedIV. The iv for the loop above is the basic induction variable i.
*
* For inverted loops like
*
* <pre>
* int i = 0;
* do {
* // body
* i++;
* } while(i < end)
* </pre>
*
* The iv compared against limit is not i, but the next iteration's body iv i+1.
*
* Thus, for inverted loops {@link #getBodyIV()} returns a different result than
* {@link #getLimitCheckedIV()}. {@link #getBodyIV()} returns i, while {@link #getLimitCheckedIV()}
* returns i + 1.
*
* Furthermore, the contract between {@link #getLimitCheckedIV()} and {@link #getBodyIV()} defines
* that both IVs iterate on the same signed-ness range, i.e., if one is purely in an unsigned range
* the other one has to be as well (same applies for signed integers). This means that optimizations
* can safely use {@link IntegerHelper} based on the signed-ness of the {@link #getLimitCheckedIV()}
* to compute min/max and iteration ranges for the loops involved.
*/
public class CountedLoopInfo {
protected final Loop loop;
/**
* @see CountedLoopInfo#getLimitCheckedIV()
*/
protected InductionVariable limitCheckedIV;
/**
* @see #getLimit()
*/
protected ValueNode limit;
/**
* {@code true} iff the limit is included in the limit test, e.g., the limit test is
* {@code i <= n} rather than {@code i < n}.
*/
protected boolean isLimitIncluded;
/**
* The first node inside the loop that is not considered to be part of the loop control nodes
* (terminating conditions). Depending on the shape of the loop, this can be different kind of
* nodes.
*/
protected AbstractBeginNode body;
/**
* The condition node that determines if this loop is exited or not. Can be in head or tail
* position depending on the shape of the loop. There can be an arbitrary number of if nodes in
* a loop. This one is special in that it either dominates or post dominates all others.
*/
protected IfNode ifNode;
/**
* Determine if we consider the control logic of the loop working in unsigned integer ranges.
*/
protected final boolean unsigned;
protected CountedLoopInfo(Loop loop, InductionVariable limitCheckedIV, IfNode ifNode, ValueNode limit, boolean isLimitIncluded, AbstractBeginNode body, boolean unsigned) {
assert limitCheckedIV.direction() != null;
this.loop = loop;
this.limitCheckedIV = limitCheckedIV;
this.limit = limit;
this.isLimitIncluded = isLimitIncluded;
this.body = body;
this.ifNode = ifNode;
this.unsigned = unsigned;
}
/**
* See {@link InductionVariable#structuralIntegrityValid()}.
*/
public boolean countedIntegrityValid() {
return limitCheckedIV.structuralIntegrityValid() && limit.isAlive() && body.isAlive() && ifNode.isAlive();
}
/**
* Returns the induction variable compared against the limit node. For a loop like
*
* <pre>
* for (int i = 0; i < limit; i++) {
* body();
* }
* </pre>
*
* The induction variable {@code i} is the limit checked one, {@code limit} will be the limit
* node. In the case where the {@link #getLimitCheckedIV()} is a {@link BasicInductionVariable}
* {@link #getLimitCheckedIV()} equals {@link #getBodyIV()}. Note that for other loop shapes the
* limit checked IV can be a {@link DerivedInductionVariable}.
*
* For a loop like
*
* <pre>
* for (int i = 0; (i + 5) < limit; i++) {
* body();
* }
* </pre>
*
* the limit checked IV will be a {@link DerivedOffsetInductionVariable} with the constant
* offset {@code 5}. In this case the {@link CountedLoopInfo#getBodyIV()} will be the
* {@link DerivedOffsetInductionVariable#getBase()} of the {@link #getLimitCheckedIV()}. This is
* the regular IV {@code i}. Most {@link #isInverted()} inverted loops have a shape where the
* limit checked IV is a {@link DerivedInductionVariable}.
*
* @return the {@link InductionVariable} compared ({@link CompareNode}) to
* {@link CountedLoopInfo#getLimit()}. If this loop is
* {@link CountedLoopInfo#isInverted()} returns to next iteration iv based on
* {@link CountedLoopInfo#getBodyIV()}.
*/
public InductionVariable getLimitCheckedIV() {
return limitCheckedIV;
}
/**
* @return the {@link InductionVariable} used in the body of this {@link CountedLoopInfo}. If
* {@link CountedLoopInfo#isInverted()} returns {@code false} this returns the same as
* {@link CountedLoopInfo#getLimitCheckedIV()}.
*/
protected InductionVariable getBodyIV() {
assert !isInverted() && getLimitCheckedIV() == limitCheckedIV : "Only inverted loops must have different body ivs.";
return limitCheckedIV;
}
/**
* @return the {@link InductionVariable#extremumNode()} for the {@link #getBodyIV()}.
*/
public ValueNode getBodyIVExtremum() {
return getBodyIV().extremumNode(true, StampFactory.forKind(JavaKind.Long));
}
/**
* @return the {@link InductionVariable#exitValueNode()} for the {@link #getBodyIV()}.
*/
public ValueNode getBodyIVExitValue() {
return getBodyIV().exitValueNode();
}
/**
* @return {@code true} iff {@link #getBodyIV()} equals {@link #getLimitCheckedIV()}.
*/
public boolean getBodyIVEqualsLimitCheckedIV() {
return getBodyIV() == getLimitCheckedIV();
}
/**
* Returns the {@link InductionVariable#entryTripValue()} for the
* {@link DerivedInductionVariable#getBase()} if {@link #getLimitCheckedIV()} is a
* {@link DerivedInductionVariable} else returns its
* {@link InductionVariableHelper#previousIteration(InductionVariable)} entry value. That is,
* the entry value of the {@link #getBodyIV()} if its an {@link #isInverted()} (because that is
* the limit checked IV's based) else the previous iteration of the regular
* {@link #getLimitCheckedIV()}.
*/
public ValueNode limitCheckedPreviousOrRootEntryValue() {
if (getBodyIVEqualsLimitCheckedIV()) {
InductionVariable limitCheckedIVDuplicated = InductionVariableHelper.previousIteration(getLimitCheckedIV()).duplicate();
return limitCheckedIVDuplicated.entryTripValue();
} else {
InductionVariable limitCheckedIVDuplicated = loop.counted().getBodyIV().duplicate();
return limitCheckedIVDuplicated.entryTripValue();
}
}
/**
* Returns the limit node of this counted loop.
*
* @return the {@link ValueNode} that is compared ({@link CompareNode}) to the
* {@link InductionVariable} return by {@link CountedLoopInfo#getLimitCheckedIV()}
*/
public ValueNode getLimit() {
return limit;
}
/**
* Returns the mathematical limit that is used to compute the
* {@link CountedLoopInfo#maxTripCountNode()}. If {@link CountedLoopInfo#isInverted()} is
* {@code false} this returns the same as {@link CountedLoopInfo#getLimit()}. Otherwise,
* depending on the shape of the inverted loops this may return a value that is |stride| off the
* real limit to account for inverted loops with none-inverted limit checks.
*
* Consider the following inverted loop
*
* <pre>
* int i = 0;
* do {
* i++;
* } while (i < 100);
* </pre>
*
* This loop performs 100 iterations. However, the following loop
*
* <pre>
* int i = 0;
* do {
* } while (i++ < 100);
* </pre>
*
* performs 101 iterations.
*
*
* While the "limit" of both is 100, the "real" mathematical limit of the second one is 101.
* Thus, in order to perform correct calculation of {@link CountedLoopInfo#maxTripCountNode()}
* we distinguish between those two concepts.
*/
public ValueNode getTripCountLimit() {
assert !isInverted() && getLimit() == limit : "Only inverted loops must have a different trip count limit";
return limit;
}
private void assertNoOverflow() {
GraalError.guarantee(loopCanNeverOverflow(), "Counter must never overflow when reasoning about trip counts of a loop");
}
/**
* Returns a node that computes the maximum trip count of this loop. That is the trip count of
* this loop assuming it is not exited by an other exit than the {@linkplain #getLimitTest()
* count check}.
*
* This count is exact if {@link #isExactTripCount()} returns true.
*
* THIS VALUE SHOULD BE TREATED AS UNSIGNED.
*/
public ValueNode maxTripCountNode() {
assertNoOverflow();
return maxTripCountNode(false);
}
public boolean isUnsignedCheck() {
return this.unsigned;
}
public ValueNode maxTripCountNode(boolean assumeLoopEntered) {
assertNoOverflow();
return maxTripCountNode(assumeLoopEntered, getCounterIntegerHelper());
}
protected ValueNode maxTripCountNode(boolean assumeLoopEntered, IntegerHelper integerHelper) {
assertNoOverflow();
// we use body IV init as that is the init of the derived IV if limitCheckedIV != getBodyIV
return maxTripCountNode(assumeLoopEntered, integerHelper, getBodyIVStart(), getTripCountLimit());
}
/**
* Returns a node that computes the maximum trip count of this loop. That is the trip count of
* this loop assuming it is not exited by an other exit than the {@link #getLimitTest() count
* check}.
*
* This count is exact if {@link #isExactTripCount()} returns true.
*
* THIS VALUE SHOULD BE TREATED AS UNSIGNED.
*
* Warning: In order to calculate the max trip count it can be necessary to perform a devision
* operation in the generated code before the loop header. If {@code stride is not a power of 2}
* we have to perform an integer division of the range of the induction variable and the stride.
*
* @param assumeLoopEntered if true the check that the loop is entered at all will be omitted.
*
*/
public ValueNode maxTripCountNode(boolean assumeLoopEntered, IntegerHelper integerHelper, ValueNode initNode, ValueNode tripCountLimit) {
assertNoOverflow();
StructuredGraph graph = getLimitCheckedIV().valueNode().graph();
Stamp stamp = getLimitCheckedIV().valueNode().stamp(NodeView.DEFAULT);
ValueNode max;
ValueNode min;
ValueNode absStride;
final InductionVariable.Direction direction = getLimitCheckedIV().direction();
if (direction == InductionVariable.Direction.Up) {
absStride = getLimitCheckedIV().strideNode();
max = tripCountLimit;
min = initNode;
} else {
assert direction == InductionVariable.Direction.Down : "direction must be down if its not up - else loop should not be counted " + direction;
absStride = NegateNode.create(getLimitCheckedIV().strideNode(), NodeView.DEFAULT);
max = initNode;
min = tripCountLimit;
}
ValueNode range = BinaryArithmeticNode.sub(max, min);
ConstantNode one = ConstantNode.forIntegerStamp(stamp, 1, graph);
if (isLimitIncluded) {
range = BinaryArithmeticNode.add(range, one);
}
// round-away-from-zero divison: (range + stride -/+ 1) / stride
ValueNode denominator = BinaryArithmeticNode.add(graph, range, BinaryArithmeticNode.sub(absStride, one), NodeView.DEFAULT);
/*
* While the divisor can never be zero because that would mean the direction of the loop is
* not strictly known which disables counted loop detection - it is possible that the stamp
* contains 0 though we know it effectively cannot. This happens when we have knowledge
* about the stride - for example its strictly positive or negative but not a constant - in
* both we cannot easily fold the negated stamp.
*
* Note that on certain architectures the division MIN/-1 also triggers a CPU divide error
* which has to be taken care of by the code generation via a state, thus actually deriving
* by stamps that this division can never trigger a divide error is very hard, and thus we
* refrain from doing so.
*/
final boolean divisorNonZero = true;
ValueNode div = MathUtil.unsignedDivBefore(graph, divisorNonZero, loop.entryPoint(), denominator, absStride, null);
if (assumeLoopEntered) {
return graph.addOrUniqueWithInputs(div);
}
ConstantNode zero = ConstantNode.forIntegerStamp(stamp, 0, graph);
// This check is "wide": it looks like min <= max
// That's OK even if the loop is strict (`!isLimitIncluded()`)
// because in this case, `div` will be zero when min == max
LogicNode noEntryCheck = graph.addOrUniqueWithInputs(integerHelper.createCompareNode(max, min, NodeView.DEFAULT));
ValueNode pi = findOrCreatePositivePi(noEntryCheck, div, graph, loop.loopsData().getCFG());
if (pi != null) {
return pi;
}
return graph.addOrUniqueWithInputs(ConditionalNode.create(noEntryCheck, zero, div, NodeView.DEFAULT));
}
/**
* Before creating a {@code ConditionalNode(noEntryCheck, zero, div)} node, check if the graph
* already contains a {@code !noEntryCheck} path dominating this loop, and build or reuse a
* {@link PiNode} there.
*
* @return a new or existing {@link PiNode} already added to the graph or {@code null}
*/
private ValueNode findOrCreatePositivePi(LogicNode noEntryCheck, ValueNode div, StructuredGraph graph, ControlFlowGraph cfg) {
Stamp positiveIntStamp = StampFactory.positiveInt();
if (!positiveIntStamp.isCompatible(div.stamp(NodeView.DEFAULT))) {
return null;
}
if (cfg.getNodeToBlock().isNew(loop.loopBegin())) {
return null;
}
HIRBlock loopBlock = cfg.blockFor(loop.loopBegin());
for (Node checkUsage : noEntryCheck.usages()) {
ValueNode candidateCheck = null;
if (checkUsage instanceof IfNode ifCheck) {
candidateCheck = ifCheck.falseSuccessor();
} else if (checkUsage instanceof FixedGuardNode guard) {
if (!guard.isNegated()) {
continue;
}
candidateCheck = guard;
} else {
continue;
}
if (cfg.getNodeToBlock().isNew(candidateCheck)) {
continue;
}
if (cfg.blockFor(candidateCheck).dominates(loopBlock)) {
return graph.addOrUniqueWithInputs(PiNode.create(div, positiveIntStamp.improveWith(div.stamp(NodeView.DEFAULT)), candidateCheck));
}
}
return null;
}
/**
* Determine if the loop might be entered. Returns {@code false} if we can tell statically that
* the loop cannot be entered; returns {@code true} if the loop might possibly be entered,
* including in the case where we cannot be sure statically.
*
* @return false if the loop can definitely not be entered, true otherwise
*/
public boolean loopMightBeEntered() {
Stamp stamp = getLimitCheckedIV().valueNode().stamp(NodeView.DEFAULT);
ValueNode max;
ValueNode min;
if (getLimitCheckedIV().direction() == InductionVariable.Direction.Up) {
max = getTripCountLimit();
// use the init of the body - if the limit checked IV is offset from the body by one
// iteration for entering the loop we want to know min max for the init of the body IV
min = getBodyIVStart();
} else {
assert getLimitCheckedIV().direction() == Direction.Down : Assertions.errorMessage(getLimitCheckedIV());
// use the init of the body - if the limit checked IV is offset from the body by one
// iteration for entering the loop we want to know min max for the init of the body IV
max = getBodyIVStart();
min = getTripCountLimit();
}
if (isLimitIncluded) {
// Ensure the constant is value numbered in the graph. Don't add other nodes to the
// graph, they will be dead code.
StructuredGraph graph = getLimitCheckedIV().valueNode().graph();
max = BinaryArithmeticNode.add(max, ConstantNode.forIntegerStamp(stamp, 1, graph), NodeView.DEFAULT);
}
LogicNode entryCheck = getCounterIntegerHelper().createCompareNode(min, max, NodeView.DEFAULT);
if (entryCheck.isContradiction()) {
// We can definitely not enter this loop.
return false;
} else {
// We don't know for sure that the loop can't be entered, so assume it can.
return true;
}
}
/**
* @return true if the loop has constant bounds.
*/
public boolean isConstantMaxTripCount() {
return getTripCountLimit() instanceof ConstantNode && getLimitCheckedIV().isConstantInit() && getLimitCheckedIV().isConstantStride();
}
public UnsignedLong constantMaxTripCount() {
assert isConstantMaxTripCount();
return new UnsignedLong(rawConstantMaxTripCount());
}
/**
* Compute the raw value of the trip count for this loop. THIS IS AN UNSIGNED VALUE;
*/
private long rawConstantMaxTripCount() {
assert getLimitCheckedIV().direction() != null;
long endValue = getTripCountLimit().asJavaConstant().asLong();
// use the init of the body - if the limit checked IV is offset from the body by one
// iteration we want to know min max for the init of the body IV
long initValue = getBodyIVStart().asJavaConstant().asLong();
long range;
long absStride;
IntegerHelper helper = getCounterIntegerHelper(64);
if (getLimitCheckedIV().direction() == InductionVariable.Direction.Up) {
if (helper.compare(endValue, initValue) < 0) {
return 0;
}
range = endValue - getLimitCheckedIV().constantInit();
absStride = getLimitCheckedIV().constantStride();
} else {
assert getLimitCheckedIV().direction() == Direction.Down : Assertions.errorMessage(getLimitCheckedIV());
if (helper.compare(initValue, endValue) < 0) {
return 0;
}
range = getLimitCheckedIV().constantInit() - endValue;
absStride = -getLimitCheckedIV().constantStride();
}
if (isLimitIncluded) {
range += 1;
}
long denominator = range + absStride - 1;
return Long.divideUnsigned(denominator, absStride);
}
public IntegerHelper getCounterIntegerHelper() {
IntegerStamp stamp = (IntegerStamp) getLimitCheckedIV().valueNode().stamp(NodeView.DEFAULT);
return getCounterIntegerHelper(stamp.getBits());
}
public IntegerHelper getCounterIntegerHelper(int bits) {
IntegerHelper helper;
if (isUnsignedCheck()) {
helper = new UnsignedIntegerHelper(bits);
} else {
helper = new SignedIntegerHelper(bits);
}
return helper;
}
public boolean isExactTripCount() {
return loop.getCFGLoop().getNaturalExits().size() == 1;
}
public ValueNode exactTripCountNode() {
assertNoOverflow();
assert isExactTripCount();
return maxTripCountNode();
}
public boolean isConstantExactTripCount() {
assert isExactTripCount();
return isConstantMaxTripCount();
}
public UnsignedLong constantExactTripCount() {
assertNoOverflow();
assert isExactTripCount();
return constantMaxTripCount();
}
@Override
public String toString() {
return (isInverted() ? "Inverted " : "") + "iv=" + getLimitCheckedIV() + " until " + getTripCountLimit() +
(isLimitIncluded ? getLimitCheckedIV().direction() == InductionVariable.Direction.Up ? "+1" : "-1" : "") +
" bodyIV=" + getLimitCheckedIV();
}
/**
* @return the {@link IfNode} that checks {@link CountedLoopInfo#getLimitCheckedIV()} against
* {@link CountedLoopInfo#getLimit()}.
*/
public IfNode getLimitTest() {
return ifNode;
}
/**
* @return the {@link InductionVariable#initNode()} of the loop's {@link #getBodyIV()}, i.e.,
* the start node of the IV used inside the loop body (which can be different than the
* IV checked in {@link #getLimitCheckedIV()}}.
*/
public ValueNode getBodyIVStart() {
return getBodyIV().initNode();
}
public boolean isLimitIncluded() {
return isLimitIncluded;
}
public AbstractBeginNode getBody() {
return body;
}
public AbstractBeginNode getCountedExit() {
if (getLimitTest().trueSuccessor() == getBody()) {
return getLimitTest().falseSuccessor();
} else {
assert getLimitTest().falseSuccessor() == getBody() : Assertions.errorMessage(this, getLimitTest(), getLimitTest().falseSuccessor(), getBody());
return getLimitTest().trueSuccessor();
}
}
public InductionVariable.Direction getDirection() {
return getLimitCheckedIV().direction();
}
public GuardingNode getOverFlowGuard() {
return loop.loopBegin().getOverflowGuard();
}
/**
* Determine if there are static properties or dynamic checks in place that guarantee that the
* {@link #getLimitCheckedIV()} never overflows.
*/
public boolean loopCanNeverOverflow() {
return counterNeverOverflows() || getOverFlowGuard() != null;
}
/**
* Determines with static analysis if the counter {@link #getLimitCheckedIV()} can ever
* overflow. If this method returns {@code true} it is statically known the limit checked
* induction variable never overflows. If this method returns {@code false} it is still possible
* that the limit checked IV never overflows but we have not been able to prove it statically.
*/
public boolean counterNeverOverflows() {
if (loop.loopBegin().canNeverOverflow()) {
return true;
}
return ivCanNeverOverflow(getLimitCheckedIV());
}
public boolean ivCanNeverOverflow(InductionVariable iv) {
if (iv != getLimitCheckedIV()) {
/*
* All non-limit checked IVs: This IV is not compared against limit and thus we cannot
* play the trick comparing against the end stamp. We have to compute (if possible) the
* extremum value and use that.
*/
if (iv.isConstantInit() && isConstantMaxTripCount() && iv.isConstantStride()) {
try {
final int bits = IntegerStamp.getBits(iv.valueNode().stamp(NodeView.DEFAULT));
final long signedTripCount = LoopUtility.tripCountSignedExact(this);
final long stripTimesTripCount = LoopUtility.multiplyExact(bits, iv.constantStride(), signedTripCount);
@SuppressWarnings("unused")
long extremum = LoopUtility.addExact(bits, stripTimesTripCount, iv.initNode().asJavaConstant().asLong());
return true;
} catch (ArithmeticException e) {
// overflow
return false;
}
}
return false;
}
// BELOW: limitCheckedIV case
if (!isLimitIncluded && iv.isConstantStride() && Loop.absStrideIsOne(iv)) {
return true;
}
if (loop.loopBegin().isProtectedNonOverflowingUnsigned()) {
return true;
}
// @formatter:off
/*
* Following comment reasons about the simplest possible loop form:
*
* for(i = 0;i < end;i += stride)
*
* The problem is we want to create an overflow guard for the loop that can be hoisted
* before the loop, i.e., the overflow guard must not have loop variant inputs else it must
* be scheduled inside the loop. This means we cannot refer explicitly to the induction
* variable's phi but must establish a relation between end, stride and max (max integer
* range for a given loop) that is sufficient for most cases.
*
* We know that a head counted loop with a stride > 1 may overflow if the stride is big
* enough that end + stride will be > MAX, i.e. it overflows into negative value range.
*
* It is important that "end" in this context is the checked value of the loop condition:
* i.e., an arbitrary value. There is no relation between end and MAX established except
* that based on the integer representation we know that end <= MAX.
*
* A loop can overflow if the last checked value of the iv allows an overflow in the next
* iteration: the value range for which an overflow can happen is [MAX-(stride-1),MAX] e.g.
*
* MAX=10, stride = 3, overflow if number > 10
* end = MAX -> 10 -> 10 + 3 = 13 -> overflow
* end = MAX-1 -> 9 -> 9 + 3 = 12 -> overflow
* end = MAX-2 -> 8 -> 8 + 3 = 11 -> overflow
* end = MAX-3 -> 7 -> 7 + 3 = 10 -> No overflow at MAX - stride
*
* Note that this guard is pessimistic, i.e., it marks loops as potentially overflowing that
* are actually not overflowing. Consider the following loop:
*
* <pre>
* for(i = MAX-56; i < MAX, i += 8)
* </pre>
*
* where i in last loop body visit = MAX - 8, i after = MAX, no overflow
*
* which is wrongly detected as overflowing since "end" is element of [MAX-(stride-1),MAX]
* which is [MAX-7,MAX] and end is MAX. We handle such cases with a speculation and disable
* counted loop detection on subsequent compilations. We can only avoid such false positive
* detections by actually computing the number of iterations with a division, however we try
* to avoid that since that may be part of the fast path.
*
* And additional backup strategy could be to actually emit the precise guard inside the
* loop if the deopt already failed, but we refrain from this for now for simplicity
* reasons.
*/
// @formatter:on
IntegerStamp endStamp = (IntegerStamp) getTripCountLimit().stamp(NodeView.DEFAULT);
ValueNode strideNode = getLimitCheckedIV().strideNode();
IntegerStamp strideStamp = (IntegerStamp) strideNode.stamp(NodeView.DEFAULT);
IntegerHelper integerHelper = getCounterIntegerHelper();
if (getDirection() == InductionVariable.Direction.Up) {
long max = integerHelper.maxValue();
return integerHelper.compare(endStamp.upperBound(), max - (strideStamp.upperBound() - 1) - (isLimitIncluded ? 1 : 0)) <= 0;
} else if (getDirection() == InductionVariable.Direction.Down) {
long min = integerHelper.minValue();
return integerHelper.compare(min + (1 - strideStamp.lowerBound()) + (isLimitIncluded ? 1 : 0), endStamp.lowerBound()) <= 0;
}
return false;
}
@SuppressWarnings("try")
public GuardingNode createOverFlowGuard() {
GuardingNode overflowGuard = getOverFlowGuard();
if (overflowGuard != null || counterNeverOverflows()) {
return overflowGuard;
}
try (DebugCloseable position = loop.loopBegin().withNodeSourcePosition()) {
StructuredGraph graph = getLimitCheckedIV().valueNode().graph();
LogicNode cond = createOverflowGuardCondition();
SpeculationLog speculationLog = graph.getSpeculationLog();
SpeculationLog.Speculation speculation = SpeculationLog.NO_SPECULATION;
if (speculationLog != null) {
SpeculationLog.SpeculationReason speculationReason = LoopBeginNode.LOOP_OVERFLOW_DEOPT.createSpeculationReason(graph.method(), getLimitCheckedIV().loop.loopBegin().stateAfter().bci);
if (speculationLog.maySpeculate(speculationReason)) {
speculation = speculationLog.speculate(speculationReason);
LoopBeginNode.overflowSpeculationTaken.increment(graph.getDebug());
} else {
GraalError.shouldNotReachHere("Must not create overflow guard for loop " + loop.loopBegin() + " where the speculation guard already failed, this can create deopt loops"); // ExcludeFromJacocoGeneratedReport
}
}
assert graph.getGuardsStage().allowsFloatingGuards();
overflowGuard = graph.unique(new GuardNode(cond, AbstractBeginNode.prevBegin(loop.entryPoint()), DeoptimizationReason.LoopLimitCheck, DeoptimizationAction.InvalidateRecompile, true,
speculation, null));
loop.loopBegin().setOverflowGuard(overflowGuard);
return overflowGuard;
}
}
/**
* Creates an overflow guard condition, that is the condition such that if it is satisfied, the
* induction variable will overflow, and we have to treat the loop as a non-counted one.
* <p>
* For example, given this loop:
* {@snippet :
* for (int i = 0; i < limit; i += 2) {
* }
* }
* Most of the time, this loop will execute a limited amount of iterations, and the value of
* {@code i} inside the loop body will be in the interval {@code [0, limit)}. However, in the
* rare cases that {@code limit == Integer.MAX_VALUE}, the addition {@code i += 2} will
* overflow, and the loop would not terminate. In those cases, We cannot treat the loop as a
* counted loop. As a result, we insert a guard for those circumstances. The guard is
* conservative, that is it will catch all cases where the calculation of the induction variable
* overflows, and it may catch cases where the calculation does not actually overflow. In the
* example, the guard would be:
* {@snippet :
* if (limit > Integer.MAX_VALUE - 1) {
* deoptimize();
* }
* }
* This method creates the aforementioned guard, it has the value {@code true} if the
* calculation may overflow, and {@code false} if it cannot, in such cases assumptions about
* counted loops hold.
*/
public LogicNode createOverflowGuardCondition() {
StructuredGraph graph = getLimitCheckedIV().valueNode().graph();
if (counterNeverOverflows()) {
return LogicConstantNode.contradiction(graph);
}
IntegerStamp stamp = (IntegerStamp) getLimitCheckedIV().valueNode().stamp(NodeView.DEFAULT);
IntegerHelper integerHelper = getCounterIntegerHelper();
LogicNode cond; // we use a negated guard with a < condition to achieve a >=
ConstantNode one = ConstantNode.forIntegerStamp(stamp, 1, graph);
if (getLimitCheckedIV().direction() == InductionVariable.Direction.Up) {
// overflow ~ (tripCountLimit + stride) overflow ~ tripCountLimit > maxValue - stride
ValueNode maxValue = ConstantNode.forIntegerStamp(stamp, integerHelper.maxValue(), graph);
ValueNode maxNonOverflowLimitValue = BinaryArithmeticNode.sub(graph, maxValue, getLimitCheckedIV().strideNode(), NodeView.DEFAULT);
if (!isLimitIncluded) {
maxNonOverflowLimitValue = BinaryArithmeticNode.add(graph, maxNonOverflowLimitValue, one, NodeView.DEFAULT);
}
cond = graph.addOrUniqueWithInputs(integerHelper.createCompareNode(maxNonOverflowLimitValue, getTripCountLimit(), NodeView.DEFAULT));
} else {
assert getLimitCheckedIV().direction() == Direction.Down : Assertions.errorMessage(getLimitCheckedIV());
// overflow ~ (tripCountLimit + stride) overflow ~ tripCountLimit < minValue - stride
ValueNode minValue = ConstantNode.forIntegerStamp(stamp, integerHelper.minValue(), graph);
ValueNode minNonOverflowLimitValue = BinaryArithmeticNode.sub(graph, minValue, getLimitCheckedIV().strideNode(), NodeView.DEFAULT);
if (!isLimitIncluded) {
minNonOverflowLimitValue = BinaryArithmeticNode.sub(graph, minNonOverflowLimitValue, one, NodeView.DEFAULT);
}
cond = graph.addOrUniqueWithInputs(integerHelper.createCompareNode(getTripCountLimit(), minNonOverflowLimitValue, NodeView.DEFAULT));
}
return cond;
}
public IntegerStamp getStamp() {
return (IntegerStamp) getLimitCheckedIV().valueNode().stamp(NodeView.DEFAULT);
}
public boolean isInverted() {
return false;
}
}
|
apache/derby | 34,544 | java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/CastNode.java | /*
Derby - Class org.apache.derby.impl.sql.compile.CastNode
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derby.impl.sql.compile;
import java.lang.reflect.Modifier;
import java.sql.Types;
import java.util.List;
import org.apache.derby.shared.common.error.StandardException;
import org.apache.derby.shared.common.reference.ClassName;
import org.apache.derby.shared.common.reference.Limits;
import org.apache.derby.shared.common.reference.SQLState;
import org.apache.derby.iapi.services.classfile.VMOpcode;
import org.apache.derby.iapi.services.compiler.LocalField;
import org.apache.derby.iapi.services.compiler.MethodBuilder;
import org.apache.derby.iapi.services.context.ContextManager;
import org.apache.derby.shared.common.sanity.SanityManager;
import org.apache.derby.iapi.sql.compile.TypeCompiler;
import org.apache.derby.iapi.sql.compile.Visitor;
import org.apache.derby.iapi.types.DataTypeDescriptor;
import org.apache.derby.iapi.types.DataTypeUtilities;
import org.apache.derby.iapi.types.DataValueDescriptor;
import org.apache.derby.iapi.types.NumberDataType;
import org.apache.derby.iapi.types.TypeId;
import org.apache.derby.iapi.util.JBitSet;
import org.apache.derby.iapi.util.StringUtil;
/**
* An CastNode represents a cast expression.
*
*/
class CastNode extends ValueNode
{
ValueNode castOperand;
private int targetCharType;
TypeId sourceCTI = null;
private boolean forDataTypeFunction = false;
/** The original, unbound descriptor for the target type, if it is a UDT. */
private DataTypeDescriptor targetUDT;
/** This variable gets set by the parser to indicate that this CAST node
* has been generated by the parser. This means that we should use the
* collation info of the current compilation schema for this node's
* collation setting. If this variable does not get set to true, then it
* means that this CAST node has been an internally generated node and we
* should not touch the collation info set for this CAST node because it
* has been already set correctly by the class that generated this CAST
* node. Collation info is part of the DataTypeDescriptor that's defined
* on the ValueNode (the super class of this CastNode class)
*/
private boolean externallyGeneratedCastNode = false;
/*
** Static array of valid casts. Dimentions
** produce a single boolean which indicates
** whether the case is possible or not.
*/
/**
* Method calls:
* Argument type has the same semantics as assignment:
* Section 9.2 (Store assignment). There, General Rule
* 2.b.v.2 says that the database should raise an exception
* if truncation occurs when stuffing a string value into a
* VARCHAR, so make sure CAST doesn't issue warning only.
*/
private boolean assignmentSemantics = false;
/**
* The name of the target type if it's a UDT. It is partly redundant, as
* the name can also be retrieved from the type descriptor. Additionally,
* it contains information about the location of the UDT name in the
* query text, which is useful if the query text needs to be rewritten.
* (Useful for example when rewriting a CHECK constraint definition to
* have fully qualified names before storing it in the dictionary.) This
* field is only set for <b>explicit</b> casts to a UDT.
*/
private TableName udtTargetName;
/**
* Constructor for a CastNode
*
* @param castOperand The operand of the node
* @param castTarget DataTypeServices (target type of cast)
* @param cm The context manager
*
* @exception StandardException Thrown on error
*/
CastNode(ValueNode castOperand,
DataTypeDescriptor castTarget,
ContextManager cm) throws StandardException {
super(cm);
this.castOperand = castOperand;
// DERBY-6421: setType() tries to bind user defined types. We don't
// want to do any binding here, since we could be called during
// parsing. If the target type is a UDT, just store it for now and
// do the binding later when bindExpression() or bindCastNodeOnly()
// is called.
if (castTarget.getTypeId().isUserDefinedTypeId()) {
targetUDT = castTarget;
} else {
setType(castTarget);
}
}
/**
* Constructor for a CastNode
*
* @param castOperand The operand of the node
* @param charType CHAR or VARCHAR JDBC type as target
* @param charLength target type length
* @param cm The context manager
*
* @exception StandardException Thrown on error
*/
CastNode(ValueNode castOperand,
int charType,
int charLength,
ContextManager cm) throws StandardException {
super(cm);
this.castOperand = castOperand;
int charLen = charLength;
targetCharType = charType;
if (charLen < 0) // unknown, figure out later
return;
setType(DataTypeDescriptor.getBuiltInDataTypeDescriptor(targetCharType, charLen));
}
/**
* Convert this object to a String. See comments in QueryTreeNode.java
* for how this should be done for tree printing.
*
* @return This object as a String
*/
@Override
public String toString()
{
if (SanityManager.DEBUG)
{
return "castTarget: " + getTypeServices() + "\n" +
super.toString();
}
else
{
return "";
}
}
/**
* Prints the sub-nodes of this object. See QueryTreeNode.java for
* how tree printing is supposed to work.
*
* @param depth The depth of this node in the tree
*/
@Override
void printSubNodes(int depth)
{
if (SanityManager.DEBUG)
{
super.printSubNodes(depth);
if (castOperand != null)
{
printLabel(depth, "castOperand: ");
castOperand.treePrint(depth + 1);
}
}
}
protected int getOrderableVariantType() throws StandardException
{
return castOperand.getOrderableVariantType();
}
/**
* Bind this expression. This means binding the sub-expressions,
* as well as figuring out what the return type is for this expression.
*
* @param fromList The FROM list for the query this
* expression is in, for binding columns.
* @param subqueryList The subquery list being built as we find SubqueryNodes
* @param aggregates The aggregate list being built as we find AggregateNodes
*
* @return The new top of the expression tree.
*
* @exception StandardException Thrown on error
*/
@Override @SuppressWarnings("fallthrough")
ValueNode bindExpression(FromList fromList, SubqueryList subqueryList, List<AggregateNode> aggregates)
throws StandardException
{
castOperand = castOperand.bindExpression(
fromList, subqueryList,
aggregates);
// Bind the target UDT.
if (targetUDT != null) {
setType(targetUDT);
}
if (getTypeServices() == null) //CHAR or VARCHAR function without specifying target length
{
DataTypeDescriptor opndType = castOperand.getTypeServices();
int length = -1;
TypeId srcTypeId = opndType.getTypeId();
if (srcTypeId.isNumericTypeId())
{
length = opndType.getPrecision() + 1; // 1 for the sign
if (opndType.getScale() > 0)
length += 1; // 1 for the decimal .
}
/*
* Derby-1132 : The length for the target type was calculated
* incorrectly while Char & Varchar functions were used. Thus
* adding the check for Char & Varchar and calculating the
* length based on the operand type.
*/
else if(srcTypeId.isStringTypeId())
{
length = opndType.getMaximumWidth();
// Truncate the target type width to the max width of the
// data type
if (this.targetCharType == Types.CHAR)
length = Math.min(length, Limits.DB2_CHAR_MAXWIDTH);
else if (this.targetCharType == Types.VARCHAR)
length = Math.min(length, Limits.DB2_VARCHAR_MAXWIDTH);
}
else
{
TypeId typeid = opndType.getTypeId();
if (length < 0) {
length = DataTypeUtilities.getColumnDisplaySize(
typeid.getJDBCTypeId(), -1);
}
}
if (length < 0)
length = 1; // same default as in parser
setType(DataTypeDescriptor.getBuiltInDataTypeDescriptor(targetCharType, length));
}
/*
** If castOperand is an untyped null,
** then we must set the type.
*/
if (castOperand instanceof UntypedNullConstantNode)
{
castOperand.setType(getTypeServices());
}
bindCastNodeOnly();
/* We can't chop out cast above an untyped null because
* the store can't handle it.
*/
if ((castOperand instanceof ConstantNode) &&
!(castOperand instanceof UntypedNullConstantNode))
{
/* If the castOperand is a typed constant then we do the cast at
* bind time and return a constant of the correct type.
* NOTE: This could return an exception, but we're prepared to
* deal with that. (NumberFormatException, etc.)
* We only worry about the easy (and useful)
* converions at bind time.
* Here's what we support:
* source destination
* ------ -----------
* boolean boolean
* boolean char
* char boolean
* char date/time/ts
* char non-decimal numeric
* date/time/ts char
* numeric char
* numeric non-decimal numeric
*/
/* RESOLVE - to be filled in. */
ValueNode retNode = this;
int sourceJDBCTypeId = sourceCTI.getJDBCTypeId();
int destJDBCTypeId = getTypeId().getJDBCTypeId();
switch (sourceJDBCTypeId)
{
case Types.BIT:
case Types.BOOLEAN:
// (BIT is boolean)
if (destJDBCTypeId == Types.BIT || destJDBCTypeId == Types.BOOLEAN)
{
retNode = castOperand;
}
else if (destJDBCTypeId == Types.CHAR)
{
BooleanConstantNode bcn = (BooleanConstantNode) castOperand;
String booleanString = bcn.getValueAsString();
retNode = new CharConstantNode(
booleanString,
getTypeServices().getMaximumWidth(),
getContextManager());
}
break;
case Types.CHAR:
retNode = getCastFromCharConstant(destJDBCTypeId);
break;
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
if (destJDBCTypeId == Types.CHAR)
{
String castValue =
((UserTypeConstantNode) castOperand).
getObjectValue().
toString();
retNode = new CharConstantNode(
castValue,
getTypeServices().getMaximumWidth(),
getContextManager());
}
break;
case Types.DECIMAL:
// ignore decimal -> decimal casts for now
if (destJDBCTypeId == Types.DECIMAL ||
destJDBCTypeId == Types.NUMERIC)
break;
// fall through
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
case Types.BIGINT:
case Types.DOUBLE:
case Types.REAL:
retNode = getCastFromNumericType(
((ConstantNode) castOperand).getValue(),
destJDBCTypeId);
break;
}
// Return the new constant if the cast was performed
return retNode;
}
return this;
}
/**
* Bind this node but not its child. Caller has already bound
* the child.
* This is useful for when we generate a CastNode during binding
* after having already bound the child.
*
* @exception StandardException Thrown on error
*/
void bindCastNodeOnly()
throws StandardException
{
// Bind the target UDT.
if (targetUDT != null) {
setType(targetUDT);
}
/*
** The result type is always castTarget.
*/
sourceCTI = castOperand.getTypeId();
//If the result type of cast is string data type, then that data type
//should get it's collation type from the current schema.
if (externallyGeneratedCastNode && getTypeId().isStringTypeId()) {
//set the collation type to be same as the compilation schema's
//collation type. Collation derivation will be set to "IMPLICIT".
setCollationUsingCompilationSchema();
}
/*
** If it is a java cast, do some work to make sure
** the classes are ok and that they are compatible
*/
if (getTypeId().userType())
{
setType( bindUserType( getTypeServices() ) );
String className = getTypeId().getCorrespondingJavaTypeName();
verifyClassExist(className);
}
// Set the schema name of the UDT target type.
if (udtTargetName != null) {
udtTargetName.setSchemaName(
getTypeId().getBaseTypeId().getSchemaName());
}
// Obviously the type of a parameter that
// requires its type from context (a parameter)
// gets its type from the type of the CAST.
if (castOperand.requiresTypeFromContext())
{
castOperand.setType(getTypeServices());
}
/*
** If it isn't null, then we have
** a cast from one JBMS type to another. So we
** have to figure out if it is legit.
*/
else if (!(castOperand instanceof UntypedNullConstantNode))
{
/*
** Make sure we can assign the two classes
*/
TypeCompiler tc = castOperand.getTypeCompiler();
if (! tc.convertible(getTypeId(), forDataTypeFunction))
{
throw StandardException.newException(SQLState.LANG_INVALID_CAST,
sourceCTI.getSQLTypeName(),
getTypeId().getSQLTypeName());
}
}
//
// Preserve the nullability of the operand since a CAST
// of a non-NULL value is also non-NULL. However, if the source type is
// a non-nullable string type and the target type is a boolean, then the result
// still must be nullable because the string "unknown" casts to boolean NULL.
//
if (
castOperand.getTypeServices().getTypeId().isStringTypeId() &&
getTypeId().isBooleanTypeId()
)
{ setNullability( true ); }
else { setNullability(castOperand.getTypeServices().isNullable()); }
if (targetUDT != null)
{
addUDTUsagePriv( this );
}
}
/**
* Get a constant representing the cast from a CHAR to another
* type. If this is not an "easy" cast to perform, then just
* return this cast node.
* Here's what we think is "easy":
* source destination
* ------ -----------
* char boolean
* char date/time/ts
* char non-decimal numeric
*
* @param destJDBCTypeId The destination JDBC TypeId
*
* @return The new top of the tree (this CastNode or a new Constant)
*
* @exception StandardException Thrown on error
*/
private ValueNode getCastFromCharConstant(int destJDBCTypeId)
throws StandardException
{
String charValue = ((CharConstantNode) castOperand).getString();
String cleanCharValue = StringUtil.SQLToUpperCase(charValue.trim());
ValueNode retNode = this;
switch (destJDBCTypeId)
{
case Types.BIT:
case Types.BOOLEAN:
if (cleanCharValue.equals("TRUE"))
{
return new BooleanConstantNode(true, getContextManager());
}
else if (cleanCharValue.equals("FALSE"))
{
return new BooleanConstantNode(false, getContextManager());
}
else if (cleanCharValue.equals("UNKNOWN"))
{
return new BooleanConstantNode(getContextManager());
}
else
{
throw StandardException.newException(SQLState.LANG_FORMAT_EXCEPTION, "boolean");
}
case Types.DATE:
return new UserTypeConstantNode(
getDataValueFactory().getDateValue(cleanCharValue, false),
getContextManager());
case Types.TIMESTAMP:
return new UserTypeConstantNode(
getDataValueFactory().getTimestampValue(cleanCharValue, false),
getContextManager());
case Types.TIME:
return new UserTypeConstantNode(
getDataValueFactory().getTimeValue(cleanCharValue, false),
getContextManager());
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
case Types.BIGINT:
try
{
// #3756 - Truncate decimal portion for casts to integer
return getCastFromIntegralType((long) Double.parseDouble(cleanCharValue),
destJDBCTypeId);
}
catch (NumberFormatException nfe)
{
String sqlName = TypeId.getBuiltInTypeId(destJDBCTypeId).getSQLTypeName();
throw StandardException.newException(SQLState.LANG_FORMAT_EXCEPTION, sqlName);
}
case Types.REAL:
Float floatValue;
try
{
floatValue = Float.valueOf(cleanCharValue);
}
catch (NumberFormatException nfe)
{
throw StandardException.newException(SQLState.LANG_FORMAT_EXCEPTION, "float");
}
return new NumericConstantNode(
TypeId.getBuiltInTypeId(Types.REAL),
floatValue,
getContextManager());
case Types.DOUBLE:
Double doubleValue;
try
{
doubleValue = Double.parseDouble(cleanCharValue);
}
catch (NumberFormatException nfe)
{
throw StandardException.newException(SQLState.LANG_FORMAT_EXCEPTION, "double");
}
return new NumericConstantNode(
TypeId.getBuiltInTypeId(Types.DOUBLE),
doubleValue,
getContextManager());
}
return retNode;
}
/**
* Get a constant representing the cast from an integral type to another
* type. If this is not an "easy" cast to perform, then just
* return this cast node.
* Here's what we think is "easy":
* source destination
* ------ -----------
* integral type non-decimal numeric
* integral type char
*
* @param longValue integral type as a long to cast from
* @param destJDBCTypeId The destination JDBC TypeId
*
* @return The new top of the tree (this CastNode or a new Constant)
*
* @exception StandardException Thrown on error
*/
private ValueNode getCastFromIntegralType(
long longValue,
int destJDBCTypeId)
throws StandardException
{
ValueNode retNode = this;
switch (destJDBCTypeId)
{
case Types.CHAR:
return new CharConstantNode(
Long.toString(longValue),
getTypeServices().getMaximumWidth(),
getContextManager());
case Types.TINYINT:
if (longValue < Byte.MIN_VALUE ||
longValue > Byte.MAX_VALUE)
{
throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "TINYINT");
}
return new NumericConstantNode(
TypeId.getBuiltInTypeId(Types.TINYINT),
(byte) longValue,
getContextManager());
case Types.SMALLINT:
if (longValue < Short.MIN_VALUE ||
longValue > Short.MAX_VALUE)
{
throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "SHORT");
}
return new NumericConstantNode(
TypeId.getBuiltInTypeId(destJDBCTypeId),
(short) longValue,
getContextManager());
case Types.INTEGER:
if (longValue < Integer.MIN_VALUE ||
longValue > Integer.MAX_VALUE)
{
throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "INTEGER");
}
return new NumericConstantNode(
TypeId.getBuiltInTypeId(destJDBCTypeId),
(int) longValue,
getContextManager());
case Types.BIGINT:
return new NumericConstantNode(
TypeId.getBuiltInTypeId(destJDBCTypeId),
longValue,
getContextManager());
case Types.REAL:
if (Math.abs(longValue) > Float.MAX_VALUE)
{
throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "REAL");
}
return new NumericConstantNode(
TypeId.getBuiltInTypeId(destJDBCTypeId),
(float) longValue,
getContextManager());
case Types.DOUBLE:
return new NumericConstantNode(
TypeId.getBuiltInTypeId(destJDBCTypeId),
(double) longValue,
getContextManager());
}
return retNode;
}
/**
* Get a constant representing the cast from a non-integral type to another
* type. If this is not an "easy" cast to perform, then just
* return this cast node.
* Here's what we think is "easy":
* source destination
* ------ -----------
* non-integral type non-decimal numeric
* non-integral type char
*
* @param constantValue non-integral type a a double to cast from
* @param destJDBCTypeId The destination JDBC TypeId
*
* @return The new top of the tree (this CastNode or a new Constant)
*
* @exception StandardException Thrown on error
*/
private ValueNode getCastFromNumericType(
DataValueDescriptor constantValue,
int destJDBCTypeId)
throws StandardException
{
switch (destJDBCTypeId)
{
case Types.CHAR:
return new CharConstantNode(
constantValue.getString(),
getTypeServices().getMaximumWidth(),
getContextManager());
case Types.TINYINT:
return new NumericConstantNode(
TypeId.getBuiltInTypeId(destJDBCTypeId),
Byte.valueOf(constantValue.getByte()),
getContextManager());
case Types.SMALLINT:
return new NumericConstantNode(
TypeId.getBuiltInTypeId(destJDBCTypeId),
Short.valueOf(constantValue.getShort()),
getContextManager());
case Types.INTEGER:
return new NumericConstantNode(
TypeId.getBuiltInTypeId(destJDBCTypeId),
Integer.valueOf(constantValue.getInt()),
getContextManager());
case Types.BIGINT:
return new NumericConstantNode(
TypeId.getBuiltInTypeId(destJDBCTypeId),
Long.valueOf(constantValue.getLong()),
getContextManager());
case Types.REAL:
return new NumericConstantNode(
TypeId.getBuiltInTypeId(destJDBCTypeId),
Float.valueOf(NumberDataType.normalizeREAL(
constantValue.getDouble())),
getContextManager());
case Types.DOUBLE:
// no need to normalize here because no constant could be out of range for a double
return new NumericConstantNode(
TypeId.getBuiltInTypeId(destJDBCTypeId),
Double.valueOf(constantValue.getDouble()),
getContextManager());
}
return this;
}
/**
* Preprocess an expression tree. We do a number of transformations
* here (including subqueries, IN lists, LIKE and BETWEEN) plus
* subquery flattening.
* NOTE: This is done before the outer ResultSetNode is preprocessed.
*
* @param numTables Number of tables in the DML Statement
* @param outerFromList FromList from outer query block
* @param outerSubqueryList SubqueryList from outer query block
* @param outerPredicateList PredicateList from outer query block
*
* @return The modified expression
*
* @exception StandardException Thrown on error
*/
@Override
ValueNode preprocess(int numTables,
FromList outerFromList,
SubqueryList outerSubqueryList,
PredicateList outerPredicateList)
throws StandardException
{
castOperand = castOperand.preprocess(numTables,
outerFromList, outerSubqueryList,
outerPredicateList);
return this;
}
/**
* Categorize this predicate. Initially, this means
* building a bit map of the referenced tables for each predicate.
* If the source of this ColumnReference (at the next underlying level)
* is not a ColumnReference or a VirtualColumnNode then this predicate
* will not be pushed down.
*
* For example, in:
* select * from (select 1 from s) a (x) where x = 1
* we will not push down x = 1.
* NOTE: It would be easy to handle the case of a constant, but if the
* inner SELECT returns an arbitrary expression, then we would have to copy
* that tree into the pushed predicate, and that tree could contain
* subqueries and method calls.
* RESOLVE - revisit this issue once we have views.
*
* @param referencedTabs JBitSet with bit map of referenced FromTables
* @param simplePredsOnly Whether or not to consider method
* calls, field references and conditional nodes
* when building bit map
*
* @return boolean Whether or not source.expression is a ColumnReference
* or a VirtualColumnNode.
*
* @exception StandardException Thrown on error
*/
@Override
boolean categorize(JBitSet referencedTabs, boolean simplePredsOnly)
throws StandardException
{
return castOperand.categorize(referencedTabs, simplePredsOnly);
}
/**
* Remap all ColumnReferences in this tree to be clones of the
* underlying expression.
*
* @return ValueNode The remapped expression tree.
*
* @exception StandardException Thrown on error
*/
@Override
ValueNode remapColumnReferencesToExpressions()
throws StandardException
{
castOperand = castOperand.remapColumnReferencesToExpressions();
return this;
}
/**
* Return whether or not this expression tree represents a constant expression.
*
* @return Whether or not this expression tree represents a constant expression.
*/
@Override
boolean isConstantExpression()
{
return castOperand.isConstantExpression();
}
/** @see ValueNode#constantExpression */
@Override
boolean constantExpression(PredicateList whereClause)
{
return castOperand.constantExpression(whereClause);
}
/**
* Return an Object representing the bind time value of this
* expression tree. If the expression tree does not evaluate to
* a constant at bind time then we return null.
* This is useful for bind time resolution of VTIs.
* RESOLVE: What do we do for primitives?
*
* @return An Object representing the bind time value of this expression tree.
* (null if not a bind time constant.)
*
* @exception StandardException Thrown on error
*/
@Override
Object getConstantValueAsObject()
throws StandardException
{
Object sourceObject = castOperand.getConstantValueAsObject();
// RESOLVE - need to figure out how to handle casts
if (sourceObject == null)
{
return null;
}
// Simple if source and destination are of same type
if (sourceCTI.getCorrespondingJavaTypeName().equals(
getTypeId().getCorrespondingJavaTypeName()))
{
return sourceObject;
}
// RESOLVE - simply return null until we can figure out how to
// do the cast
return null;
}
/**
* Do code generation for this unary operator.
*
* @param acb The ExpressionClassBuilder for the class we're generating
* @param mb The method the code to place the code
*
* @exception StandardException Thrown on error
*/
@Override
void generateExpression(ExpressionClassBuilder acb, MethodBuilder mb)
throws StandardException
{
castOperand.generateExpression(acb, mb);
/* No need to generate code for null constants */
if (castOperand instanceof UntypedNullConstantNode)
{
return;
}
/* HACK ALERT. When casting a parameter, there
* is not sourceCTI. Code generation requires one,
* so we simply set it to be the same as the
* destCTI. The user can still pass whatever
* type they'd like in as a parameter.
* They'll get an exception, as expected, if the
* conversion cannot be performed.
*/
else if (castOperand.requiresTypeFromContext())
{
sourceCTI = getTypeId();
}
genDataValueConversion(acb, mb);
}
private void genDataValueConversion(ExpressionClassBuilder acb,
MethodBuilder mb)
throws StandardException
{
MethodBuilder acbConstructor = acb.getConstructor();
String resultTypeName = getTypeCompiler().interfaceName();
/* field = method call */
/* Allocate an object for re-use to hold the result of the operator */
LocalField field = acb.newFieldDeclaration(Modifier.PRIVATE, resultTypeName);
/*
** Store the result of the method call in the field, so we can re-use
** the object.
*/
acb.generateNull(acbConstructor, getTypeCompiler(getTypeId()),
getTypeServices().getCollationType());
acbConstructor.setField(field);
/*
For most types generate
targetDVD.setValue(sourceDVD);
For source or destination java types generate
Object o = sourceDVD.getObject();
targetDVD.setObjectForCast(o, o instanceof dest java type, dest java type);
// optional for variable length types
targetDVD.setWidth();
*/
if (!sourceCTI.userType() && !getTypeId().userType()) {
mb.getField(field); // targetDVD reference for the setValue method call
mb.swap();
mb.upCast(ClassName.DataValueDescriptor);
mb.callMethod(VMOpcode.INVOKEINTERFACE, ClassName.DataValueDescriptor,
"setValue", "void", 1);
}
else
{
/*
** generate: expr.getObject()
*/
mb.callMethod(VMOpcode.INVOKEINTERFACE, ClassName.DataValueDescriptor,
"getObject", "java.lang.Object", 0);
//castExpr
mb.getField(field); // instance for the setValue/setObjectForCast method call
mb.swap(); // push it before the value
/*
** We are casting a java type, generate:
**
** DataValueDescriptor.setObjectForCast(java.lang.Object castExpr, boolean instanceOfExpr, destinationClassName)
** where instanceOfExpr is "source instanceof destinationClass".
**
*/
String destinationType = getTypeId().getCorrespondingJavaTypeName();
// at this point method instance and cast result are on the stack
// we duplicate the cast value in order to perform the instanceof check
mb.dup();
mb.isInstanceOf(destinationType);
mb.push(destinationType);
mb.callMethod(VMOpcode.INVOKEINTERFACE, ClassName.DataValueDescriptor,
"setObjectForCast", "void", 3);
}
mb.getField(field);
/*
** If we are casting to a variable length datatype, we
** have to make sure we have set it to the correct
** length.
*/
if (getTypeId().variableLength())
{
boolean isNumber = getTypeId().isNumericTypeId();
// to leave the DataValueDescriptor value on the stack, since setWidth is void
mb.dup();
/* setWidth() is on VSDV - upcast since
* decimal implements subinterface
* of VSDV.
*/
mb.push(isNumber ? getTypeServices().getPrecision() : getTypeServices().getMaximumWidth());
mb.push(getTypeServices().getScale());
mb.push(!sourceCTI.variableLength() ||
isNumber ||
assignmentSemantics);
mb.callMethod(VMOpcode.INVOKEINTERFACE, ClassName.VariableSizeDataValue,
"setWidth", "void", 3);
}
}
/**
* Accept the visitor for all visitable children of this node.
*
* @param v the visitor
*
* @exception StandardException on error
*/
@Override
void acceptChildren(Visitor v)
throws StandardException
{
super.acceptChildren(v);
if (castOperand != null)
{
castOperand = (ValueNode)castOperand.accept(v);
}
if (udtTargetName != null)
{
udtTargetName = (TableName) udtTargetName.accept(v);
}
}
/** This method gets called by the parser to indiciate that this CAST node
* has been generated by the parser. This means that we should use the
* collation info of the current compilation schmea for this node's
* collation setting. If this method does not get called, then it means
* that this CAST node has been an internally generated node and we should
* not touch the collation of this CAST node because it has been already
* set correctly by the class that generated this CAST node.
*/
void setForExternallyGeneratedCASTnode()
{
externallyGeneratedCastNode = true;
}
/** set this to be a dataTypeScalarFunction
*
* @param b true to use function conversion rules
*/
void setForDataTypeFunction(boolean b)
{
forDataTypeFunction = b;
}
/**
* Set assignmentSemantics to true. Used by method calls for casting actual
* arguments
*/
void setAssignmentSemantics()
{
assignmentSemantics = true;
}
/**
* {@inheritDoc}
* @throws StandardException
*/
boolean isEquivalent(ValueNode o) throws StandardException
{
if (isSameNodeKind(o)) {
CastNode other = (CastNode)o;
return getTypeServices().equals(other.getTypeServices())
&& castOperand.isEquivalent(other.castOperand);
}
return false;
}
/**
* Set the target type name if this is a cast to a UDT.
* @param name the name of the target type
*/
void setTargetUDTName(TableName name) {
udtTargetName = name;
}
}
|
oracle/graal | 36,835 | compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/phases/common/FixReadsPhase.java | /*
* Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.graal.compiler.phases.common;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.ListIterator;
import java.util.Optional;
import org.graalvm.collections.EconomicMap;
import org.graalvm.collections.Equivalence;
import org.graalvm.collections.MapCursor;
import jdk.graal.compiler.core.common.GraalOptions;
import jdk.graal.compiler.core.common.cfg.BlockMap;
import jdk.graal.compiler.core.common.type.FloatStamp;
import jdk.graal.compiler.core.common.type.Stamp;
import jdk.graal.compiler.core.common.type.StampFactory;
import jdk.graal.compiler.debug.Assertions;
import jdk.graal.compiler.debug.CounterKey;
import jdk.graal.compiler.debug.DebugContext;
import jdk.graal.compiler.graph.Graph;
import jdk.graal.compiler.graph.Node;
import jdk.graal.compiler.graph.NodeBitMap;
import jdk.graal.compiler.graph.NodeMap;
import jdk.graal.compiler.graph.NodeStack;
import jdk.graal.compiler.graph.Position;
import jdk.graal.compiler.graph.iterators.NodePredicate;
import jdk.graal.compiler.nodeinfo.InputType;
import jdk.graal.compiler.nodes.AbstractBeginNode;
import jdk.graal.compiler.nodes.AbstractMergeNode;
import jdk.graal.compiler.nodes.BinaryOpLogicNode;
import jdk.graal.compiler.nodes.ConstantNode;
import jdk.graal.compiler.nodes.EndNode;
import jdk.graal.compiler.nodes.FixedNode;
import jdk.graal.compiler.nodes.FloatingGuardedNode;
import jdk.graal.compiler.nodes.GraphState;
import jdk.graal.compiler.nodes.GraphState.StageFlag;
import jdk.graal.compiler.nodes.IfNode;
import jdk.graal.compiler.nodes.LogicConstantNode;
import jdk.graal.compiler.nodes.LogicNode;
import jdk.graal.compiler.nodes.MergeNode;
import jdk.graal.compiler.nodes.NodeView;
import jdk.graal.compiler.nodes.PhiNode;
import jdk.graal.compiler.nodes.PiNode;
import jdk.graal.compiler.nodes.StructuredGraph;
import jdk.graal.compiler.nodes.StructuredGraph.ScheduleResult;
import jdk.graal.compiler.nodes.UnaryOpLogicNode;
import jdk.graal.compiler.nodes.ValueNode;
import jdk.graal.compiler.nodes.ValueNodeInterface;
import jdk.graal.compiler.nodes.ValuePhiNode;
import jdk.graal.compiler.nodes.calc.BinaryNode;
import jdk.graal.compiler.nodes.calc.ConditionalNode;
import jdk.graal.compiler.nodes.calc.UnaryNode;
import jdk.graal.compiler.nodes.cfg.ControlFlowGraph;
import jdk.graal.compiler.nodes.cfg.ControlFlowGraph.RecursiveVisitor;
import jdk.graal.compiler.nodes.cfg.HIRBlock;
import jdk.graal.compiler.nodes.extended.GuardingNode;
import jdk.graal.compiler.nodes.extended.IntegerSwitchNode;
import jdk.graal.compiler.nodes.extended.MultiGuardNode;
import jdk.graal.compiler.nodes.extended.SwitchNode;
import jdk.graal.compiler.nodes.memory.FixedAccessNode;
import jdk.graal.compiler.nodes.memory.FloatingAccessNode;
import jdk.graal.compiler.nodes.memory.FloatingReadNode;
import jdk.graal.compiler.nodes.memory.MemoryAccess;
import jdk.graal.compiler.nodes.memory.MemoryPhiNode;
import jdk.graal.compiler.nodes.spi.CanonicalizerTool;
import jdk.graal.compiler.nodes.spi.CoreProviders;
import jdk.graal.compiler.nodes.spi.CoreProvidersDelegate;
import jdk.graal.compiler.nodes.util.GraphUtil;
import jdk.graal.compiler.options.OptionValues;
import jdk.graal.compiler.phases.BasePhase;
import jdk.graal.compiler.phases.graph.ScheduledNodeIterator;
import jdk.graal.compiler.phases.util.Providers;
import jdk.vm.ci.meta.Assumptions;
import jdk.vm.ci.meta.Constant;
import jdk.vm.ci.meta.MetaAccessProvider;
import jdk.vm.ci.meta.TriState;
/**
* This phase lowers {@link FloatingReadNode FloatingReadNodes} into corresponding fixed reads.
* After this operation, there are no longer any nodes in the graph that have to remain below a
* control flow split to be considered "safe". Therefore, this phase subsequently removes all
* {@link PiNode} instances from the graph. Then it runs a raw conditional elimination
* {@link RawConditionalEliminationVisitor} that aggressively uses stamps for values based on
* control flow. For every if node, the logic node is inspected and a stamp is derived for the true
* and false branch. Stamps for a value are combined based on all previous knowledge about that
* value. For merge points, a union of the stamps of a value is constructed. When a value is used,
* the corresponding best derived stamp is provided to the canonicalizer.
*/
public class FixReadsPhase extends BasePhase<CoreProviders> {
private static final CounterKey counterStampsRegistered = DebugContext.counter("FixReads_StampsRegistered");
private static final CounterKey counterBetterMergedStamps = DebugContext.counter("FixReads_BetterMergedStamp");
protected final boolean replaceInputsWithConstants;
protected final BasePhase<? super CoreProviders> schedulePhase;
@Override
public float codeSizeIncrease() {
return 2.0f;
}
private static class FixReadsClosure extends ScheduledNodeIterator {
/**
* Bitmap that is used to schedule nodes for inferring a new stamp when they are visited.
* After removing the pi nodes from the graph, the stamp information injected by the pi
* nodes is cleared this way.
*/
private final NodeBitMap inferStampBitmap;
FixReadsClosure(StructuredGraph graph, ScheduleResult schedule) {
super(schedule);
inferStampBitmap = graph.createNodeBitMap();
}
@Override
protected void processNode(Node node, HIRBlock block, ListIterator<Node> iter) {
if (inferStampBitmap.isMarked(node) && node instanceof ValueNode) {
ValueNode valueNode = (ValueNode) node;
if (valueNode.inferStamp()) {
for (Node n : valueNode.usages()) {
inferStampBitmap.mark(n);
}
}
}
if (node instanceof AbstractMergeNode) {
AbstractMergeNode mergeNode = (AbstractMergeNode) node;
for (MemoryPhiNode memoryPhi : mergeNode.memoryPhis().snapshot()) {
// Memory phi nodes are no longer necessary at this point.
memoryPhi.replaceAtUsages(null);
memoryPhi.safeDelete();
}
} else if (node instanceof FloatingAccessNode) {
FloatingAccessNode floatingAccessNode = (FloatingAccessNode) node;
floatingAccessNode.setLastLocationAccess(null);
GuardingNode guard = floatingAccessNode.getGuard();
if (guard != null) {
floatingAccessNode.setGuard(null);
GraphUtil.tryKillUnused(guard.asNode());
}
FixedAccessNode fixedAccess = floatingAccessNode.asFixedNode();
replaceCurrent(fixedAccess);
} else if (node instanceof PiNode piNode) {
// incompatible stamps can result from unreachable code with empty stamps missed by
// control flow optimizations
if (piNode.stamp(NodeView.DEFAULT).isCompatible(piNode.getOriginalNode().stamp(NodeView.DEFAULT))) {
// Pi nodes are no longer necessary at this point. Make sure to infer stamps
// for all usages to clear out the stamp information added by the pi node.
for (Node n : piNode.usages()) {
inferStampBitmap.mark(n);
}
piNode.replaceAndDelete(piNode.getOriginalNode());
}
} else if (node instanceof MemoryAccess) {
MemoryAccess memoryAccess = (MemoryAccess) node;
memoryAccess.setLastLocationAccess(null);
}
}
}
public static class RawConditionalEliminationVisitor implements RecursiveVisitor<Integer> {
protected final NodeMap<StampElement> stampMap;
protected final NodeStack undoOperations;
private final ScheduleResult schedule;
private final StructuredGraph graph;
private final MetaAccessProvider metaAccess;
private final boolean replaceConstantInputs;
private final BlockMap<Integer> blockActionStart;
private final EconomicMap<MergeNode, EconomicMap<ValueNode, Stamp>> endMaps;
private final DebugContext debug;
private final RawCanonicalizerTool rawCanonicalizerTool;
private final EconomicMap<Node, HIRBlock> nodeToBlockMap;
protected EconomicMap<AbstractBeginNode, Stamp> successorStampCache;
private class RawCanonicalizerTool extends CoreProvidersDelegate implements NodeView, CanonicalizerTool {
RawCanonicalizerTool(CoreProviders providers) {
super(providers);
}
@Override
public Assumptions getAssumptions() {
return graph.getAssumptions();
}
@Override
public boolean canonicalizeReads() {
return false;
}
@Override
public boolean allUsagesAvailable() {
return true;
}
@Override
public Integer smallestCompareWidth() {
return null;
}
@Override
public OptionValues getOptions() {
return graph.getOptions();
}
@Override
public Stamp stamp(ValueNode node) {
return getBestStamp(node);
}
@Override
public boolean divisionOverflowIsJVMSCompliant() {
return false;
}
}
public RawConditionalEliminationVisitor(StructuredGraph graph, ScheduleResult schedule, MetaAccessProvider metaAccess, boolean replaceInputsWithConstants) {
this.graph = graph;
this.debug = graph.getDebug();
this.schedule = schedule;
this.metaAccess = metaAccess;
this.rawCanonicalizerTool = new RawCanonicalizerTool(new Providers(metaAccess, null, null, null, null, null, null, null, null, null, null, null, null, null));
blockActionStart = new BlockMap<>(schedule.getCFG());
endMaps = EconomicMap.create(Equivalence.IDENTITY);
stampMap = graph.createNodeMap();
undoOperations = new NodeStack();
replaceConstantInputs = replaceInputsWithConstants && GraalOptions.ReplaceInputsWithConstantsBasedOnStamps.getValue(graph.getOptions());
nodeToBlockMap = EconomicMap.create();
}
protected void replaceInput(Position p, Node oldInput, Node newConstantInput) {
p.set(oldInput, newConstantInput);
}
protected int replaceConstantInputs(Node node) {
int replacements = 0;
// Check if we can replace any of the inputs with a constant.
for (Position p : node.inputPositions()) {
Node input = p.get(node);
if (p.getInputType() == InputType.Value) {
if (input instanceof ValueNode) {
ValueNode valueNode = (ValueNode) input;
if (valueNode instanceof ConstantNode) {
// Input already is a constant.
} else {
Stamp bestStamp = getBestStamp(valueNode);
Constant constant = bestStamp.asConstant();
if (constant != null) {
if (bestStamp instanceof FloatStamp) {
FloatStamp floatStamp = (FloatStamp) bestStamp;
if (floatStamp.contains(0.0d)) {
// Could also be -0.0d.
continue;
}
}
ConstantNode stampConstant = ConstantNode.forConstant(bestStamp, constant, metaAccess, graph);
assert stampConstant.stamp(NodeView.DEFAULT).isCompatible(valueNode.stamp(NodeView.DEFAULT));
replaceInput(p, node, stampConstant);
graph.getOptimizationLog().report(FixReadsPhase.class, "ConstantInputReplacement", node);
replacements++;
}
}
}
}
}
return replacements;
}
private static boolean nonNullAndDominates(HIRBlock a, HIRBlock b) {
if (a == null) {
return false;
} else {
return a.dominates(b);
}
}
protected void processNode(Node node, HIRBlock b, NodePredicate nodePredicate) {
assert node.isAlive();
if (replaceConstantInputs) {
replaceConstantInputs(node);
}
if (node.getNodeClass().valueNumberable()) {
Node dominatingDuplicate = graph.findDuplicate(node, nodePredicate);
if (dominatingDuplicate != null) {
node.replaceAndDelete(dominatingDuplicate);
return;
}
}
if (node instanceof MergeNode) {
registerCombinedStamps((MergeNode) node);
}
if (node instanceof SwitchNode switchNode) {
/*
* Since later in this phase we will be visiting all control split successors the
* operation of computing successor stamps for switch nodes can be quite costly.
* Thus, we already compute and cache all eagerly here.
*/
if (successorStampCache == null) {
successorStampCache = EconomicMap.create();
}
switchNode.getAllSuccessorValueStamps(successorStampCache);
}
if (node instanceof AbstractBeginNode) {
processAbstractBegin((AbstractBeginNode) node);
} else if (node instanceof IfNode) {
processIf((IfNode) node);
} else if (node instanceof IntegerSwitchNode) {
processIntegerSwitch((IntegerSwitchNode) node);
} else if (node instanceof BinaryNode) {
processBinary((BinaryNode) node, b, nodePredicate);
} else if (node instanceof ConditionalNode) {
processConditional((ConditionalNode) node);
} else if (node instanceof UnaryNode) {
processUnary((UnaryNode) node, b, nodePredicate);
} else if (node instanceof EndNode) {
processEnd((EndNode) node);
}
if (node.getNodeClass().valueNumberable() && node.isAlive()) {
nodeToBlockMap.put(node, b);
}
}
protected void registerCombinedStamps(MergeNode node) {
EconomicMap<ValueNode, Stamp> endMap = endMaps.get(node);
MapCursor<ValueNode, Stamp> entries = endMap.getEntries();
while (entries.advance()) {
ValueNode value = entries.getKey();
if (value.isDeleted()) {
// nodes from this map can be deleted when a loop dies
continue;
}
if (registerNewValueStamp(value, entries.getValue())) {
counterBetterMergedStamps.increment(debug);
}
}
}
/**
* Maximum depth of dominators walked during the creation of better stamps at end nodes. Any
* larger number can lead to combinatorial explosion and long compilation times.
*/
private static final int BETTER_END_STAMPS_MAX_DOM_DEPTH = 128;
protected void processEnd(EndNode node) {
AbstractMergeNode abstractMerge = node.merge();
if (abstractMerge instanceof MergeNode) {
MergeNode merge = (MergeNode) abstractMerge;
NodeMap<HIRBlock> blockToNodeMap = this.schedule.getNodeToBlockMap();
HIRBlock mergeBlock = blockToNodeMap.get(merge);
HIRBlock mergeBlockDominator = mergeBlock.getDominator();
HIRBlock currentBlock = blockToNodeMap.get(node);
EconomicMap<ValueNode, Stamp> currentEndMap = endMaps.get(merge);
if (currentEndMap == null || !currentEndMap.isEmpty()) {
EconomicMap<ValueNode, Stamp> endMap = EconomicMap.create(Equivalence.IDENTITY);
// Process phis
for (ValuePhiNode phi : merge.valuePhis()) {
if (currentEndMap == null || currentEndMap.containsKey(phi)) {
ValueNode valueAt = phi.valueAt(node);
Stamp bestStamp = getBestStamp(valueAt);
if (currentEndMap != null) {
bestStamp = bestStamp.meet(currentEndMap.get(phi));
}
if (!bestStamp.equals(phi.stamp(NodeView.DEFAULT))) {
endMap.put(phi, bestStamp);
}
}
}
int distance = 0;
int lastMark = undoOperations.size();
while (currentBlock != mergeBlockDominator) {
if (distance++ > BETTER_END_STAMPS_MAX_DOM_DEPTH) {
break;
}
int mark = blockActionStart.get(currentBlock);
for (int i = lastMark - 1; i >= mark; --i) {
ValueNode nodeWithNewStamp = (ValueNode) undoOperations.get(i);
if (nodeWithNewStamp.isDeleted() || nodeWithNewStamp instanceof LogicNode || nodeWithNewStamp instanceof ConstantNode || blockToNodeMap.isNew(nodeWithNewStamp)) {
continue;
}
HIRBlock block = getBlock(nodeWithNewStamp, blockToNodeMap);
if (block == null || block.getId() <= mergeBlockDominator.getId()) {
// Node with new stamp in path to the merge block dominator and that
// at the same time was defined at least in the merge block
// dominator (i.e., therefore can be used after the merge.)
Stamp bestStamp = getBestStamp(nodeWithNewStamp);
assert bestStamp != null;
if (currentEndMap != null) {
Stamp otherEndsStamp = currentEndMap.get(nodeWithNewStamp);
if (otherEndsStamp == null) {
// No stamp registered in one of the previously processed
// ends => skip.
continue;
}
bestStamp = bestStamp.meet(otherEndsStamp);
}
if (nodeWithNewStamp.stamp(NodeView.DEFAULT).tryImproveWith(bestStamp) == null) {
// No point in registering the stamp.
} else {
endMap.put(nodeWithNewStamp, bestStamp);
}
}
}
currentBlock = currentBlock.getDominator();
}
endMaps.put(merge, endMap);
}
}
}
private static HIRBlock getBlock(ValueNode node, NodeMap<HIRBlock> blockToNodeMap) {
if (node instanceof PhiNode) {
PhiNode phiNode = (PhiNode) node;
return blockToNodeMap.get(phiNode.merge());
}
return blockToNodeMap.get(node);
}
protected void processUnary(UnaryNode node, HIRBlock block, NodePredicate gvnPredicate) {
ValueNode value = node.getValue();
Stamp bestStamp = getBestStamp(value);
Stamp newStamp = node.foldStamp(bestStamp);
if (!checkReplaceWithConstant(newStamp, node)) {
if (!bestStamp.equals(value.stamp(NodeView.DEFAULT))) {
ValueNode newNode = node.canonical(rawCanonicalizerTool);
if (newNode != node) {
// Canonicalization successfully triggered.
if (newNode != null && !newNode.isAlive()) {
newNode = addHelper(newNode, block, gvnPredicate);
}
node.replaceAndDelete(newNode);
GraphUtil.tryKillUnused(value);
return;
}
}
registerNewValueStamp(node, newStamp);
}
}
private ValueNode addHelper(ValueNode newNode, HIRBlock block, NodePredicate gvnPredicate) {
Graph.Mark m = graph.getMark();
ValueNode result = graph.addOrUniqueWithInputs(newNode, gvnPredicate);
for (Node n : graph.getNewNodes(m)) {
nodeToBlockMap.put(n, block);
}
return result;
}
protected boolean checkReplaceWithConstant(Stamp newStamp, ValueNode node) {
Constant constant = newStamp.asConstant();
if (constant != null && !(node instanceof ConstantNode)) {
ConstantNode stampConstant = ConstantNode.forConstant(newStamp, constant, metaAccess, graph);
node.replaceAtUsages(stampConstant, InputType.Value);
graph.getOptimizationLog().report(FixReadsPhase.class, "ConstantReplacement", node);
GraphUtil.tryKillUnused(node);
return true;
}
return false;
}
protected void processBinary(BinaryNode node, HIRBlock b, NodePredicate nodePredicate) {
ValueNode x = node.getX();
ValueNode y = node.getY();
Stamp xStamp = getBestStamp(x);
Stamp yStamp = getBestStamp(y);
Stamp newStamp = node.foldStamp(xStamp, yStamp);
if (!checkReplaceWithConstant(newStamp, node)) {
if (!xStamp.equals(x.stamp(NodeView.DEFAULT)) || !yStamp.equals(y.stamp(NodeView.DEFAULT))) {
// At least one of the inputs has an improved stamp => attempt to canonicalize
// based on that improvement.
ValueNode newNode = node.canonical(rawCanonicalizerTool);
if (newNode != node) {
// Canonicalization successfully triggered.
if (newNode != null && !newNode.isAlive()) {
newNode = addHelper(newNode, b, nodePredicate);
}
node.replaceAndDelete(newNode);
GraphUtil.tryKillUnused(x);
GraphUtil.tryKillUnused(y);
graph.getOptimizationLog().report(FixReadsPhase.class, "BinaryCanonicalization", node);
return;
}
}
registerNewValueStamp(node, newStamp);
}
}
protected void processIntegerSwitch(IntegerSwitchNode node) {
Stamp bestStamp = getBestStamp(node.value());
if (node.tryRemoveUnreachableKeys(null, bestStamp, successorStampCache)) {
graph.getOptimizationLog().report(FixReadsPhase.class, "SwitchCanonicalization", node);
}
}
protected void processIf(IfNode node) {
TriState result = tryProveCondition(node.condition());
if (result != TriState.UNKNOWN) {
boolean isTrue = (result == TriState.TRUE);
// Don't kill the other branch immediately, see
// `ConditionalEliminationPhase.processGuard`.
node.setCondition(LogicConstantNode.forBoolean(isTrue, node.graph()));
graph.getOptimizationLog().report(FixReadsPhase.class, "IfElimination", node);
}
}
protected void processConditional(ConditionalNode node) {
TriState result = tryProveCondition(node.condition());
if (result != TriState.UNKNOWN) {
boolean isTrue = (result == TriState.TRUE);
node.replaceAndDelete(isTrue ? node.trueValue() : node.falseValue());
graph.getOptimizationLog().report(FixReadsPhase.class, "ConditionalElimination", node);
} else {
Stamp trueStamp = getBestStamp(node.trueValue());
Stamp falseStamp = getBestStamp(node.falseValue());
registerNewStamp(node, trueStamp.meet(falseStamp));
}
}
protected TriState tryProveCondition(LogicNode condition) {
Stamp conditionStamp = this.getBestStamp(condition);
if (conditionStamp == StampFactory.tautology()) {
return TriState.TRUE;
} else if (conditionStamp == StampFactory.contradiction()) {
return TriState.FALSE;
}
if (condition instanceof UnaryOpLogicNode) {
UnaryOpLogicNode unaryOpLogicNode = (UnaryOpLogicNode) condition;
return unaryOpLogicNode.tryFold(this.getBestStamp(unaryOpLogicNode.getValue()));
} else if (condition instanceof BinaryOpLogicNode) {
BinaryOpLogicNode binaryOpLogicNode = (BinaryOpLogicNode) condition;
return binaryOpLogicNode.tryFold(this.getBestStamp(binaryOpLogicNode.getX()), this.getBestStamp(binaryOpLogicNode.getY()));
}
return TriState.UNKNOWN;
}
protected void processAbstractBegin(AbstractBeginNode beginNode) {
Node predecessor = beginNode.predecessor();
if (predecessor instanceof IfNode) {
IfNode ifNode = (IfNode) predecessor;
boolean negated = (ifNode.falseSuccessor() == beginNode);
LogicNode condition = ifNode.condition();
registerNewCondition(condition, negated);
} else if (predecessor instanceof IntegerSwitchNode) {
IntegerSwitchNode integerSwitchNode = (IntegerSwitchNode) predecessor;
registerIntegerSwitch(beginNode, integerSwitchNode);
}
}
private void registerIntegerSwitch(AbstractBeginNode beginNode, IntegerSwitchNode integerSwitchNode) {
if (successorStampCache == null) {
successorStampCache = EconomicMap.create();
}
registerNewValueStamp(integerSwitchNode.value(), integerSwitchNode.getValueStampForSuccessor(beginNode, successorStampCache));
}
protected void registerNewCondition(LogicNode condition, boolean negated) {
if (condition instanceof UnaryOpLogicNode) {
UnaryOpLogicNode unaryLogicNode = (UnaryOpLogicNode) condition;
ValueNode value = unaryLogicNode.getValue();
Stamp newStamp = unaryLogicNode.getSucceedingStampForValue(negated);
registerNewValueStamp(value, newStamp);
} else if (condition instanceof BinaryOpLogicNode) {
BinaryOpLogicNode binaryOpLogicNode = (BinaryOpLogicNode) condition;
ValueNode x = binaryOpLogicNode.getX();
ValueNode y = binaryOpLogicNode.getY();
Stamp xStamp = getBestStamp(x);
Stamp yStamp = getBestStamp(y);
registerNewValueStamp(x, binaryOpLogicNode.getSucceedingStampForX(negated, xStamp, yStamp));
registerNewValueStamp(y, binaryOpLogicNode.getSucceedingStampForY(negated, xStamp, yStamp));
}
registerCondition(condition, negated);
}
protected void registerCondition(LogicNode condition, boolean negated) {
registerNewStamp(condition, negated ? StampFactory.contradiction() : StampFactory.tautology());
}
protected boolean registerNewValueStamp(ValueNode value, Stamp newStamp) {
if (newStamp != null && !value.isConstant()) {
Stamp currentStamp = getBestStamp(value);
Stamp betterStamp = currentStamp.tryImproveWith(newStamp);
if (betterStamp != null) {
registerNewStamp(value, betterStamp);
return true;
}
}
return false;
}
protected void registerNewStamp(ValueNode value, Stamp newStamp) {
counterStampsRegistered.increment(debug);
debug.log("\t Saving stamp for node %s stamp %s", value, newStamp);
ValueNode originalNode = value;
stampMap.setAndGrow(originalNode, new StampElement(newStamp, stampMap.getAndGrow(originalNode)));
undoOperations.push(originalNode);
}
protected Stamp getBestStamp(ValueNode value) {
ValueNode originalNode = value;
if (!value.isAlive()) {
return value.stamp(NodeView.DEFAULT);
}
StampElement currentStamp = stampMap.getAndGrow(originalNode);
if (currentStamp == null) {
return value.stamp(NodeView.DEFAULT);
}
return currentStamp.getStamp();
}
@Override
public Integer enter(HIRBlock b) {
int mark = undoOperations.size();
blockActionStart.put(b, mark);
NodePredicate nodePredicate = n -> nonNullAndDominates(nodeToBlockMap.get(n), b);
for (Node n : schedule.getBlockToNodesMap().get(b)) {
if (n.isAlive()) {
processNode(n, b, nodePredicate);
}
}
return mark;
}
@Override
public void exit(HIRBlock b, Integer state) {
int mark = state;
while (undoOperations.size() > mark) {
Node node = undoOperations.pop();
if (node.isAlive()) {
stampMap.set(node, stampMap.get(node).getParent());
}
}
}
}
public FixReadsPhase(boolean replaceInputsWithConstants, BasePhase<? super CoreProviders> schedulePhase) {
this.replaceInputsWithConstants = replaceInputsWithConstants;
this.schedulePhase = schedulePhase;
}
@Override
public Optional<NotApplicable> notApplicableTo(GraphState graphState) {
return NotApplicable.ifAny(
NotApplicable.ifApplied(this, StageFlag.FIXED_READS, graphState),
NotApplicable.unlessRunAfter(this, StageFlag.LOW_TIER_LOWERING, graphState),
NotApplicable.when(graphState.getGuardsStage().areFrameStatesAtSideEffects(), "This phase must run after FSA"));
}
@Override
public boolean mustApply(GraphState graphState) {
return graphState.requiresFutureStage(StageFlag.FIXED_READS);
}
@Override
@SuppressWarnings("try")
protected void run(StructuredGraph graph, CoreProviders context) {
schedulePhase.apply(graph, context);
ScheduleResult schedule = graph.getLastSchedule();
FixReadsClosure fixReadsClosure = new FixReadsClosure(graph, schedule);
for (HIRBlock block : schedule.getCFG().getBlocks()) {
fixReadsClosure.processNodes(block);
}
if (GraalOptions.RawConditionalElimination.getValue(graph.getOptions()) && GraalOptions.EnableFixReadsConditionalElimination.getValue(graph.getOptions())) {
schedule.getCFG().visitDominatorTree(createVisitor(graph, schedule, context), false);
}
assert verifyPiRemovalInvariants(graph);
}
/**
* Run verifications to test invariants that need to hold after removing {@link PiNode} from a
* graph.
*/
public static boolean verifyPiRemovalInvariants(StructuredGraph graph) {
if (Assertions.assertionsEnabled()) {
for (Node n : graph.getNodes()) {
final boolean isFloatingGuardedNode = n instanceof FloatingGuardedNode;
if (isFloatingGuardedNode) {
// floating guarded nodes without a guard are "universally" true meaning they
// can be executed everywhere
final GuardingNode guard = ((FloatingGuardedNode) n).getGuard();
assert verifyOnlyFixedGuards(guard);
}
}
}
return true;
}
private static boolean verifyOnlyFixedGuards(ValueNodeInterface guardingRoot) {
final boolean isUniversallyTrue = guardingRoot == null;
if (isUniversallyTrue) {
return true;
}
final StructuredGraph graph = guardingRoot.asNode().graph();
NodeBitMap visited = graph.createNodeBitMap();
Deque<ValueNodeInterface> toVisit = new ArrayDeque<>();
toVisit.add(guardingRoot);
while (!toVisit.isEmpty()) {
ValueNodeInterface currentGuard = toVisit.pop();
if (visited.isMarked(currentGuard.asNode())) {
continue;
}
visited.mark(currentGuard.asNode());
if (currentGuard instanceof MultiGuardNode mg) {
toVisit.addAll(mg.getGuards());
} else {
assert currentGuard instanceof FixedNode : Assertions.errorMessage(
"Should not have floating guarded nodes without fixed guards left after removing pis, they could float uncontrolled now", currentGuard);
}
}
return true;
}
@Override
public void updateGraphState(GraphState graphState) {
super.updateGraphState(graphState);
graphState.setAfterStage(StageFlag.FIXED_READS);
graphState.removeRequirementToStage(StageFlag.FIXED_READS);
}
protected ControlFlowGraph.RecursiveVisitor<?> createVisitor(StructuredGraph graph, ScheduleResult schedule, CoreProviders context) {
return new RawConditionalEliminationVisitor(graph, schedule, context.getMetaAccess(), replaceInputsWithConstants);
}
protected static final class StampElement {
private final Stamp stamp;
private final StampElement parent;
public StampElement(Stamp stamp, StampElement parent) {
this.stamp = stamp;
this.parent = parent;
}
public StampElement getParent() {
return parent;
}
public Stamp getStamp() {
return stamp;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(stamp);
if (this.parent != null) {
result.append(" (");
result.append(this.parent);
result.append(")");
}
return result.toString();
}
}
public BasePhase<? super CoreProviders> getSchedulePhase() {
return schedulePhase;
}
}
|
googleapis/google-cloud-java | 36,404 | java-private-catalog/proto-google-cloud-private-catalog-v1beta1/src/main/java/com/google/cloud/privatecatalog/v1beta1/SearchProductsRequest.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/privatecatalog/v1beta1/private_catalog.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.privatecatalog.v1beta1;
/**
*
*
* <pre>
* Request message for [PrivateCatalog.SearchProducts][google.cloud.privatecatalog.v1beta1.PrivateCatalog.SearchProducts].
* </pre>
*
* Protobuf type {@code google.cloud.privatecatalog.v1beta1.SearchProductsRequest}
*/
public final class SearchProductsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.privatecatalog.v1beta1.SearchProductsRequest)
SearchProductsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use SearchProductsRequest.newBuilder() to construct.
private SearchProductsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SearchProductsRequest() {
resource_ = "";
query_ = "";
pageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new SearchProductsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.privatecatalog.v1beta1.PrivateCatalogProto
.internal_static_google_cloud_privatecatalog_v1beta1_SearchProductsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.privatecatalog.v1beta1.PrivateCatalogProto
.internal_static_google_cloud_privatecatalog_v1beta1_SearchProductsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest.class,
com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest.Builder.class);
}
public static final int RESOURCE_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object resource_ = "";
/**
*
*
* <pre>
* Required. The name of the resource context. See [SearchCatalogsRequest.resource][google.cloud.privatecatalog.v1beta1.SearchCatalogsRequest.resource]
* for details.
* </pre>
*
* <code>string resource = 1 [(.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>
* Required. The name of the resource context. See [SearchCatalogsRequest.resource][google.cloud.privatecatalog.v1beta1.SearchCatalogsRequest.resource]
* for details.
* </pre>
*
* <code>string resource = 1 [(.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;
}
}
public static final int QUERY_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object query_ = "";
/**
*
*
* <pre>
* The query to filter the products.
*
* The supported queries are:
* * List products of all catalogs: empty
* * List products under a catalog: `parent=catalogs/{catalog}`
* * Get a product by name:
* `name=catalogs/{catalog}/products/{product}`
* </pre>
*
* <code>string query = 2;</code>
*
* @return The query.
*/
@java.lang.Override
public java.lang.String getQuery() {
java.lang.Object ref = query_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
query_ = s;
return s;
}
}
/**
*
*
* <pre>
* The query to filter the products.
*
* The supported queries are:
* * List products of all catalogs: empty
* * List products under a catalog: `parent=catalogs/{catalog}`
* * Get a product by name:
* `name=catalogs/{catalog}/products/{product}`
* </pre>
*
* <code>string query = 2;</code>
*
* @return The bytes for query.
*/
@java.lang.Override
public com.google.protobuf.ByteString getQueryBytes() {
java.lang.Object ref = query_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
query_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 3;
private int pageSize_ = 0;
/**
*
*
* <pre>
* The maximum number of entries that are requested.
* </pre>
*
* <code>int32 page_size = 3;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A pagination token returned from a previous call to SearchProducts that
* indicates where this listing should continue from.
* </pre>
*
* <code>string page_token = 4;</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 pagination token returned from a previous call to SearchProducts that
* indicates where this listing should continue from.
* </pre>
*
* <code>string page_token = 4;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resource_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resource_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(query_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, query_);
}
if (pageSize_ != 0) {
output.writeInt32(3, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, pageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resource_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resource_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(query_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, query_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, pageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest)) {
return super.equals(obj);
}
com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest other =
(com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest) obj;
if (!getResource().equals(other.getResource())) return false;
if (!getQuery().equals(other.getQuery())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + RESOURCE_FIELD_NUMBER;
hash = (53 * hash) + getResource().hashCode();
hash = (37 * hash) + QUERY_FIELD_NUMBER;
hash = (53 * hash) + getQuery().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest 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.privatecatalog.v1beta1.SearchProductsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest 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.privatecatalog.v1beta1.SearchProductsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest 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.privatecatalog.v1beta1.SearchProductsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest 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.privatecatalog.v1beta1.SearchProductsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest 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.privatecatalog.v1beta1.SearchProductsRequest 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 [PrivateCatalog.SearchProducts][google.cloud.privatecatalog.v1beta1.PrivateCatalog.SearchProducts].
* </pre>
*
* Protobuf type {@code google.cloud.privatecatalog.v1beta1.SearchProductsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.privatecatalog.v1beta1.SearchProductsRequest)
com.google.cloud.privatecatalog.v1beta1.SearchProductsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.privatecatalog.v1beta1.PrivateCatalogProto
.internal_static_google_cloud_privatecatalog_v1beta1_SearchProductsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.privatecatalog.v1beta1.PrivateCatalogProto
.internal_static_google_cloud_privatecatalog_v1beta1_SearchProductsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest.class,
com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest.Builder.class);
}
// Construct using com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
resource_ = "";
query_ = "";
pageSize_ = 0;
pageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.privatecatalog.v1beta1.PrivateCatalogProto
.internal_static_google_cloud_privatecatalog_v1beta1_SearchProductsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest
getDefaultInstanceForType() {
return com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest build() {
com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest buildPartial() {
com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest result =
new com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.resource_ = resource_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.query_ = query_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.pageToken_ = pageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest) {
return mergeFrom((com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest other) {
if (other
== com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest.getDefaultInstance())
return this;
if (!other.getResource().isEmpty()) {
resource_ = other.resource_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getQuery().isEmpty()) {
query_ = other.query_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000008;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
resource_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
query_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 24:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000004;
break;
} // case 24
case 34:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object resource_ = "";
/**
*
*
* <pre>
* Required. The name of the resource context. See [SearchCatalogsRequest.resource][google.cloud.privatecatalog.v1beta1.SearchCatalogsRequest.resource]
* for details.
* </pre>
*
* <code>string resource = 1 [(.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>
* Required. The name of the resource context. See [SearchCatalogsRequest.resource][google.cloud.privatecatalog.v1beta1.SearchCatalogsRequest.resource]
* for details.
* </pre>
*
* <code>string resource = 1 [(.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>
* Required. The name of the resource context. See [SearchCatalogsRequest.resource][google.cloud.privatecatalog.v1beta1.SearchCatalogsRequest.resource]
* for details.
* </pre>
*
* <code>string resource = 1 [(.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_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the resource context. See [SearchCatalogsRequest.resource][google.cloud.privatecatalog.v1beta1.SearchCatalogsRequest.resource]
* for details.
* </pre>
*
* <code>string resource = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearResource() {
resource_ = getDefaultInstance().getResource();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the resource context. See [SearchCatalogsRequest.resource][google.cloud.privatecatalog.v1beta1.SearchCatalogsRequest.resource]
* for details.
* </pre>
*
* <code>string resource = 1 [(.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_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object query_ = "";
/**
*
*
* <pre>
* The query to filter the products.
*
* The supported queries are:
* * List products of all catalogs: empty
* * List products under a catalog: `parent=catalogs/{catalog}`
* * Get a product by name:
* `name=catalogs/{catalog}/products/{product}`
* </pre>
*
* <code>string query = 2;</code>
*
* @return The query.
*/
public java.lang.String getQuery() {
java.lang.Object ref = query_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
query_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The query to filter the products.
*
* The supported queries are:
* * List products of all catalogs: empty
* * List products under a catalog: `parent=catalogs/{catalog}`
* * Get a product by name:
* `name=catalogs/{catalog}/products/{product}`
* </pre>
*
* <code>string query = 2;</code>
*
* @return The bytes for query.
*/
public com.google.protobuf.ByteString getQueryBytes() {
java.lang.Object ref = query_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
query_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The query to filter the products.
*
* The supported queries are:
* * List products of all catalogs: empty
* * List products under a catalog: `parent=catalogs/{catalog}`
* * Get a product by name:
* `name=catalogs/{catalog}/products/{product}`
* </pre>
*
* <code>string query = 2;</code>
*
* @param value The query to set.
* @return This builder for chaining.
*/
public Builder setQuery(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
query_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The query to filter the products.
*
* The supported queries are:
* * List products of all catalogs: empty
* * List products under a catalog: `parent=catalogs/{catalog}`
* * Get a product by name:
* `name=catalogs/{catalog}/products/{product}`
* </pre>
*
* <code>string query = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearQuery() {
query_ = getDefaultInstance().getQuery();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The query to filter the products.
*
* The supported queries are:
* * List products of all catalogs: empty
* * List products under a catalog: `parent=catalogs/{catalog}`
* * Get a product by name:
* `name=catalogs/{catalog}/products/{product}`
* </pre>
*
* <code>string query = 2;</code>
*
* @param value The bytes for query to set.
* @return This builder for chaining.
*/
public Builder setQueryBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
query_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* The maximum number of entries that are requested.
* </pre>
*
* <code>int32 page_size = 3;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* The maximum number of entries that are requested.
* </pre>
*
* <code>int32 page_size = 3;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The maximum number of entries that are requested.
* </pre>
*
* <code>int32 page_size = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000004);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A pagination token returned from a previous call to SearchProducts that
* indicates where this listing should continue from.
* </pre>
*
* <code>string page_token = 4;</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 pagination token returned from a previous call to SearchProducts that
* indicates where this listing should continue from.
* </pre>
*
* <code>string page_token = 4;</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 pagination token returned from a previous call to SearchProducts that
* indicates where this listing should continue from.
* </pre>
*
* <code>string page_token = 4;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* A pagination token returned from a previous call to SearchProducts that
* indicates where this listing should continue from.
* </pre>
*
* <code>string page_token = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* A pagination token returned from a previous call to SearchProducts that
* indicates where this listing should continue from.
* </pre>
*
* <code>string page_token = 4;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.privatecatalog.v1beta1.SearchProductsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.privatecatalog.v1beta1.SearchProductsRequest)
private static final com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest();
}
public static com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SearchProductsRequest> PARSER =
new com.google.protobuf.AbstractParser<SearchProductsRequest>() {
@java.lang.Override
public SearchProductsRequest 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<SearchProductsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SearchProductsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.privatecatalog.v1beta1.SearchProductsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/incubator-hugegraph | 35,982 | hugegraph-server/hugegraph-test/src/main/java/org/apache/hugegraph/core/PropertyCoreTest.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.hugegraph.core;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.apache.hugegraph.HugeGraph;
import org.apache.hugegraph.backend.serializer.BytesBuffer;
import org.apache.hugegraph.schema.SchemaManager;
import org.apache.hugegraph.testutil.Assert;
import org.apache.hugegraph.testutil.Utils;
import org.apache.hugegraph.traversal.optimize.TraversalUtil;
import org.apache.hugegraph.util.Blob;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
public abstract class PropertyCoreTest extends BaseCoreTest {
protected abstract <V> V property(String key, V value);
protected abstract <V> V propertyList(String key, Object... values);
protected abstract <V> V propertySet(String key, Object... values);
@Before
public void initSchema() {
SchemaManager schema = graph().schema();
schema.propertyKey("id").asInt().create();
schema.propertyKey("string").asText().create();
schema.propertyKey("bool").asBoolean().create();
schema.propertyKey("byte").asByte().create();
schema.propertyKey("int").asInt().create();
schema.propertyKey("long").asLong().create();
schema.propertyKey("float").asFloat().create();
schema.propertyKey("double").asDouble().create();
schema.propertyKey("blob").asBlob().create();
schema.propertyKey("time").asDate().create();
schema.propertyKey("uuid").asUUID().create();
schema.propertyKey("list_string").asText().valueList().create();
schema.propertyKey("list_bool").asBoolean().valueList().create();
schema.propertyKey("list_byte").asByte().valueList().create();
schema.propertyKey("list_int").asInt().valueList().create();
schema.propertyKey("list_long").asLong().valueList().create();
schema.propertyKey("list_float").asFloat().valueList().create();
schema.propertyKey("list_double").asDouble().valueList().create();
schema.propertyKey("list_blob").asBlob().valueList().create();
schema.propertyKey("list_time").asDate().valueList().create();
schema.propertyKey("list_uuid").asUUID().valueList().create();
schema.propertyKey("set_string").asText().valueSet().create();
schema.propertyKey("set_bool").asBoolean().valueSet().create();
schema.propertyKey("set_byte").asByte().valueSet().create();
schema.propertyKey("set_int").asInt().valueSet().create();
schema.propertyKey("set_long").asLong().valueSet().create();
schema.propertyKey("set_float").asFloat().valueSet().create();
schema.propertyKey("set_double").asDouble().valueSet().create();
schema.propertyKey("set_blob").asBlob().valueSet().create();
schema.propertyKey("set_time").asDate().valueSet().create();
schema.propertyKey("set_uuid").asUUID().valueSet().create();
schema.vertexLabel("person")
.properties("id", "string", "bool", "byte", "int",
"long", "float", "double",
"time", "uuid", "blob",
"list_string", "list_bool", "list_byte", "list_int",
"list_long", "list_float", "list_double",
"list_time", "list_uuid", "list_blob",
"set_string", "set_bool", "set_byte", "set_int",
"set_long", "set_float", "set_double",
"set_time", "set_uuid", "set_blob")
.nullableKeys("string", "bool", "byte", "int",
"long", "float", "double",
"time", "uuid", "blob",
"list_string", "list_bool", "list_byte", "list_int",
"list_long", "list_float", "list_double",
"list_time", "list_uuid", "list_blob",
"set_string", "set_bool", "set_byte", "set_int",
"set_long", "set_float", "set_double",
"set_time", "set_uuid", "set_blob")
.primaryKeys("id")
.create();
schema.edgeLabel("transfer")
.properties("id", "string", "bool", "byte", "int",
"long", "float", "double",
"time", "uuid", "blob",
"list_string", "list_bool", "list_byte", "list_int",
"list_long", "list_float", "list_double",
"list_time", "list_uuid", "list_blob",
"set_string", "set_bool", "set_byte", "set_int",
"set_long", "set_float", "set_double",
"set_time", "set_uuid", "set_blob")
.nullableKeys("string", "bool", "byte", "int",
"long", "float", "double",
"time", "uuid", "blob",
"list_string", "list_bool", "list_byte", "list_int",
"list_long", "list_float", "list_double",
"list_time", "list_uuid", "list_blob",
"set_string", "set_bool", "set_byte", "set_int",
"set_long", "set_float", "set_double",
"set_time", "set_uuid", "set_blob")
.link("person", "person")
.create();
}
public static class VertexPropertyCoreTest extends PropertyCoreTest {
@Override
protected <V> V property(String key, V value) {
HugeGraph graph = graph();
Vertex vertex = graph.addVertex(T.label, "person", "id", 1,
key, value);
graph.tx().commit();
vertex = graph.vertices(vertex.id()).next();
Assert.assertTrue(TraversalUtil.testProperty(vertex.property(key),
value));
return vertex.value(key);
}
@Override
protected <V> V propertyList(String key, Object... values) {
HugeGraph graph = graph();
key = "list_" + key;
Vertex vertex = graph.addVertex(T.label, "person", "id", 2,
key, Arrays.asList(values));
graph.tx().commit();
vertex = graph.vertices(vertex.id()).next();
Assert.assertTrue(TraversalUtil.testProperty(vertex.property(key),
Arrays.asList(values)));
return vertex.value(key);
}
@Override
protected <V> V propertySet(String key, Object... values) {
HugeGraph graph = graph();
key = "set_" + key;
Vertex vertex = graph.addVertex(T.label, "person", "id", 3,
key, Arrays.asList(values));
graph.tx().commit();
vertex = graph.vertices(vertex.id()).next();
Assert.assertTrue(TraversalUtil.testProperty(vertex.property(key),
ImmutableSet.copyOf(values)));
Assert.assertFalse(TraversalUtil.testProperty(vertex.property(key),
ImmutableList.copyOf(values)));
return vertex.value(key);
}
}
public static class EdgePropertyCoreTest extends PropertyCoreTest {
@Override
protected <V> V property(String key, V value) {
HugeGraph graph = graph();
Vertex vertex1 = graph.addVertex(T.label, "person", "id", 1);
Vertex vertex2 = graph.addVertex(T.label, "person", "id", 2);
Edge edge = vertex1.addEdge("transfer", vertex2, "id", 1,
key, value);
graph.tx().commit();
edge = graph.edges(edge.id()).next();
Assert.assertTrue(TraversalUtil.testProperty(edge.property(key),
value));
return edge.value(key);
}
@Override
protected <V> V propertyList(String key, Object... values) {
HugeGraph graph = graph();
Vertex vertex1 = graph.addVertex(T.label, "person", "id", 1);
Vertex vertex2 = graph.addVertex(T.label, "person", "id", 2);
key = "list_" + key;
Edge edge = vertex1.addEdge("transfer", vertex2, "id", 2,
key, Arrays.asList(values));
graph.tx().commit();
edge = graph.edges(edge.id()).next();
Assert.assertTrue(TraversalUtil.testProperty(edge.property(key),
Arrays.asList(values)));
return edge.value(key);
}
@Override
protected <V> V propertySet(String key, Object... values) {
HugeGraph graph = graph();
Vertex vertex1 = graph.addVertex(T.label, "person", "id", 1);
Vertex vertex2 = graph.addVertex(T.label, "person", "id", 2);
key = "set_" + key;
Edge edge = vertex1.addEdge("transfer", vertex2, "id", 3,
key, Arrays.asList(values));
graph.tx().commit();
edge = graph.edges(edge.id()).next();
Assert.assertTrue(TraversalUtil.testProperty(edge.property(key),
ImmutableSet.copyOf(values)));
Assert.assertFalse(TraversalUtil.testProperty(edge.property(key),
ImmutableList.copyOf(values)));
return edge.value(key);
}
}
@Test
public void testTypeBoolean() {
boolean gender = true;
Assert.assertEquals(gender, property("bool", gender));
gender = false;
Assert.assertEquals(gender, property("bool", gender));
List<Boolean> list = ImmutableList.of(true, false, true, false);
Assert.assertEquals(list, propertyList("bool",
true, false, true, false));
Set<Boolean> set = ImmutableSet.of(true, false);
Assert.assertEquals(set, propertySet("bool",
true, false, true, false));
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertyList("bool", (byte) 1, true);
}, e -> {
Assert.assertContains("Invalid property value '[1, true]' " +
"for key 'list_bool'", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertySet("bool", (byte) 1, true);
}, e -> {
Assert.assertContains("Invalid property value '[1, true]' " +
"for key 'set_bool'", e.getMessage());
});
}
@Test
public void testTypeByte() {
Assert.assertEquals((byte) 3, property("byte", (byte) 3));
Assert.assertEquals((byte) 3, property("byte", 3));
Assert.assertEquals((byte) 18, property("byte", 18L));
Assert.assertEquals(Byte.MIN_VALUE, property("byte", Byte.MIN_VALUE));
Assert.assertEquals(Byte.MAX_VALUE, property("byte", Byte.MAX_VALUE));
List<Byte> list = ImmutableList.of((byte) 1, (byte) 3, (byte) 3,
(byte) 127, (byte) 128);
Assert.assertEquals(list, propertyList("byte",
(byte) 1, (byte) 3, (byte) 3,
(byte) 127, (byte) 128));
Assert.assertEquals(list, propertyList("byte",
(byte) 1, 3, (long) 3,
(byte) 127, (byte) 128));
Set<Byte> set = ImmutableSet.of((byte) 1, (byte) 3,
(byte) 127, (byte) 128);
Assert.assertEquals(set, propertySet("byte",
(byte) 1, (byte) 3, (byte) 3,
(byte) 127, (byte) 128));
Assert.assertThrows(IllegalArgumentException.class, () -> {
property("byte", 1.0);
}, e -> {
Assert.assertContains("Invalid property value '1.0' " +
"for key 'byte'", e.getMessage());
Assert.assertContains("Can't read '1.0' as byte: ", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
property("byte", 128);
}, e -> {
Assert.assertContains("Invalid property value '128' " +
"for key 'byte'", e.getMessage());
Assert.assertContains("Can't read '128' as byte: " +
"Value out of range", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
property("byte", "1");
}, e -> {
Assert.assertContains("Invalid property value '1' " +
"for key 'byte'", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertyList("byte", (byte) 1, true);
}, e -> {
Assert.assertContains("Invalid property value '[1, true]' " +
"for key 'list_byte'", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertyList("byte", (byte) 1, 128);
}, e -> {
Assert.assertContains("Invalid property value '[1, 128]' " +
"for key 'list_byte'", e.getMessage());
Assert.assertContains("Can't read '128' as byte: " +
"Value out of range", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertySet("byte", (byte) 1, true);
}, e -> {
Assert.assertContains("Invalid property value '[1, true]' " +
"for key 'set_byte'", e.getMessage());
});
}
@Test
public void testTypeInt() {
Assert.assertEquals(18, property("int", 18));
Assert.assertEquals(18, property("int", 18L));
Assert.assertEquals(Integer.MAX_VALUE,
property("int", Integer.MAX_VALUE));
Assert.assertEquals(Integer.MIN_VALUE,
property("int", Integer.MIN_VALUE));
List<Integer> list = ImmutableList.of(1, 3, 3, 127, 128);
Assert.assertEquals(list, propertyList("int",
1, 3, 3, 127, 128));
Assert.assertEquals(list, propertyList("int",
1, 3, 3, (byte) 127, 128L));
Set<Integer> set = ImmutableSet.of(1, 3, 127, 128);
Assert.assertEquals(set, propertySet("int",
1, 3, 3, 127, 128));
Assert.assertThrows(IllegalArgumentException.class, () -> {
property("int", 1.0);
}, e -> {
Assert.assertContains("Invalid property value '1.0' " +
"for key 'int'", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
property("int", Integer.MAX_VALUE + 1L);
}, e -> {
Assert.assertContains("Invalid property value '2147483648' " +
"for key 'int'", e.getMessage());
Assert.assertContains("Can't read '2147483648' as int: ",
e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
property("int", "1");
}, e -> {
Assert.assertContains("Invalid property value '1' " +
"for key 'int'", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertyList("int", 1, true);
}, e -> {
Assert.assertContains("Invalid property value '[1, true]' " +
"for key 'list_int'", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertyList("int", 1, Integer.MAX_VALUE + 1L);
}, e -> {
Assert.assertContains("Invalid property value '[1, 2147483648]' " +
"for key 'list_int'", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertySet("int", 1, true);
}, e -> {
Assert.assertContains("Invalid property value '[1, true]' " +
"for key 'set_int'", e.getMessage());
});
}
@Test
public void testTypeLong() {
Assert.assertEquals(18888888888L, property("long", 18888888888L));
Assert.assertEquals(Long.MIN_VALUE, property("long", Long.MIN_VALUE));
Assert.assertEquals(Long.MAX_VALUE, property("long", Long.MAX_VALUE));
List<Long> list = ImmutableList.of(1L, 3L, 3L, 127L, 128L);
Assert.assertEquals(list, propertyList("long",
1L, 3L, 3L, 127L, 128L));
Assert.assertEquals(list, propertyList("long",
1, (byte) 3, 3,
(short) 127, 128L));
Set<Long> set = ImmutableSet.of(1L, 3L, 127L, 128L);
Assert.assertEquals(set, propertySet("long",
1, 3, 3, 127, 128));
Assert.assertThrows(IllegalArgumentException.class, () -> {
property("long", 1.0);
}, e -> {
Assert.assertContains("Invalid property value '1.0' " +
"for key 'long'", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
property("long", "1");
}, e -> {
Assert.assertContains("Invalid property value '1' " +
"for key 'long'", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertyList("long", 1, true);
}, e -> {
Assert.assertContains("Invalid property value '[1, true]' " +
"for key 'list_long'", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertySet("long", 1, true);
}, e -> {
Assert.assertContains("Invalid property value '[1, true]' " +
"for key 'set_long'", e.getMessage());
});
}
@Test
public void testTypeFloat() {
Assert.assertEquals(1.86F, property("float", 1.86F));
Assert.assertEquals(3.14f, property("float", 3.14d));
Assert.assertEquals(Float.MIN_VALUE,
property("float", Float.MIN_VALUE));
Assert.assertEquals(Float.MAX_VALUE,
property("float", Float.MAX_VALUE));
Assert.assertEquals(Float.POSITIVE_INFINITY,
property("float", Float.POSITIVE_INFINITY));
Assert.assertEquals(Float.POSITIVE_INFINITY,
property("float", Double.MAX_VALUE));
Assert.assertEquals(Float.POSITIVE_INFINITY,
property("float", Double.POSITIVE_INFINITY));
Assert.assertEquals(Float.NEGATIVE_INFINITY,
property("float", Float.NEGATIVE_INFINITY));
Assert.assertEquals(Float.NEGATIVE_INFINITY,
property("float", -Double.MAX_VALUE));
Assert.assertEquals(Float.POSITIVE_INFINITY,
property("float", -Double.NEGATIVE_INFINITY));
Assert.assertEquals(Float.POSITIVE_INFINITY,
property("float", -2 * Double.NEGATIVE_INFINITY));
Assert.assertEquals(Float.NaN, property("float", Float.NaN));
List<Float> list = ImmutableList.of(1f, 3f, 3f, 127f, 128f);
Assert.assertEquals(list, propertyList("float",
1f, 3f, 3f, 127f, 128f));
Assert.assertEquals(list, propertyList("float",
1, (byte) 3, (long) 3,
127f, 128d));
Set<Float> set = ImmutableSet.of(1f, 3f, 127f, 128f);
Assert.assertEquals(set, propertySet("float",
1f, 3f, 3f, 127f, 128f));
Assert.assertThrows(IllegalArgumentException.class, () -> {
property("float", 'a');
}, e -> {
Assert.assertContains("Invalid property value " +
"'a' for key 'float'",
e.getMessage());
Assert.assertContains("expect a value of type Float, " +
"actual type Character",
e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
property("float", "1");
}, e -> {
Assert.assertContains("Invalid property value '1' " +
"for key 'float'", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertyList("float", 1, true);
}, e -> {
Assert.assertContains("Invalid property value '[1, true]' " +
"for key 'list_float'", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertySet("float", 1, true);
}, e -> {
Assert.assertContains("Invalid property value '[1, true]' " +
"for key 'set_float'", e.getMessage());
});
}
@Test
public void testTypeDouble() {
Assert.assertEquals(1.86d, property("double", 1.86d));
Assert.assertEquals(Double.MIN_VALUE,
property("double", Double.MIN_VALUE));
Assert.assertEquals(Double.MAX_VALUE,
property("double", Double.MAX_VALUE));
Assert.assertEquals(Double.POSITIVE_INFINITY,
property("double", Double.POSITIVE_INFINITY));
Assert.assertEquals(Double.POSITIVE_INFINITY,
property("double", 2 * Double.POSITIVE_INFINITY));
BigDecimal two = new BigDecimal(2);
BigDecimal value = BigDecimal.valueOf(Double.MAX_VALUE).multiply(two);
Assert.assertEquals(Double.POSITIVE_INFINITY,
property("double", value));
Assert.assertEquals(Double.POSITIVE_INFINITY,
property("double", -Double.NEGATIVE_INFINITY));
Assert.assertEquals(Double.POSITIVE_INFINITY,
property("double", -2 * Double.NEGATIVE_INFINITY));
value = BigDecimal.valueOf(-Double.MAX_VALUE).multiply(two);
Assert.assertEquals(Double.NEGATIVE_INFINITY,
property("double", value));
value = BigDecimal.valueOf(Double.MIN_VALUE).divide(two);
Assert.assertEquals(0.0, property("double", value));
Assert.assertEquals(Double.NEGATIVE_INFINITY,
property("double", Double.NEGATIVE_INFINITY));
Assert.assertEquals(Double.NaN, property("double", Double.NaN));
List<Double> list = ImmutableList.of(1d, 3d, 3d, 127d, 128d);
Assert.assertEquals(list, propertyList("double",
1d, 3d, 3d, 127d, 128d));
Assert.assertEquals(list, propertyList("double",
1, (byte) 3, (long) 3,
127f, 128d));
Set<Double> set = ImmutableSet.of(1d, 3d, 127d, 128d);
Assert.assertEquals(set, propertySet("double",
1d, 3d, 3d, 127d, 128f));
Assert.assertThrows(IllegalArgumentException.class, () -> {
property("double", "1");
}, e -> {
Assert.assertContains("Invalid property value '1' " +
"for key 'double'", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertyList("double", 1, true);
}, e -> {
Assert.assertContains("Invalid property value '[1, true]' " +
"for key 'list_double'", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertySet("double", 1, true);
}, e -> {
Assert.assertContains("Invalid property value '[1, true]' " +
"for key 'set_double'", e.getMessage());
});
}
@Test
public void testTypeString() {
Assert.assertEquals("Jame", property("string", "Jame"));
List<String> list = ImmutableList.of("ab", "cde", "cde", "123");
Assert.assertEquals(list, propertyList("string",
"ab", "cde", "cde", "123"));
Set<String> set = ImmutableSet.of("ab", "cde", "123");
Assert.assertEquals(set, propertySet("string",
"ab", "cde", "cde", "123", "cde"));
Assert.assertThrows(IllegalArgumentException.class, () -> {
property("string", 123);
}, e -> {
Assert.assertContains("Invalid property value '123' " +
"for key 'string'", e.getMessage());
Assert.assertContains(" expect a value of type String, " +
"actual type Integer", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertyList("string", "abc", true);
}, e -> {
Assert.assertContains("Invalid property value '[abc, true]' " +
"for key 'list_string'", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertySet("string", "abc", true);
}, e -> {
Assert.assertContains("Invalid property value '[abc, true]' " +
"for key 'set_string'", e.getMessage());
});
}
@Test
public void testTypeDate() throws ParseException {
Date time = new Date();
Assert.assertEquals(time, property("time", time));
Date expected = Utils.date("2018-12-12 00:00:00.000");
String date = "2018-12-12";
Assert.assertEquals(expected, property("time", date));
date = "2018-12-12 00:00:00";
Assert.assertEquals(expected, property("time", date));
date = "2018-12-12 00:00:00.000";
Assert.assertEquals(expected, property("time", date));
Assert.assertEquals(expected, property("time", expected.getTime()));
Date date1 = Utils.date("1970-01-01");
Date date2 = Utils.date("2019-12-12");
Date date3 = Utils.date("2020-5-28");
List<Date> list = ImmutableList.of(date1, date2, date2, date3);
Assert.assertEquals(list, propertyList("time",
date1, date2, date2, date3));
Set<Date> set = ImmutableSet.of(date1, date2, date3);
Assert.assertEquals(set, propertySet("time",
date1, date2, date2, date3));
Assert.assertEquals(new Date(123), property("time", 123));
Assert.assertThrows(IllegalArgumentException.class, () -> {
property("time", 123f);
}, e -> {
Assert.assertContains("Invalid property value '123.0' " +
"for key 'time'", e.getMessage());
Assert.assertContains(" expect a value of type Date, " +
"actual type Float", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertyList("time", date1, true);
}, e -> {
Assert.assertContains(", true]' for key 'list_time'",
e.getMessage());
Assert.assertContains("expect a value of type List<Date>",
e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertySet("time", date1, true);
}, e -> {
Assert.assertContains(", true]' for key 'set_time'",
e.getMessage());
Assert.assertContains("expect a value of type Set<Date>",
e.getMessage());
});
}
@Test
public void testTypeUUID() {
UUID uid = UUID.randomUUID();
Assert.assertEquals(uid, property("uuid", uid));
UUID uid1 = UUID.randomUUID();
UUID uid2 = UUID.randomUUID();
UUID uid3 = UUID.randomUUID();
List<UUID> list = ImmutableList.of(uid1, uid2, uid2, uid3);
Assert.assertEquals(list, propertyList("uuid",
uid1, uid2, uid2, uid3));
Set<UUID> set = ImmutableSet.of(uid1, uid2, uid3);
Assert.assertEquals(set, propertySet("uuid",
uid1, uid2, uid2, uid3));
Assert.assertThrows(IllegalArgumentException.class, () -> {
property("uuid", 123f);
}, e -> {
Assert.assertContains("Invalid property value '123.0' " +
"for key 'uuid'", e.getMessage());
Assert.assertContains(" expect a value of type UUID, " +
"actual type Float", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertyList("uuid", uid1, true);
}, e -> {
Assert.assertContains(", true]' for key 'list_uuid'",
e.getMessage());
Assert.assertContains("expect a value of type List<UUID>",
e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertySet("uuid", uid1, true);
}, e -> {
Assert.assertContains(", true]' for key 'set_uuid'",
e.getMessage());
Assert.assertContains("expect a value of type Set<UUID>",
e.getMessage());
});
}
@Test
public void testTypeBlob() {
byte[] img = new byte[]{1, 2, 8, 50, 80, 96, 110, 125, -1, -10, -100};
Assert.assertEquals(Blob.wrap(img), property("blob", img));
Object buf = Blob.wrap(img);
Assert.assertEquals(Blob.wrap(img), property("blob", buf));
buf = BytesBuffer.wrap(img).forReadAll();
Assert.assertEquals(Blob.wrap(img), property("blob", buf));
Blob bytes = Blob.wrap(new byte[]{97, 49, 50, 51, 52});
buf = ImmutableList.of((byte) 97, (byte) 49, 50, 51, 52);
Assert.assertEquals(bytes, property("blob", buf));
Object base64 = "YTEyMzQ=";
Assert.assertEquals(bytes, property("blob", base64));
Object hex = "0x6131323334";
Assert.assertEquals(bytes, property("blob", hex));
hex = "0x";
Assert.assertEquals(Blob.wrap(new byte[]{}), property("blob", hex));
Blob img1 = Blob.wrap(new byte[]{1, 2, 8, 50});
Blob img2 = Blob.wrap(new byte[]{-1, -2, -8, -50});
Blob img3 = Blob.wrap(new byte[]{1, 127, -128, 0});
List<Blob> list = ImmutableList.of(img1, img2, img2, img3);
Assert.assertEquals(list, propertyList("blob", img1, img2, img2, img3));
Set<Blob> set = ImmutableSet.of(img1, img2, img2, img3);
Assert.assertEquals(3, set.size());
Assert.assertEquals(set, propertySet("blob", img1, img2, img2, img3));
Assert.assertThrows(IllegalArgumentException.class, () -> {
// Invalid base64
property("blob", "#");
}, e -> {
Assert.assertContains("Invalid property value '#' for key 'blob'",
e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
// Invalid hex
property("blob", "0xh");
}, e -> {
Assert.assertContains("Invalid property value '0xh' for key 'blob'",
e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
property("blob", 123f);
}, e -> {
Assert.assertContains("Invalid property value '123.0' " +
"for key 'blob'", e.getMessage());
Assert.assertContains("expect a value of type Blob, " +
"actual type Float", e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
property("blob", ImmutableList.of((byte) 97, 49, 50f));
}, e -> {
Assert.assertContains("Invalid property value '[97, 49, 50.0]' " +
"for key 'blob'", e.getMessage());
Assert.assertContains("expect byte or int value, but got '50.0'",
e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertyList("blob", img1, true);
}, e -> {
Assert.assertContains("Invalid property value '[Blob{01020832}, " +
"true]' for key 'list_blob'", e.getMessage());
Assert.assertContains("expect a value of type List<Blob>",
e.getMessage());
});
Assert.assertThrows(IllegalArgumentException.class, () -> {
propertySet("blob", img1, true);
}, e -> {
Assert.assertContains("Invalid property value '[Blob{01020832}, " +
"true]' for key 'set_blob'", e.getMessage());
Assert.assertContains("expect a value of type Set<Blob>",
e.getMessage());
});
}
}
|
apache/sis | 36,587 | endorsed/src/org.apache.sis.referencing/main/org/apache/sis/referencing/factory/sql/SQLTranslator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sis.referencing.factory.sql;
import java.util.Map;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.function.UnaryOperator;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.apache.sis.util.CharSequences;
import org.apache.sis.util.OptionalCandidate;
import org.apache.sis.util.StringBuilders;
import org.apache.sis.util.resources.Errors;
import org.apache.sis.util.internal.shared.Constants;
import org.apache.sis.metadata.sql.internal.shared.Reflection;
import org.apache.sis.metadata.sql.internal.shared.SQLUtilities;
import org.apache.sis.referencing.internal.Resources;
/**
* Translator of <abbr>SQL</abbr> statements for variations in schema, table and column names.
* The {@link #apply(String)} method is invoked when a new {@link PreparedStatement}
* is about to be created from a <abbr>SQL</abbr> string.
* That method can modify the string before execution.
* For example, the following <abbr>SQL</abbr> query:
*
* <ul>
* <li>{@code SELECT * FROM "Coordinate Reference System"}</li>
* </ul>
*
* can be translated to one of the following possibilities:
*
* <ul>
* <li>{@code SELECT * FROM "Coordinate Reference System"} (no change)</li>
* <li>{@code SELECT * FROM CoordinateReferenceSystem} (without quote, so the case will be database-dependent)</li>
* <li>{@code SELECT * FROM epsg_CoordinateReferenceSystem} (same as above with {@code "epsg_"} prefix added)</li>
* </ul>
*
* Some differences are the lower or camel case, the spaces between words and the {@code "epsg_"} prefix.
* Those differences exist because the <abbr>EPSG</abbr> database is distributed in two family of formats:
* as an MS-Access file and as <abbr>SQL</abbr> scripts, and those two families use different table names.
* In addition to format-dependent differences, there is also changes in the database schema between some
* versions of the <abbr>EPSG</abbr> dataset.
*
* <h2>Table naming convention</h2>
* For readability reasons,
* Apache <abbr>SIS</abbr> generally uses the naming convention found in the MS-Access database,
* except for the cases shown in the "Name in Apache <abbr>SIS</abbr>" column of the table below.
* The <abbr>SQL</abbr> statements given to the {@link #apply(String)} method use the latter.
* The following table gives the mapping between the naming conventions:
*
* <table class="sis">
* <caption>Mapping of table names</caption>
* <tr><th>Name in <abbr>SQL</abbr> scripts</th> <th>Name in MS-Access database</th> <th>Name in Apache <abbr>SIS</abbr></th></tr>
* <tr><td>{@code epsg_alias}</td> <td>{@code Alias}</td> <td>″</td></tr>
* <tr><td>{@code epsg_area}</td> <td>{@code Area}</td> <td>″</td></tr>
* <tr><td>{@code epsg_change}</td> <td>{@code Change}</td> <td>″</td></tr>
* <tr><td>{@code epsg_conventionalrs}</td> <td>{@code ConventionalRS}</td> <td>{@code Conventional RS}</td></tr>
* <tr><td>{@code epsg_coordinateaxis}</td> <td>{@code Coordinate Axis}</td> <td>″</td></tr>
* <tr><td>{@code epsg_coordinateaxisname}</td> <td>{@code Coordinate Axis Name}</td> <td>″</td></tr>
* <tr><td>{@code epsg_coordoperation}</td> <td>{@code Coordinate_Operation}</td> <td>″</td></tr>
* <tr><td>{@code epsg_coordoperationmethod}</td> <td>{@code Coordinate_Operation Method}</td> <td>″</td></tr>
* <tr><td>{@code epsg_coordoperationparam}</td> <td>{@code Coordinate_Operation Parameter}</td> <td>″</td></tr>
* <tr><td>{@code epsg_coordoperationparamusage}</td> <td>{@code Coordinate_Operation Parameter Usage}</td><td>″</td></tr>
* <tr><td>{@code epsg_coordoperationparamvalue}</td> <td>{@code Coordinate_Operation Parameter Value}</td><td>″</td></tr>
* <tr><td>{@code epsg_coordoperationpath}</td> <td>{@code Coordinate_Operation Path}</td> <td>″</td></tr>
* <tr><td>{@code epsg_coordinatereferencesystem}</td><td>{@code Coordinate Reference System}</td> <td>″</td></tr>
* <tr><td>{@code epsg_coordinatesystem}</td> <td>{@code Coordinate System}</td> <td>″</td></tr>
* <tr><td>{@code epsg_datum}</td> <td>{@code Datum}</td> <td>″</td></tr>
* <tr><td>{@code epsg_datumensemble}</td> <td>{@code DatumEnsemble}</td> <td>{@code Datum Ensemble}</td></tr>
* <tr><td>{@code epsg_datumensemblemember}</td> <td>{@code DatumEnsembleMember}</td> <td>{@code Datum Ensemble Member}</td></tr>
* <tr><td>{@code epsg_datumrealizationmethod}</td> <td>{@code DatumRealizationMethod}</td> <td>{@code Datum Realization Method}</td></tr>
* <tr><td>{@code epsg_definingoperation}</td> <td>{@code DefiningOperation}</td> <td>{@code Defining Operation}</td></tr>
* <tr><td>{@code epsg_deprecation}</td> <td>{@code Deprecation}</td> <td>″</td></tr>
* <tr><td>{@code epsg_ellipsoid}</td> <td>{@code Ellipsoid}</td> <td>″</td></tr>
* <tr><td>{@code epsg_extent}</td> <td>{@code Extent}</td> <td>″</td></tr>
* <tr><td>{@code epsg_namingsystem}</td> <td>{@code Naming System}</td> <td>″</td></tr>
* <tr><td>{@code epsg_primemeridian}</td> <td>{@code Prime Meridian}</td> <td>″</td></tr>
* <tr><td>{@code epsg_scope}</td> <td>{@code Scope}</td> <td>″</td></tr>
* <tr><td>{@code epsg_supersession}</td> <td>{@code Supersession}</td> <td>″</td></tr>
* <tr><td>{@code epsg_unitofmeasure}</td> <td>{@code Unit of Measure}</td> <td>″</td></tr>
* <tr><td>{@code epsg_versionhistory}</td> <td>{@code Version History}</td> <td>″</td></tr>
* <tr><td>{@code epsg_usage}</td> <td>{@code Usage}</td> <td>″</td></tr>
* </table>
*
* Columns have the same name in all formats, with only one exception:
* for avoiding confusion with the <abbr>SQL</abbr> keyword of the same name,
* the {@code ORDER} column in MS-Access has been renamed {@code coord_axis_order} in <abbr>SQL</abbr> scripts.
* Apache <abbr>SIS</abbr> uses the latter.
*
* <p>Apache <abbr>SIS</abbr> automatically detects which name convention is used, regardless the database engine.
* For example, it is legal to use the mixed-case variant in a PostgreSQL database
* even if <abbr>EPSG</abbr> distributes the PostgreSQL scripts in lower-case.
* The {@code "epsg_"} prefix is redundant with database schema and can be omitted.
* {@code SQLTranslator} automatically detects which database schema contains the <abbr>EPSG</abbr> tables.</p>
*
* <h2>Versions of <abbr>EPSG</abbr> schema</h2>
* Apache <abbr>SIS</abbr> assumes an <abbr>EPSG</abbr> database schema version 10 or latter.
* If {@link EPSGFactory} is connected to the <abbr>EPSG</abbr> version 9 database,
* then this {@code SQLTranslator} class will modify the <abbr>SQL</abbr> statements on-the-fly.
*
* <h2>Thread safety</h2>
* All {@code SQLTranslator} instances given to the {@link EPSGFactory} constructor
* <strong>shall</strong> be immutable and thread-safe.
*
* @author Rueben Schulz (UBC)
* @author Martin Desruisseaux (IRD, Geomatys)
* @author Didier Richard (IGN)
* @author John Grange
* @version 1.5
* @since 0.7
*/
public class SQLTranslator implements UnaryOperator<String> {
/**
* The prefix in table names. The SQL scripts are provided by EPSG with this prefix in front of all table names.
* SIS rather uses a modified version of those SQL scripts which creates the tables in an "EPSG" database schema.
* But we still need to check for existence of this prefix in case someone used the original SQL scripts.
*
* @see #usePrefixedTableNames
*/
static final String TABLE_PREFIX = "epsg_";
/**
* The column where {@code VARCHAR} value may need to be cast to an enumeration.
* With PostgreSQL, only columns in the {@code WHERE} part of the <abbr>SQL</abbr> statement
* needs an explicit cast, as the columns in the {@code SELECT} part are implicitly cast.
*/
private static final String ENUMERATION_COLUMN = "OBJECT_TABLE_NAME"; // In "Alias" table.
/**
* The name of the catalog that contains the EPSG tables, or {@code null} or an empty string.
* <ul>
* <li>The {@code ""} value retrieves the <abbr>EPSG</abbr> schema without a catalog.</li>
* <li>The {@code null} value means that the catalog name should not be used to narrow the search.</li>
* </ul>
*
* @see #getCatalog()
*/
private String catalog;
/**
* The name of the schema that contains the EPSG tables, or {@code null} or an empty string.
* <ul>
* <li>The {@code ""} value retrieves the EPSG tables without a schema.
* In such case, table names are typically prefixed by {@value #TABLE_PREFIX}.</li>
* <li>The {@code null} value means that the schema name should not be used to narrow the search.
* In such case, {@code SQLTranslator} will try to automatically detect the schema.</li>
* </ul>
*
* Note that the <abbr>SQL</abbr> scripts distributed by <abbr>EPSG</abbr> do not use schema.
* Instead, <abbr>EPSG</abbr> puts an {@value #TABLE_PREFIX} prefix in front of every table names.
* The {@link #usePrefixedTableNames} flag tells whether it is the case for the current database.
* The two approaches (schema or prefix) are redundant, but it is okay to use both of them anyway.
*
* @see #getSchema()
* @see #usePrefixedTableNames
*/
private String schema;
/**
* Whether the table names are prefixed by {@value #TABLE_PREFIX}. The <abbr>EPSG</abbr> geodetic dataset
* in the {@code org.apache.sis.referencing.epsg} module replaces that prefix by the {@code "epsg"} schema.
* However, if the dataset has been installed manually by the user, then the table name prefix is present.
*
* @see #TABLE_PREFIX
* @see #schema
*/
private boolean usePrefixedTableNames;
/**
* {@code true} if this class uses mixed-case convention for table names.
* In such case, the table names will need to be quoted using the {@link #quote} character.
*/
private boolean useMixedCaseTableNames;
/**
* Mapping from mixed-case "word" used by {@link EPSGDataAccess} to the words actually used by the database.
* A word may be a table name or a part of it. A table name may consist of many words separated by spaces.
* This map does not list all tables used in <abbr>EPSG</abbr> schema, but only the ones that cannot be mapped
* by more generic code (e.g. by replacing spaces by '_').
*
* <p>The keys are names that are hard-coded in the <abbr>SQL</abbr> statements of {@link EPSGDataAccess} class,
* and values are the names used in the <abbr>EPSG</abbr> database on which {@link EPSGDataAccess} is connected.
* By convention, all column names are in upper-case while table names are in mixed-case characters.</p>
*/
private Map<String,String> tableRewording;
/**
* Replacements to perform on <abbr>SQL</abbr> statements before execution. Some entries are the replacements
* of column names used by {@link EPSGDataAccess} to the names actually used in the target database. The main
* case is the {@code COORD_AXIS_ORDER} column which may be named {@code ORDER} in the dataset for MS-Access.
* Other entries are replacements of missing columns by {@code CAST(NULL AS …)} expressions and replacements
* of {@code BOOLEAN} comparator operands by {@code SMALLINT}.
*/
private Map<String,String> replacements;
/**
* The characters used for quoting identifiers, or an empty string if none.
* This information is provided by {@link DatabaseMetaData#getIdentifierQuoteString()}.
*/
private final String identifierQuote;
/**
* The string that can be used to escape wildcard characters in {@code LIKE}.
* This is the value returned by {@link DatabaseMetaData#getSearchStringEscape()}.
* It may be null or empty if the database has no escape character.
*/
final String wildcardEscape;
/**
* Non-null if the {@value #ENUMERATION_COLUMN} column in {@code "Alias"} table uses enumeration instead
* than character varying. In such case, this field contains the enumeration type. If {@code null}, then
* then column type is {@code VARCHAR} and the cast can be omitted.
* If non-null, this string should contain the identifier quotes.
*/
private String tableNameEnum;
/**
* {@code true} if the database uses the {@code BOOLEAN} type instead of {@code SMALLINT}
* for the {@code show_crs}, {@code show_operation} and all {@code deprecated} fields.
*
* @see #useBoolean()
*/
private boolean useBoolean;
/**
* Whether the sentinel table {@code "Coordinate_Operation"} or a variant has been found.
* If {@code false}, then {@link EPSGInstaller} needs to be run.
* Note that the {@linkplain #schema} may be {@code null}.
*
* @see #isSchemaFound()
*/
private boolean isSchemaFound;
/**
* Whether the "Usage" table has been found.
* That table has been added in version 10 of <abbr>EPSG</abbr> database.
*
* @see #isUsageTableFound()
*/
private boolean isUsageTableFound;
/**
* Whether the table names in the hard-coded <abbr>SQL</abbr> queries and in the actual database are the same.
* If {@code true}, then the renaming of tables can be skipped.
*/
private boolean sameTableNames;
/**
* Whether the <abbr>SQL</abbr> queries hard-coded in {@link EPSGDataAccess} can be used verbatim
* with the actual database. This is {@code true} if this translator applies no change at all.
*/
private boolean sameQueries;
/**
* Creates a new <abbr>SQL</abbr> translator for the database described by the given metadata.
* This constructor detects automatically the dialect: the characters to use for quoting identifiers,
* and whether the <abbr>EPSG</abbr> table names uses the mixed-case or lower-case convention.
*
* <p>If the given catalog or schema name is non-null, then the {@linkplain DatabaseMetaData#getTables
* search for EPSG tables} will be restricted to the catalog or schema of that name.
* An empty string ({@code ""}) means to search for tables without catalog or schema.
* A {@code null} value means that the catalog or schema should not be used to narrow the search.</p>
*
* @param md information about the database.
* @param catalog the catalog where to look for EPSG schema, or {@code null} if any.
* @param schema the schema where to look for EPSG tables, or {@code null} if any.
* @throws SQLException if an error occurred while querying the database metadata.
*/
public SQLTranslator(final DatabaseMetaData md, final String catalog, final String schema) throws SQLException {
identifierQuote = md.getIdentifierQuoteString().trim();
wildcardEscape = md.getSearchStringEscape();
this.catalog = catalog;
this.schema = schema;
setup(md);
}
/**
* Sets the value of all non-final fields. This method performs the following steps:
*
* <ol class="verbose">
* <li>Find the schema that seems to contain the <abbr>EPSG</abbr> tables.
* If there is more than one schema containing the tables, give precedence to the schema named
* {@code "EPSG"} (ignoring case), or an arbitrary schema if none has been found with that name.
* The schema name may be the empty string if the tables are not contained in a schema.</li>
*
* <li>Determine whether the table names are prefixed by {@value #TABLE_PREFIX}
* and whether table names are in lower-case or mixed-case.</li>
*
* <li>Fill the {@link #tableRewording} and {@link #replacements} maps. These maps translate table
* and column names used in the <abbr>SQL</abbr> statements into the names used by the database.
* Two conventions are understood: the names used in the MS-Access database or the names used
* in the <abbr>SQL</abbr> scripts, potentially with {@linkplain #TABLE_PREFIX prefix} removed.</li>
* </ol>
*/
@SuppressWarnings("fallthrough")
final void setup(final DatabaseMetaData md) throws SQLException {
String schemaPattern = SQLUtilities.escape(schema, wildcardEscape);
int tableIndex = 0;
do {
usePrefixedTableNames = false;
useMixedCaseTableNames = false;
String table = "";
switch (tableIndex++) {
case 0: { // Test EPSG standard table name first.
usePrefixedTableNames = true;
table = SQLUtilities.escape(TABLE_PREFIX, wildcardEscape);
// Fallthrough for testing "epsg_coordoperation".
}
case 2: {
table += "coordoperation"; // Prefixed by "epsg_" in case 0.
if (md.storesUpperCaseIdentifiers()) {
table = table.toUpperCase(Locale.US);
}
break;
}
case 1: { // Variant used by the Apache SIS installer.
useMixedCaseTableNames = true;
table = "Coordinate_Operation";
break;
}
default: return; // EPSG table not found.
}
try (ResultSet result = md.getTables(catalog, schemaPattern, table, null)) {
while (result.next()) {
isSchemaFound = true;
catalog = result.getString(Reflection.TABLE_CAT);
schema = result.getString(Reflection.TABLE_SCHEM);
if (result.wasNull()) schema = "";
if (Constants.EPSG.equalsIgnoreCase(schema)) {
break; // Give precedence to "epsg" schema.
}
}
}
} while (!isSchemaFound);
/*
* At this point, we found the EPSG sentinel table and we identified the
* naming convention (unquoted or mixed-case, prefixed by "epsg_" or not).
*/
UnaryOperator<String> toNativeCase = UnaryOperator.identity();
schemaPattern = SQLUtilities.escape(schema, wildcardEscape);
tableRewording = new HashMap<>();
replacements = new HashMap<>();
/*
* Special cases not covered by the generic algorithm implemented in `toActualTableName(…)`.
* The entries are actually not full table names, but words separated by space. For example,
* "Coordinate_Operation Parameter Value" will be renamed "epsg_CoordOperationParamValue"
* (note that this renaming combines the two entries of the map).
*/
if (!useMixedCaseTableNames) {
tableRewording.put("Coordinate_Operation", "coordoperation");
tableRewording.put("Parameter", "param");
if (md.storesLowerCaseIdentifiers()) {
toNativeCase = (table) -> table.toLowerCase(Locale.US);
} else if (md.storesUpperCaseIdentifiers()) {
toNativeCase = (table) -> table.toUpperCase(Locale.US);
}
}
/*
* Check if some columns need to be renamed in SQL queries. For example, MS-Access database
* uses a column named "ORDER" instead of "COORD_AXIS_ORDER" in the "Coordinate Axis" table.
* The other changes are differences between EPSG version 9 and version 10. For example,
* column "BASE_CRS_CODE" in EPSG version 10 was named "SOURCE_GEOGCRS_CODE" in version 9.
*
* Furthermore, some columns in EPSG version 10 did not existed in EPSG version 9.
* This loop also checks for columns that do not exist, and replaces them by NULL constant.
*/
final var missingColumns = new HashMap<String, String>();
final var mayRenameColumns = new HashMap<String, String>();
final var brokenTargetCols = new HashSet<String>();
tableIndex = 0;
check: for (;;) {
String table;
boolean isUsage = false; // "Usage" is a new table in EPSG version 19.
boolean isArea = false; // "Area" was a table name used in EPSG version 9.
boolean mayReuse = false; // If true, do not clear the maps if the table was not found.
switch (tableIndex++) {
case 0: {
table = "Coordinate Axis";
mayRenameColumns.put("COORD_AXIS_ORDER", "ORDER"); // SQL script → MS-Access.
break;
}
case 1: {
table = "Coordinate_Operation";
missingColumns.put("AREA_OF_USE_CODE", "INTEGER"); // Defined in version 9, deprecated in 10+.
missingColumns.put("COORD_OP_SCOPE", "CHAR(1)"); // Idem.
break;
}
case 2: {
table = "Coordinate Reference System";
mayRenameColumns.put("BASE_CRS_CODE", "SOURCE_GEOGCRS_CODE"); // EPSG version 10 → version 9.
missingColumns .put("AREA_OF_USE_CODE", "INTEGER"); // Defined in version 9, deprecated in 10+.
missingColumns .put("CRS_SCOPE", "CHAR(1)"); // Idem.
break;
}
case 3: {
table = "Datum";
mayRenameColumns.put("PUBLICATION_DATE", "REALIZATION_EPOCH"); // EPSG version 10 → version 9.
missingColumns .put("ANCHOR_EPOCH", "DOUBLE PRECISION");
missingColumns .put("FRAME_REFERENCE_EPOCH", "DOUBLE PRECISION");
missingColumns .put("REALIZATION_METHOD_CODE", "INTEGER");
missingColumns .put("CONVENTIONAL_RS_CODE", "INTEGER");
missingColumns .put("AREA_OF_USE_CODE", "INTEGER"); // Defined in version 9, deprecated in 10+.
missingColumns .put("DATUM_SCOPE", "CHAR(1)"); // Idem.
break;
}
case 4: {
table = "Extent"; // "Area" in 9, "Extent" in 10.
mayRenameColumns.put("EXTENT_CODE", "AREA_CODE"); // EPSG version 10 → version 9.
mayRenameColumns.put("EXTENT_NAME", "AREA_NAME");
mayRenameColumns.put("EXTENT_DESCRIPTION", "AREA_OF_USE");
mayRenameColumns.put("BBOX_SOUTH_BOUND_LAT", "AREA_SOUTH_BOUND_LAT");
mayRenameColumns.put("BBOX_NORTH_BOUND_LAT", "AREA_NORTH_BOUND_LAT");
mayRenameColumns.put("BBOX_WEST_BOUND_LON", "AREA_WEST_BOUND_LON");
mayRenameColumns.put("BBOX_EAST_BOUND_LON", "AREA_EAST_BOUND_LON");
missingColumns .put("VERTICAL_EXTENT_MIN", "DOUBLE PRECISION");
missingColumns .put("VERTICAL_EXTENT_MAX", "DOUBLE PRECISION");
missingColumns .put("VERTICAL_EXTENT_CRS_CODE", "INTEGER");
missingColumns .put("TEMPORAL_EXTENT_BEGIN", "CHAR(1)");
missingColumns .put("TEMPORAL_EXTENT_END", "CHAR(1)");
mayReuse = true;
break;
}
case 5: {
if (mayRenameColumns.isEmpty()) continue; // "Extent" table has been found.
isArea = true;
table = "Area";
break;
}
case 6: {
isUsage = true;
table = "Usage";
break;
}
case 7: {
if (isUsageTableFound) break check; // The check of `ENUMERATION_COLUMN` is already done.
table = "Alias"; // For checking the type of the `ENUMERATION_COLUMN`.
break;
}
default: break check;
}
boolean isTableFound = false;
brokenTargetCols.addAll(mayRenameColumns.values());
table = toNativeCase.apply(toActualTableName(table));
try (ResultSet result = md.getColumns(catalog, schemaPattern, SQLUtilities.escape(table, wildcardEscape), "%")) {
while (result.next()) {
isTableFound = true; // Assuming that all tables contain at least one column.
final String column = result.getString(Reflection.COLUMN_NAME).toUpperCase(Locale.US);
missingColumns.remove(column);
if (mayRenameColumns.remove(column) == null) { // Do not rename if the new column exists.
brokenTargetCols.remove(column); // Remember which old names were found.
}
/*
* Detect if the database uses boolean types where applicable.
* We arbitrarily use the `deprecated` column as a representative value.
*/
if ("DEPRECATED".equals(column)) {
final int type = result.getInt(Reflection.DATA_TYPE);
useBoolean |= (type == Types.BOOLEAN) || (type == Types.BIT);
}
/*
* Detect if the tables use enumeration (on PostgreSQL database) instead of VARCHAR.
* Enumerations appear in various tables, including in a WHERE clause for the Alias table.
* Note: we cannot rely on `result.getInt(Reflection.DATA_TYPE)` because the declared type
* of enumeration is `Types.VARCHAR` (at least on PostgresSQL)`.
*/
if (ENUMERATION_COLUMN.equals(column)) {
String type = result.getString(Reflection.TYPE_NAME);
if (!(CharSequences.startsWith(type, "VARCHAR", true) || CharSequences.startsWith(type, "CHARACTER", true))) {
if (!type.contains(identifierQuote)) {
type = identifierQuote + type + identifierQuote;
}
tableNameEnum = type;
}
}
}
}
if (isTableFound) {
isUsageTableFound |= isUsage;
if (isArea) {
tableRewording.put("Extent", "Area");
}
missingColumns.forEach((column, type) -> {
replacements.put(column, "CAST(NULL AS " + type + ") AS " + column);
});
mayRenameColumns.values().removeAll(brokenTargetCols); // For renaming only when the old name has been found.
replacements.putAll(mayRenameColumns);
mayReuse = false;
}
if (!mayReuse) {
mayRenameColumns.clear();
brokenTargetCols.clear();
missingColumns.clear();
}
}
/*
* If the database uses the SMALLINT type instead of BOOLEAN, replace `DEPRECATED=FALSE` by `DEPRECATED=0`.
* Note: is does not cover all cases. Some more complex cases are handled in `if (useBoolean())` blocks.
*/
if (!useBoolean) {
replacements.put("=FALSE", "=0");
replacements.put("=TRUE", "<>0");
}
replacements = Map.copyOf(replacements);
tableRewording = Map.copyOf(tableRewording);
sameTableNames = useMixedCaseTableNames && "\"".equals(identifierQuote) && tableRewording.isEmpty();
sameQueries = sameTableNames && useBoolean && (tableNameEnum == null) && replacements.isEmpty();
}
/**
* Returns the catalog that contains the EPSG schema. This is the catalog specified at construction time
* if it was non-null, or the catalog discovered by the constructor otherwise.
* Note that this method may still return {@code null} if the EPSG tables were not found or if the database
* does not {@linkplain DatabaseMetaData#supportsCatalogsInDataManipulation() supports catalogs}.
*
* @return the catalog that contains the EPSG schema, or {@code null}.
*/
@OptionalCandidate
public String getCatalog() {
return catalog;
}
/**
* Returns the schema that contains the EPSG tables. This is the schema specified at construction time
* if it was non-null, or the schema discovered by the constructor otherwise.
* Note that this method may still return {@code null} if the EPSG tables were not found or if the database
* does not {@linkplain DatabaseMetaData#supportsSchemasInDataManipulation() supports schemas}.
*
* @return the schema that contains the EPSG tables, or {@code null}.
*/
@OptionalCandidate
public String getSchema() {
return schema;
}
/**
* Returns whether the <abbr>EPSG</abbr> tables have been found.
* If {@code false}, then {@link EPSGInstaller} needs to be run.
* Note that the {@linkplain #getSchema() schema} may be {@code null}.
*/
final boolean isSchemaFound() {
return isSchemaFound;
}
/**
* Returns whether the "Usage" table has been found.
* That table has been added in version 10 of <abbr>EPSG</abbr> database.
*/
final boolean isUsageTableFound() {
return isUsageTableFound;
}
/**
* Returns the error message for the exception to throw if the EPSG tables are not found and we cannot create them.
*/
static String tableNotFound(final DatabaseMetaData md, final Locale locale) throws SQLException {
String db = md.getURL();
if (db == null) {
db = "?";
} else {
int s = db.indexOf('?');
if (s >= 0 || (s = db.indexOf('#')) >= 0) {
db = db.substring(9, s);
}
}
return Resources.forLocale(locale).getString(Resources.Keys.TableNotFound_3,
Constants.EPSG, db, "Coordinate_Operation");
}
/**
* Returns {@code true} if the database uses the {@code BOOLEAN} type instead of {@code SMALLINT}
* for the {@code show_crs}, {@code show_operation} and all {@code deprecated} fields.
*/
final boolean useBoolean() {
return useBoolean;
}
/**
* Converts a mixed-case table name to the convention used in the database.
* The names of the tables for the two conventions are listed in a table in the Javadoc of this class.
* The returned string does not include the identifier quotes.
*
* @param name the mixed-case table name, without quotes.
* @return the name converted to the convention used by the database.
*
* @since 1.5
*/
public final String toActualTableName(String name) {
if (useMixedCaseTableNames) {
return name;
}
final var buffer = new StringBuilder(name.length() + 5);
toActualTableName(name, buffer);
return buffer.toString().toLowerCase(Locale.US);
}
/**
* Appends the table name in the given buffer, converted to the convention used in the database.
* Identifier quotes are added when mixed-case is used. Otherwise, the identifier may not be in
* the right lower/upper case. But when there is no identifier quotes, the database should convert
* to* whatever convention it uses.
*/
private void toActualTableName(final String name, final StringBuilder buffer) {
if (useMixedCaseTableNames) {
buffer.append(identifierQuote)
.append(tableRewording.getOrDefault(name, name))
.append(identifierQuote);
} else {
if (usePrefixedTableNames) {
buffer.append(TABLE_PREFIX);
}
for (final String word : name.split("\\s")) {
buffer.append(tableRewording.getOrDefault(word, word));
}
// Ignore lower/upper case.
}
}
/**
* Adapts the given <abbr>SQL</abbr> statement from the mixed-case convention to the convention used by
* the target database. The mixed-case convention is used by {@link EPSGDataAccess} hard-coded queries.
* This method can replace the schema and table names, and sometime some <abbr>SQL</abbr> keywords,
* for complying with the expectation of the target database.
*
* @param sql a <abbr>SQL</abbr> statement with table names in mixed-case convention.
* @return the given statement adapted to the expectation of the target database.
*/
@Override
public String apply(final String sql) {
if (sameQueries) {
return sql; // Shortcut when there is nothing to change.
}
final var buffer = new StringBuilder(sql.length() + 16);
int end = 0;
if (!sameTableNames) {
int start;
while ((start = sql.indexOf('"', end)) >= 0) {
/*
* Append every characters since the end of the last processed table/column name,
* or since the beginning of the SQL statement if we are in the first iteration.
* Then find the end of the new table/column name to process in this iteration.
*/
buffer.append(sql, end, start);
if ((end = sql.indexOf('"', ++start)) < 0) {
throw new IllegalArgumentException(Errors.format(
Errors.Keys.MissingCharacterInElement_2, sql.substring(start), '"'));
}
toActualTableName(sql.substring(start, end++), buffer);
}
}
buffer.append(sql, end, sql.length());
replacements.forEach((toSearch, replaceBy) -> StringBuilders.replace(buffer, toSearch, replaceBy));
/*
* If the database uses enumeration, we need an explicit cast with PostgreSQL.
* The enumeration type is typically "EPSG"."Table Name".
*/
if (tableNameEnum != null) {
int w = buffer.lastIndexOf(ENUMERATION_COLUMN + "=?");
if (w >= 0) {
w += ENUMERATION_COLUMN.length() + 1;
buffer.replace(w, w+1, "CAST(? AS " + tableNameEnum + ')');
}
}
return buffer.toString();
}
}
|
googleapis/google-cloud-java | 36,250 | java-batch/proto-google-cloud-batch-v1/src/main/java/com/google/cloud/batch/v1/ListJobsRequest.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/batch/v1/batch.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.batch.v1;
/**
*
*
* <pre>
* ListJob Request.
* </pre>
*
* Protobuf type {@code google.cloud.batch.v1.ListJobsRequest}
*/
public final class ListJobsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.batch.v1.ListJobsRequest)
ListJobsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListJobsRequest.newBuilder() to construct.
private ListJobsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListJobsRequest() {
parent_ = "";
filter_ = "";
orderBy_ = "";
pageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListJobsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.batch.v1.BatchProto
.internal_static_google_cloud_batch_v1_ListJobsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.batch.v1.BatchProto
.internal_static_google_cloud_batch_v1_ListJobsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.batch.v1.ListJobsRequest.class,
com.google.cloud.batch.v1.ListJobsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Parent path.
* </pre>
*
* <code>string parent = 1;</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>
* Parent path.
* </pre>
*
* <code>string parent = 1;</code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* List filter.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* List filter.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORDER_BY_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Optional. Sort results. Supported are "name", "name desc", "create_time",
* and "create_time desc".
* </pre>
*
* <code>string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The orderBy.
*/
@java.lang.Override
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. Sort results. Supported are "name", "name desc", "create_time",
* and "create_time desc".
* </pre>
*
* <code>string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for orderBy.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* Page size.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, orderBy_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, orderBy_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.batch.v1.ListJobsRequest)) {
return super.equals(obj);
}
com.google.cloud.batch.v1.ListJobsRequest other =
(com.google.cloud.batch.v1.ListJobsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (!getOrderBy().equals(other.getOrderBy())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + ORDER_BY_FIELD_NUMBER;
hash = (53 * hash) + getOrderBy().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.batch.v1.ListJobsRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.batch.v1.ListJobsRequest 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.batch.v1.ListJobsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.batch.v1.ListJobsRequest 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.batch.v1.ListJobsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.batch.v1.ListJobsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.batch.v1.ListJobsRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.batch.v1.ListJobsRequest 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.batch.v1.ListJobsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.batch.v1.ListJobsRequest 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.batch.v1.ListJobsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.batch.v1.ListJobsRequest 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.batch.v1.ListJobsRequest 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>
* ListJob Request.
* </pre>
*
* Protobuf type {@code google.cloud.batch.v1.ListJobsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.batch.v1.ListJobsRequest)
com.google.cloud.batch.v1.ListJobsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.batch.v1.BatchProto
.internal_static_google_cloud_batch_v1_ListJobsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.batch.v1.BatchProto
.internal_static_google_cloud_batch_v1_ListJobsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.batch.v1.ListJobsRequest.class,
com.google.cloud.batch.v1.ListJobsRequest.Builder.class);
}
// Construct using com.google.cloud.batch.v1.ListJobsRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
filter_ = "";
orderBy_ = "";
pageSize_ = 0;
pageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.batch.v1.BatchProto
.internal_static_google_cloud_batch_v1_ListJobsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.batch.v1.ListJobsRequest getDefaultInstanceForType() {
return com.google.cloud.batch.v1.ListJobsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.batch.v1.ListJobsRequest build() {
com.google.cloud.batch.v1.ListJobsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.batch.v1.ListJobsRequest buildPartial() {
com.google.cloud.batch.v1.ListJobsRequest result =
new com.google.cloud.batch.v1.ListJobsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.batch.v1.ListJobsRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.filter_ = filter_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.orderBy_ = orderBy_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.pageToken_ = pageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.batch.v1.ListJobsRequest) {
return mergeFrom((com.google.cloud.batch.v1.ListJobsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.batch.v1.ListJobsRequest other) {
if (other == com.google.cloud.batch.v1.ListJobsRequest.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getOrderBy().isEmpty()) {
orderBy_ = other.orderBy_;
bitField0_ |= 0x00000004;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000010;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000008;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000010;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 34
case 42:
{
orderBy_ = input.readStringRequireUtf8();
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 java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Parent path.
* </pre>
*
* <code>string parent = 1;</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>
* Parent path.
* </pre>
*
* <code>string parent = 1;</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>
* Parent path.
* </pre>
*
* <code>string parent = 1;</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>
* Parent path.
* </pre>
*
* <code>string parent = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Parent path.
* </pre>
*
* <code>string parent = 1;</code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* List filter.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* List filter.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* List filter.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* List filter.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* List filter.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Optional. Sort results. Supported are "name", "name desc", "create_time",
* and "create_time desc".
* </pre>
*
* <code>string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The orderBy.
*/
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. Sort results. Supported are "name", "name desc", "create_time",
* and "create_time desc".
* </pre>
*
* <code>string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for orderBy.
*/
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. Sort results. Supported are "name", "name desc", "create_time",
* and "create_time desc".
* </pre>
*
* <code>string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderBy(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
orderBy_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Sort results. Supported are "name", "name desc", "create_time",
* and "create_time desc".
* </pre>
*
* <code>string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearOrderBy() {
orderBy_ = getDefaultInstance().getOrderBy();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Sort results. Supported are "name", "name desc", "create_time",
* and "create_time desc".
* </pre>
*
* <code>string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderByBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
orderBy_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Page size.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Page size.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Page size.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000008);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
return this;
}
/**
*
*
* <pre>
* Page token.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.batch.v1.ListJobsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.batch.v1.ListJobsRequest)
private static final com.google.cloud.batch.v1.ListJobsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.batch.v1.ListJobsRequest();
}
public static com.google.cloud.batch.v1.ListJobsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListJobsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListJobsRequest>() {
@java.lang.Override
public ListJobsRequest 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<ListJobsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListJobsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.batch.v1.ListJobsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,475 | java-visionai/proto-google-cloud-visionai-v1/src/main/java/com/google/cloud/visionai/v1/DataSchema.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/visionai/v1/warehouse.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.visionai.v1;
/**
*
*
* <pre>
* Data schema indicates how the user specified annotation is interpreted in the
* system.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.DataSchema}
*/
public final class DataSchema extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.visionai.v1.DataSchema)
DataSchemaOrBuilder {
private static final long serialVersionUID = 0L;
// Use DataSchema.newBuilder() to construct.
private DataSchema(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DataSchema() {
name_ = "";
key_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new DataSchema();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_DataSchema_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_DataSchema_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.DataSchema.class,
com.google.cloud.visionai.v1.DataSchema.Builder.class);
}
private int bitField0_;
public static final int NAME_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object name_ = "";
/**
*
*
* <pre>
* Resource name of the data schema in the form of:
* `projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema}`
* where {data_schema} part should be the same as the `key` field below.
* </pre>
*
* <code>string name = 1;</code>
*
* @return The name.
*/
@java.lang.Override
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
*
*
* <pre>
* Resource name of the data schema in the form of:
* `projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema}`
* where {data_schema} part should be the same as the `key` field below.
* </pre>
*
* <code>string name = 1;</code>
*
* @return The bytes for name.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int KEY_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object key_ = "";
/**
*
*
* <pre>
* Required. The key of this data schema. This key should be matching the key
* of user specified annotation and unique inside corpus. This value can be up
* to 63 characters, and valid characters are /[a-z][0-9]-/. The first
* character must be a letter, the last could be a letter or a number.
* </pre>
*
* <code>string key = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The key.
*/
@java.lang.Override
public java.lang.String getKey() {
java.lang.Object ref = key_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
key_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The key of this data schema. This key should be matching the key
* of user specified annotation and unique inside corpus. This value can be up
* to 63 characters, and valid characters are /[a-z][0-9]-/. The first
* character must be a letter, the last could be a letter or a number.
* </pre>
*
* <code>string key = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for key.
*/
@java.lang.Override
public com.google.protobuf.ByteString getKeyBytes() {
java.lang.Object ref = key_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
key_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SCHEMA_DETAILS_FIELD_NUMBER = 3;
private com.google.cloud.visionai.v1.DataSchemaDetails schemaDetails_;
/**
*
*
* <pre>
* The schema details mapping to the key.
* </pre>
*
* <code>.google.cloud.visionai.v1.DataSchemaDetails schema_details = 3;</code>
*
* @return Whether the schemaDetails field is set.
*/
@java.lang.Override
public boolean hasSchemaDetails() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The schema details mapping to the key.
* </pre>
*
* <code>.google.cloud.visionai.v1.DataSchemaDetails schema_details = 3;</code>
*
* @return The schemaDetails.
*/
@java.lang.Override
public com.google.cloud.visionai.v1.DataSchemaDetails getSchemaDetails() {
return schemaDetails_ == null
? com.google.cloud.visionai.v1.DataSchemaDetails.getDefaultInstance()
: schemaDetails_;
}
/**
*
*
* <pre>
* The schema details mapping to the key.
* </pre>
*
* <code>.google.cloud.visionai.v1.DataSchemaDetails schema_details = 3;</code>
*/
@java.lang.Override
public com.google.cloud.visionai.v1.DataSchemaDetailsOrBuilder getSchemaDetailsOrBuilder() {
return schemaDetails_ == null
? com.google.cloud.visionai.v1.DataSchemaDetails.getDefaultInstance()
: schemaDetails_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(key_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, key_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(3, getSchemaDetails());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(key_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, key_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getSchemaDetails());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.visionai.v1.DataSchema)) {
return super.equals(obj);
}
com.google.cloud.visionai.v1.DataSchema other = (com.google.cloud.visionai.v1.DataSchema) obj;
if (!getName().equals(other.getName())) return false;
if (!getKey().equals(other.getKey())) return false;
if (hasSchemaDetails() != other.hasSchemaDetails()) return false;
if (hasSchemaDetails()) {
if (!getSchemaDetails().equals(other.getSchemaDetails())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (37 * hash) + KEY_FIELD_NUMBER;
hash = (53 * hash) + getKey().hashCode();
if (hasSchemaDetails()) {
hash = (37 * hash) + SCHEMA_DETAILS_FIELD_NUMBER;
hash = (53 * hash) + getSchemaDetails().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.visionai.v1.DataSchema parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.DataSchema parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.visionai.v1.DataSchema parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.DataSchema parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.visionai.v1.DataSchema parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.DataSchema parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.visionai.v1.DataSchema parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.DataSchema parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.visionai.v1.DataSchema parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.DataSchema parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.visionai.v1.DataSchema parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.DataSchema parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.visionai.v1.DataSchema prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Data schema indicates how the user specified annotation is interpreted in the
* system.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.DataSchema}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.visionai.v1.DataSchema)
com.google.cloud.visionai.v1.DataSchemaOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_DataSchema_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_DataSchema_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.DataSchema.class,
com.google.cloud.visionai.v1.DataSchema.Builder.class);
}
// Construct using com.google.cloud.visionai.v1.DataSchema.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getSchemaDetailsFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
name_ = "";
key_ = "";
schemaDetails_ = null;
if (schemaDetailsBuilder_ != null) {
schemaDetailsBuilder_.dispose();
schemaDetailsBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_DataSchema_descriptor;
}
@java.lang.Override
public com.google.cloud.visionai.v1.DataSchema getDefaultInstanceForType() {
return com.google.cloud.visionai.v1.DataSchema.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.visionai.v1.DataSchema build() {
com.google.cloud.visionai.v1.DataSchema result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.visionai.v1.DataSchema buildPartial() {
com.google.cloud.visionai.v1.DataSchema result =
new com.google.cloud.visionai.v1.DataSchema(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.visionai.v1.DataSchema result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.name_ = name_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.key_ = key_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.schemaDetails_ =
schemaDetailsBuilder_ == null ? schemaDetails_ : schemaDetailsBuilder_.build();
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.visionai.v1.DataSchema) {
return mergeFrom((com.google.cloud.visionai.v1.DataSchema) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.visionai.v1.DataSchema other) {
if (other == com.google.cloud.visionai.v1.DataSchema.getDefaultInstance()) return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getKey().isEmpty()) {
key_ = other.key_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasSchemaDetails()) {
mergeSchemaDetails(other.getSchemaDetails());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
name_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
key_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
input.readMessage(getSchemaDetailsFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000004;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object name_ = "";
/**
*
*
* <pre>
* Resource name of the data schema in the form of:
* `projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema}`
* where {data_schema} part should be the same as the `key` field below.
* </pre>
*
* <code>string name = 1;</code>
*
* @return The name.
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Resource name of the data schema in the form of:
* `projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema}`
* where {data_schema} part should be the same as the `key` field below.
* </pre>
*
* <code>string name = 1;</code>
*
* @return The bytes for name.
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Resource name of the data schema in the form of:
* `projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema}`
* where {data_schema} part should be the same as the `key` field below.
* </pre>
*
* <code>string name = 1;</code>
*
* @param value The name to set.
* @return This builder for chaining.
*/
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Resource name of the data schema in the form of:
* `projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema}`
* where {data_schema} part should be the same as the `key` field below.
* </pre>
*
* <code>string name = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Resource name of the data schema in the form of:
* `projects/{project_number}/locations/{location}/corpora/{corpus}/dataSchemas/{data_schema}`
* where {data_schema} part should be the same as the `key` field below.
* </pre>
*
* <code>string name = 1;</code>
*
* @param value The bytes for name to set.
* @return This builder for chaining.
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object key_ = "";
/**
*
*
* <pre>
* Required. The key of this data schema. This key should be matching the key
* of user specified annotation and unique inside corpus. This value can be up
* to 63 characters, and valid characters are /[a-z][0-9]-/. The first
* character must be a letter, the last could be a letter or a number.
* </pre>
*
* <code>string key = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The key.
*/
public java.lang.String getKey() {
java.lang.Object ref = key_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
key_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The key of this data schema. This key should be matching the key
* of user specified annotation and unique inside corpus. This value can be up
* to 63 characters, and valid characters are /[a-z][0-9]-/. The first
* character must be a letter, the last could be a letter or a number.
* </pre>
*
* <code>string key = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for key.
*/
public com.google.protobuf.ByteString getKeyBytes() {
java.lang.Object ref = key_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
key_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The key of this data schema. This key should be matching the key
* of user specified annotation and unique inside corpus. This value can be up
* to 63 characters, and valid characters are /[a-z][0-9]-/. The first
* character must be a letter, the last could be a letter or a number.
* </pre>
*
* <code>string key = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The key to set.
* @return This builder for chaining.
*/
public Builder setKey(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
key_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The key of this data schema. This key should be matching the key
* of user specified annotation and unique inside corpus. This value can be up
* to 63 characters, and valid characters are /[a-z][0-9]-/. The first
* character must be a letter, the last could be a letter or a number.
* </pre>
*
* <code>string key = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearKey() {
key_ = getDefaultInstance().getKey();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The key of this data schema. This key should be matching the key
* of user specified annotation and unique inside corpus. This value can be up
* to 63 characters, and valid characters are /[a-z][0-9]-/. The first
* character must be a letter, the last could be a letter or a number.
* </pre>
*
* <code>string key = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for key to set.
* @return This builder for chaining.
*/
public Builder setKeyBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
key_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.cloud.visionai.v1.DataSchemaDetails schemaDetails_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.visionai.v1.DataSchemaDetails,
com.google.cloud.visionai.v1.DataSchemaDetails.Builder,
com.google.cloud.visionai.v1.DataSchemaDetailsOrBuilder>
schemaDetailsBuilder_;
/**
*
*
* <pre>
* The schema details mapping to the key.
* </pre>
*
* <code>.google.cloud.visionai.v1.DataSchemaDetails schema_details = 3;</code>
*
* @return Whether the schemaDetails field is set.
*/
public boolean hasSchemaDetails() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* The schema details mapping to the key.
* </pre>
*
* <code>.google.cloud.visionai.v1.DataSchemaDetails schema_details = 3;</code>
*
* @return The schemaDetails.
*/
public com.google.cloud.visionai.v1.DataSchemaDetails getSchemaDetails() {
if (schemaDetailsBuilder_ == null) {
return schemaDetails_ == null
? com.google.cloud.visionai.v1.DataSchemaDetails.getDefaultInstance()
: schemaDetails_;
} else {
return schemaDetailsBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The schema details mapping to the key.
* </pre>
*
* <code>.google.cloud.visionai.v1.DataSchemaDetails schema_details = 3;</code>
*/
public Builder setSchemaDetails(com.google.cloud.visionai.v1.DataSchemaDetails value) {
if (schemaDetailsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
schemaDetails_ = value;
} else {
schemaDetailsBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The schema details mapping to the key.
* </pre>
*
* <code>.google.cloud.visionai.v1.DataSchemaDetails schema_details = 3;</code>
*/
public Builder setSchemaDetails(
com.google.cloud.visionai.v1.DataSchemaDetails.Builder builderForValue) {
if (schemaDetailsBuilder_ == null) {
schemaDetails_ = builderForValue.build();
} else {
schemaDetailsBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The schema details mapping to the key.
* </pre>
*
* <code>.google.cloud.visionai.v1.DataSchemaDetails schema_details = 3;</code>
*/
public Builder mergeSchemaDetails(com.google.cloud.visionai.v1.DataSchemaDetails value) {
if (schemaDetailsBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& schemaDetails_ != null
&& schemaDetails_
!= com.google.cloud.visionai.v1.DataSchemaDetails.getDefaultInstance()) {
getSchemaDetailsBuilder().mergeFrom(value);
} else {
schemaDetails_ = value;
}
} else {
schemaDetailsBuilder_.mergeFrom(value);
}
if (schemaDetails_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The schema details mapping to the key.
* </pre>
*
* <code>.google.cloud.visionai.v1.DataSchemaDetails schema_details = 3;</code>
*/
public Builder clearSchemaDetails() {
bitField0_ = (bitField0_ & ~0x00000004);
schemaDetails_ = null;
if (schemaDetailsBuilder_ != null) {
schemaDetailsBuilder_.dispose();
schemaDetailsBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The schema details mapping to the key.
* </pre>
*
* <code>.google.cloud.visionai.v1.DataSchemaDetails schema_details = 3;</code>
*/
public com.google.cloud.visionai.v1.DataSchemaDetails.Builder getSchemaDetailsBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getSchemaDetailsFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The schema details mapping to the key.
* </pre>
*
* <code>.google.cloud.visionai.v1.DataSchemaDetails schema_details = 3;</code>
*/
public com.google.cloud.visionai.v1.DataSchemaDetailsOrBuilder getSchemaDetailsOrBuilder() {
if (schemaDetailsBuilder_ != null) {
return schemaDetailsBuilder_.getMessageOrBuilder();
} else {
return schemaDetails_ == null
? com.google.cloud.visionai.v1.DataSchemaDetails.getDefaultInstance()
: schemaDetails_;
}
}
/**
*
*
* <pre>
* The schema details mapping to the key.
* </pre>
*
* <code>.google.cloud.visionai.v1.DataSchemaDetails schema_details = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.visionai.v1.DataSchemaDetails,
com.google.cloud.visionai.v1.DataSchemaDetails.Builder,
com.google.cloud.visionai.v1.DataSchemaDetailsOrBuilder>
getSchemaDetailsFieldBuilder() {
if (schemaDetailsBuilder_ == null) {
schemaDetailsBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.visionai.v1.DataSchemaDetails,
com.google.cloud.visionai.v1.DataSchemaDetails.Builder,
com.google.cloud.visionai.v1.DataSchemaDetailsOrBuilder>(
getSchemaDetails(), getParentForChildren(), isClean());
schemaDetails_ = null;
}
return schemaDetailsBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.visionai.v1.DataSchema)
}
// @@protoc_insertion_point(class_scope:google.cloud.visionai.v1.DataSchema)
private static final com.google.cloud.visionai.v1.DataSchema DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.visionai.v1.DataSchema();
}
public static com.google.cloud.visionai.v1.DataSchema getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DataSchema> PARSER =
new com.google.protobuf.AbstractParser<DataSchema>() {
@java.lang.Override
public DataSchema 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<DataSchema> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DataSchema> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.visionai.v1.DataSchema getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
openjdk/jdk8 | 36,751 | jdk/src/share/classes/java/util/TimSort.java | /*
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright 2009 Google Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util;
/**
* A stable, adaptive, iterative mergesort that requires far fewer than
* n lg(n) comparisons when running on partially sorted arrays, while
* offering performance comparable to a traditional mergesort when run
* on random arrays. Like all proper mergesorts, this sort is stable and
* runs O(n log n) time (worst case). In the worst case, this sort requires
* temporary storage space for n/2 object references; in the best case,
* it requires only a small constant amount of space.
*
* This implementation was adapted from Tim Peters's list sort for
* Python, which is described in detail here:
*
* http://svn.python.org/projects/python/trunk/Objects/listsort.txt
*
* Tim's C code may be found here:
*
* http://svn.python.org/projects/python/trunk/Objects/listobject.c
*
* The underlying techniques are described in this paper (and may have
* even earlier origins):
*
* "Optimistic Sorting and Information Theoretic Complexity"
* Peter McIlroy
* SODA (Fourth Annual ACM-SIAM Symposium on Discrete Algorithms),
* pp 467-474, Austin, Texas, 25-27 January 1993.
*
* While the API to this class consists solely of static methods, it is
* (privately) instantiable; a TimSort instance holds the state of an ongoing
* sort, assuming the input array is large enough to warrant the full-blown
* TimSort. Small arrays are sorted in place, using a binary insertion sort.
*
* @author Josh Bloch
*/
class TimSort<T> {
/**
* This is the minimum sized sequence that will be merged. Shorter
* sequences will be lengthened by calling binarySort. If the entire
* array is less than this length, no merges will be performed.
*
* This constant should be a power of two. It was 64 in Tim Peter's C
* implementation, but 32 was empirically determined to work better in
* this implementation. In the unlikely event that you set this constant
* to be a number that's not a power of two, you'll need to change the
* {@link #minRunLength} computation.
*
* If you decrease this constant, you must change the stackLen
* computation in the TimSort constructor, or you risk an
* ArrayOutOfBounds exception. See listsort.txt for a discussion
* of the minimum stack length required as a function of the length
* of the array being sorted and the minimum merge sequence length.
*/
private static final int MIN_MERGE = 32;
/**
* The array being sorted.
*/
private final T[] a;
/**
* The comparator for this sort.
*/
private final Comparator<? super T> c;
/**
* When we get into galloping mode, we stay there until both runs win less
* often than MIN_GALLOP consecutive times.
*/
private static final int MIN_GALLOP = 7;
/**
* This controls when we get *into* galloping mode. It is initialized
* to MIN_GALLOP. The mergeLo and mergeHi methods nudge it higher for
* random data, and lower for highly structured data.
*/
private int minGallop = MIN_GALLOP;
/**
* Maximum initial size of tmp array, which is used for merging. The array
* can grow to accommodate demand.
*
* Unlike Tim's original C version, we do not allocate this much storage
* when sorting smaller arrays. This change was required for performance.
*/
private static final int INITIAL_TMP_STORAGE_LENGTH = 256;
/**
* Temp storage for merges. A workspace array may optionally be
* provided in constructor, and if so will be used as long as it
* is big enough.
*/
private T[] tmp;
private int tmpBase; // base of tmp array slice
private int tmpLen; // length of tmp array slice
/**
* A stack of pending runs yet to be merged. Run i starts at
* address base[i] and extends for len[i] elements. It's always
* true (so long as the indices are in bounds) that:
*
* runBase[i] + runLen[i] == runBase[i + 1]
*
* so we could cut the storage for this, but it's a minor amount,
* and keeping all the info explicit simplifies the code.
*/
private int stackSize = 0; // Number of pending runs on stack
private final int[] runBase;
private final int[] runLen;
/**
* Creates a TimSort instance to maintain the state of an ongoing sort.
*
* @param a the array to be sorted
* @param c the comparator to determine the order of the sort
* @param work a workspace array (slice)
* @param workBase origin of usable space in work array
* @param workLen usable size of work array
*/
private TimSort(T[] a, Comparator<? super T> c, T[] work, int workBase, int workLen) {
this.a = a;
this.c = c;
// Allocate temp storage (which may be increased later if necessary)
int len = a.length;
int tlen = (len < 2 * INITIAL_TMP_STORAGE_LENGTH) ?
len >>> 1 : INITIAL_TMP_STORAGE_LENGTH;
if (work == null || workLen < tlen || workBase + tlen > work.length) {
@SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
T[] newArray = (T[])java.lang.reflect.Array.newInstance
(a.getClass().getComponentType(), tlen);
tmp = newArray;
tmpBase = 0;
tmpLen = tlen;
}
else {
tmp = work;
tmpBase = workBase;
tmpLen = workLen;
}
/*
* Allocate runs-to-be-merged stack (which cannot be expanded). The
* stack length requirements are described in listsort.txt. The C
* version always uses the same stack length (85), but this was
* measured to be too expensive when sorting "mid-sized" arrays (e.g.,
* 100 elements) in Java. Therefore, we use smaller (but sufficiently
* large) stack lengths for smaller arrays. The "magic numbers" in the
* computation below must be changed if MIN_MERGE is decreased. See
* the MIN_MERGE declaration above for more information.
*/
int stackLen = (len < 120 ? 5 :
len < 1542 ? 10 :
len < 119151 ? 24 : 40);
runBase = new int[stackLen];
runLen = new int[stackLen];
}
/*
* The next method (package private and static) constitutes the
* entire API of this class.
*/
/**
* Sorts the given range, using the given workspace array slice
* for temp storage when possible. This method is designed to be
* invoked from public methods (in class Arrays) after performing
* any necessary array bounds checks and expanding parameters into
* the required forms.
*
* @param a the array to be sorted
* @param lo the index of the first element, inclusive, to be sorted
* @param hi the index of the last element, exclusive, to be sorted
* @param c the comparator to use
* @param work a workspace array (slice)
* @param workBase origin of usable space in work array
* @param workLen usable size of work array
* @since 1.8
*/
static <T> void sort(T[] a, int lo, int hi, Comparator<? super T> c,
T[] work, int workBase, int workLen) {
assert c != null && a != null && lo >= 0 && lo <= hi && hi <= a.length;
int nRemaining = hi - lo;
if (nRemaining < 2)
return; // Arrays of size 0 and 1 are always sorted
// If array is small, do a "mini-TimSort" with no merges
if (nRemaining < MIN_MERGE) {
int initRunLen = countRunAndMakeAscending(a, lo, hi, c);
binarySort(a, lo, hi, lo + initRunLen, c);
return;
}
/**
* March over the array once, left to right, finding natural runs,
* extending short natural runs to minRun elements, and merging runs
* to maintain stack invariant.
*/
TimSort<T> ts = new TimSort<>(a, c, work, workBase, workLen);
int minRun = minRunLength(nRemaining);
do {
// Identify next run
int runLen = countRunAndMakeAscending(a, lo, hi, c);
// If run is short, extend to min(minRun, nRemaining)
if (runLen < minRun) {
int force = nRemaining <= minRun ? nRemaining : minRun;
binarySort(a, lo, lo + force, lo + runLen, c);
runLen = force;
}
// Push run onto pending-run stack, and maybe merge
ts.pushRun(lo, runLen);
ts.mergeCollapse();
// Advance to find next run
lo += runLen;
nRemaining -= runLen;
} while (nRemaining != 0);
// Merge all remaining runs to complete sort
assert lo == hi;
ts.mergeForceCollapse();
assert ts.stackSize == 1;
}
/**
* Sorts the specified portion of the specified array using a binary
* insertion sort. This is the best method for sorting small numbers
* of elements. It requires O(n log n) compares, but O(n^2) data
* movement (worst case).
*
* If the initial part of the specified range is already sorted,
* this method can take advantage of it: the method assumes that the
* elements from index {@code lo}, inclusive, to {@code start},
* exclusive are already sorted.
*
* @param a the array in which a range is to be sorted
* @param lo the index of the first element in the range to be sorted
* @param hi the index after the last element in the range to be sorted
* @param start the index of the first element in the range that is
* not already known to be sorted ({@code lo <= start <= hi})
* @param c comparator to used for the sort
*/
@SuppressWarnings("fallthrough")
private static <T> void binarySort(T[] a, int lo, int hi, int start,
Comparator<? super T> c) {
assert lo <= start && start <= hi;
if (start == lo)
start++;
for ( ; start < hi; start++) {
T pivot = a[start];
// Set left (and right) to the index where a[start] (pivot) belongs
int left = lo;
int right = start;
assert left <= right;
/*
* Invariants:
* pivot >= all in [lo, left).
* pivot < all in [right, start).
*/
while (left < right) {
int mid = (left + right) >>> 1;
if (c.compare(pivot, a[mid]) < 0)
right = mid;
else
left = mid + 1;
}
assert left == right;
/*
* The invariants still hold: pivot >= all in [lo, left) and
* pivot < all in [left, start), so pivot belongs at left. Note
* that if there are elements equal to pivot, left points to the
* first slot after them -- that's why this sort is stable.
* Slide elements over to make room for pivot.
*/
int n = start - left; // The number of elements to move
// Switch is just an optimization for arraycopy in default case
switch (n) {
case 2: a[left + 2] = a[left + 1];
case 1: a[left + 1] = a[left];
break;
default: System.arraycopy(a, left, a, left + 1, n);
}
a[left] = pivot;
}
}
/**
* Returns the length of the run beginning at the specified position in
* the specified array and reverses the run if it is descending (ensuring
* that the run will always be ascending when the method returns).
*
* A run is the longest ascending sequence with:
*
* a[lo] <= a[lo + 1] <= a[lo + 2] <= ...
*
* or the longest descending sequence with:
*
* a[lo] > a[lo + 1] > a[lo + 2] > ...
*
* For its intended use in a stable mergesort, the strictness of the
* definition of "descending" is needed so that the call can safely
* reverse a descending sequence without violating stability.
*
* @param a the array in which a run is to be counted and possibly reversed
* @param lo index of the first element in the run
* @param hi index after the last element that may be contained in the run.
It is required that {@code lo < hi}.
* @param c the comparator to used for the sort
* @return the length of the run beginning at the specified position in
* the specified array
*/
private static <T> int countRunAndMakeAscending(T[] a, int lo, int hi,
Comparator<? super T> c) {
assert lo < hi;
int runHi = lo + 1;
if (runHi == hi)
return 1;
// Find end of run, and reverse range if descending
if (c.compare(a[runHi++], a[lo]) < 0) { // Descending
while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0)
runHi++;
reverseRange(a, lo, runHi);
} else { // Ascending
while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0)
runHi++;
}
return runHi - lo;
}
/**
* Reverse the specified range of the specified array.
*
* @param a the array in which a range is to be reversed
* @param lo the index of the first element in the range to be reversed
* @param hi the index after the last element in the range to be reversed
*/
private static void reverseRange(Object[] a, int lo, int hi) {
hi--;
while (lo < hi) {
Object t = a[lo];
a[lo++] = a[hi];
a[hi--] = t;
}
}
/**
* Returns the minimum acceptable run length for an array of the specified
* length. Natural runs shorter than this will be extended with
* {@link #binarySort}.
*
* Roughly speaking, the computation is:
*
* If n < MIN_MERGE, return n (it's too small to bother with fancy stuff).
* Else if n is an exact power of 2, return MIN_MERGE/2.
* Else return an int k, MIN_MERGE/2 <= k <= MIN_MERGE, such that n/k
* is close to, but strictly less than, an exact power of 2.
*
* For the rationale, see listsort.txt.
*
* @param n the length of the array to be sorted
* @return the length of the minimum run to be merged
*/
private static int minRunLength(int n) {
assert n >= 0;
int r = 0; // Becomes 1 if any 1 bits are shifted off
while (n >= MIN_MERGE) {
r |= (n & 1);
n >>= 1;
}
return n + r;
}
/**
* Pushes the specified run onto the pending-run stack.
*
* @param runBase index of the first element in the run
* @param runLen the number of elements in the run
*/
private void pushRun(int runBase, int runLen) {
this.runBase[stackSize] = runBase;
this.runLen[stackSize] = runLen;
stackSize++;
}
/**
* Examines the stack of runs waiting to be merged and merges adjacent runs
* until the stack invariants are reestablished:
*
* 1. runLen[i - 3] > runLen[i - 2] + runLen[i - 1]
* 2. runLen[i - 2] > runLen[i - 1]
*
* This method is called each time a new run is pushed onto the stack,
* so the invariants are guaranteed to hold for i < stackSize upon
* entry to the method.
*/
private void mergeCollapse() {
while (stackSize > 1) {
int n = stackSize - 2;
if (n > 0 && runLen[n-1] <= runLen[n] + runLen[n+1]) {
if (runLen[n - 1] < runLen[n + 1])
n--;
mergeAt(n);
} else if (runLen[n] <= runLen[n + 1]) {
mergeAt(n);
} else {
break; // Invariant is established
}
}
}
/**
* Merges all runs on the stack until only one remains. This method is
* called once, to complete the sort.
*/
private void mergeForceCollapse() {
while (stackSize > 1) {
int n = stackSize - 2;
if (n > 0 && runLen[n - 1] < runLen[n + 1])
n--;
mergeAt(n);
}
}
/**
* Merges the two runs at stack indices i and i+1. Run i must be
* the penultimate or antepenultimate run on the stack. In other words,
* i must be equal to stackSize-2 or stackSize-3.
*
* @param i stack index of the first of the two runs to merge
*/
private void mergeAt(int i) {
assert stackSize >= 2;
assert i >= 0;
assert i == stackSize - 2 || i == stackSize - 3;
int base1 = runBase[i];
int len1 = runLen[i];
int base2 = runBase[i + 1];
int len2 = runLen[i + 1];
assert len1 > 0 && len2 > 0;
assert base1 + len1 == base2;
/*
* Record the length of the combined runs; if i is the 3rd-last
* run now, also slide over the last run (which isn't involved
* in this merge). The current run (i+1) goes away in any case.
*/
runLen[i] = len1 + len2;
if (i == stackSize - 3) {
runBase[i + 1] = runBase[i + 2];
runLen[i + 1] = runLen[i + 2];
}
stackSize--;
/*
* Find where the first element of run2 goes in run1. Prior elements
* in run1 can be ignored (because they're already in place).
*/
int k = gallopRight(a[base2], a, base1, len1, 0, c);
assert k >= 0;
base1 += k;
len1 -= k;
if (len1 == 0)
return;
/*
* Find where the last element of run1 goes in run2. Subsequent elements
* in run2 can be ignored (because they're already in place).
*/
len2 = gallopLeft(a[base1 + len1 - 1], a, base2, len2, len2 - 1, c);
assert len2 >= 0;
if (len2 == 0)
return;
// Merge remaining runs, using tmp array with min(len1, len2) elements
if (len1 <= len2)
mergeLo(base1, len1, base2, len2);
else
mergeHi(base1, len1, base2, len2);
}
/**
* Locates the position at which to insert the specified key into the
* specified sorted range; if the range contains an element equal to key,
* returns the index of the leftmost equal element.
*
* @param key the key whose insertion point to search for
* @param a the array in which to search
* @param base the index of the first element in the range
* @param len the length of the range; must be > 0
* @param hint the index at which to begin the search, 0 <= hint < n.
* The closer hint is to the result, the faster this method will run.
* @param c the comparator used to order the range, and to search
* @return the int k, 0 <= k <= n such that a[b + k - 1] < key <= a[b + k],
* pretending that a[b - 1] is minus infinity and a[b + n] is infinity.
* In other words, key belongs at index b + k; or in other words,
* the first k elements of a should precede key, and the last n - k
* should follow it.
*/
private static <T> int gallopLeft(T key, T[] a, int base, int len, int hint,
Comparator<? super T> c) {
assert len > 0 && hint >= 0 && hint < len;
int lastOfs = 0;
int ofs = 1;
if (c.compare(key, a[base + hint]) > 0) {
// Gallop right until a[base+hint+lastOfs] < key <= a[base+hint+ofs]
int maxOfs = len - hint;
while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) > 0) {
lastOfs = ofs;
ofs = (ofs << 1) + 1;
if (ofs <= 0) // int overflow
ofs = maxOfs;
}
if (ofs > maxOfs)
ofs = maxOfs;
// Make offsets relative to base
lastOfs += hint;
ofs += hint;
} else { // key <= a[base + hint]
// Gallop left until a[base+hint-ofs] < key <= a[base+hint-lastOfs]
final int maxOfs = hint + 1;
while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) <= 0) {
lastOfs = ofs;
ofs = (ofs << 1) + 1;
if (ofs <= 0) // int overflow
ofs = maxOfs;
}
if (ofs > maxOfs)
ofs = maxOfs;
// Make offsets relative to base
int tmp = lastOfs;
lastOfs = hint - ofs;
ofs = hint - tmp;
}
assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
/*
* Now a[base+lastOfs] < key <= a[base+ofs], so key belongs somewhere
* to the right of lastOfs but no farther right than ofs. Do a binary
* search, with invariant a[base + lastOfs - 1] < key <= a[base + ofs].
*/
lastOfs++;
while (lastOfs < ofs) {
int m = lastOfs + ((ofs - lastOfs) >>> 1);
if (c.compare(key, a[base + m]) > 0)
lastOfs = m + 1; // a[base + m] < key
else
ofs = m; // key <= a[base + m]
}
assert lastOfs == ofs; // so a[base + ofs - 1] < key <= a[base + ofs]
return ofs;
}
/**
* Like gallopLeft, except that if the range contains an element equal to
* key, gallopRight returns the index after the rightmost equal element.
*
* @param key the key whose insertion point to search for
* @param a the array in which to search
* @param base the index of the first element in the range
* @param len the length of the range; must be > 0
* @param hint the index at which to begin the search, 0 <= hint < n.
* The closer hint is to the result, the faster this method will run.
* @param c the comparator used to order the range, and to search
* @return the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k]
*/
private static <T> int gallopRight(T key, T[] a, int base, int len,
int hint, Comparator<? super T> c) {
assert len > 0 && hint >= 0 && hint < len;
int ofs = 1;
int lastOfs = 0;
if (c.compare(key, a[base + hint]) < 0) {
// Gallop left until a[b+hint - ofs] <= key < a[b+hint - lastOfs]
int maxOfs = hint + 1;
while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) < 0) {
lastOfs = ofs;
ofs = (ofs << 1) + 1;
if (ofs <= 0) // int overflow
ofs = maxOfs;
}
if (ofs > maxOfs)
ofs = maxOfs;
// Make offsets relative to b
int tmp = lastOfs;
lastOfs = hint - ofs;
ofs = hint - tmp;
} else { // a[b + hint] <= key
// Gallop right until a[b+hint + lastOfs] <= key < a[b+hint + ofs]
int maxOfs = len - hint;
while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) >= 0) {
lastOfs = ofs;
ofs = (ofs << 1) + 1;
if (ofs <= 0) // int overflow
ofs = maxOfs;
}
if (ofs > maxOfs)
ofs = maxOfs;
// Make offsets relative to b
lastOfs += hint;
ofs += hint;
}
assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
/*
* Now a[b + lastOfs] <= key < a[b + ofs], so key belongs somewhere to
* the right of lastOfs but no farther right than ofs. Do a binary
* search, with invariant a[b + lastOfs - 1] <= key < a[b + ofs].
*/
lastOfs++;
while (lastOfs < ofs) {
int m = lastOfs + ((ofs - lastOfs) >>> 1);
if (c.compare(key, a[base + m]) < 0)
ofs = m; // key < a[b + m]
else
lastOfs = m + 1; // a[b + m] <= key
}
assert lastOfs == ofs; // so a[b + ofs - 1] <= key < a[b + ofs]
return ofs;
}
/**
* Merges two adjacent runs in place, in a stable fashion. The first
* element of the first run must be greater than the first element of the
* second run (a[base1] > a[base2]), and the last element of the first run
* (a[base1 + len1-1]) must be greater than all elements of the second run.
*
* For performance, this method should be called only when len1 <= len2;
* its twin, mergeHi should be called if len1 >= len2. (Either method
* may be called if len1 == len2.)
*
* @param base1 index of first element in first run to be merged
* @param len1 length of first run to be merged (must be > 0)
* @param base2 index of first element in second run to be merged
* (must be aBase + aLen)
* @param len2 length of second run to be merged (must be > 0)
*/
private void mergeLo(int base1, int len1, int base2, int len2) {
assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
// Copy first run into temp array
T[] a = this.a; // For performance
T[] tmp = ensureCapacity(len1);
int cursor1 = tmpBase; // Indexes into tmp array
int cursor2 = base2; // Indexes int a
int dest = base1; // Indexes int a
System.arraycopy(a, base1, tmp, cursor1, len1);
// Move first element of second run and deal with degenerate cases
a[dest++] = a[cursor2++];
if (--len2 == 0) {
System.arraycopy(tmp, cursor1, a, dest, len1);
return;
}
if (len1 == 1) {
System.arraycopy(a, cursor2, a, dest, len2);
a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge
return;
}
Comparator<? super T> c = this.c; // Use local variable for performance
int minGallop = this.minGallop; // " " " " "
outer:
while (true) {
int count1 = 0; // Number of times in a row that first run won
int count2 = 0; // Number of times in a row that second run won
/*
* Do the straightforward thing until (if ever) one run starts
* winning consistently.
*/
do {
assert len1 > 1 && len2 > 0;
if (c.compare(a[cursor2], tmp[cursor1]) < 0) {
a[dest++] = a[cursor2++];
count2++;
count1 = 0;
if (--len2 == 0)
break outer;
} else {
a[dest++] = tmp[cursor1++];
count1++;
count2 = 0;
if (--len1 == 1)
break outer;
}
} while ((count1 | count2) < minGallop);
/*
* One run is winning so consistently that galloping may be a
* huge win. So try that, and continue galloping until (if ever)
* neither run appears to be winning consistently anymore.
*/
do {
assert len1 > 1 && len2 > 0;
count1 = gallopRight(a[cursor2], tmp, cursor1, len1, 0, c);
if (count1 != 0) {
System.arraycopy(tmp, cursor1, a, dest, count1);
dest += count1;
cursor1 += count1;
len1 -= count1;
if (len1 <= 1) // len1 == 1 || len1 == 0
break outer;
}
a[dest++] = a[cursor2++];
if (--len2 == 0)
break outer;
count2 = gallopLeft(tmp[cursor1], a, cursor2, len2, 0, c);
if (count2 != 0) {
System.arraycopy(a, cursor2, a, dest, count2);
dest += count2;
cursor2 += count2;
len2 -= count2;
if (len2 == 0)
break outer;
}
a[dest++] = tmp[cursor1++];
if (--len1 == 1)
break outer;
minGallop--;
} while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
if (minGallop < 0)
minGallop = 0;
minGallop += 2; // Penalize for leaving gallop mode
} // End of "outer" loop
this.minGallop = minGallop < 1 ? 1 : minGallop; // Write back to field
if (len1 == 1) {
assert len2 > 0;
System.arraycopy(a, cursor2, a, dest, len2);
a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge
} else if (len1 == 0) {
throw new IllegalArgumentException(
"Comparison method violates its general contract!");
} else {
assert len2 == 0;
assert len1 > 1;
System.arraycopy(tmp, cursor1, a, dest, len1);
}
}
/**
* Like mergeLo, except that this method should be called only if
* len1 >= len2; mergeLo should be called if len1 <= len2. (Either method
* may be called if len1 == len2.)
*
* @param base1 index of first element in first run to be merged
* @param len1 length of first run to be merged (must be > 0)
* @param base2 index of first element in second run to be merged
* (must be aBase + aLen)
* @param len2 length of second run to be merged (must be > 0)
*/
private void mergeHi(int base1, int len1, int base2, int len2) {
assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
// Copy second run into temp array
T[] a = this.a; // For performance
T[] tmp = ensureCapacity(len2);
int tmpBase = this.tmpBase;
System.arraycopy(a, base2, tmp, tmpBase, len2);
int cursor1 = base1 + len1 - 1; // Indexes into a
int cursor2 = tmpBase + len2 - 1; // Indexes into tmp array
int dest = base2 + len2 - 1; // Indexes into a
// Move last element of first run and deal with degenerate cases
a[dest--] = a[cursor1--];
if (--len1 == 0) {
System.arraycopy(tmp, tmpBase, a, dest - (len2 - 1), len2);
return;
}
if (len2 == 1) {
dest -= len1;
cursor1 -= len1;
System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
a[dest] = tmp[cursor2];
return;
}
Comparator<? super T> c = this.c; // Use local variable for performance
int minGallop = this.minGallop; // " " " " "
outer:
while (true) {
int count1 = 0; // Number of times in a row that first run won
int count2 = 0; // Number of times in a row that second run won
/*
* Do the straightforward thing until (if ever) one run
* appears to win consistently.
*/
do {
assert len1 > 0 && len2 > 1;
if (c.compare(tmp[cursor2], a[cursor1]) < 0) {
a[dest--] = a[cursor1--];
count1++;
count2 = 0;
if (--len1 == 0)
break outer;
} else {
a[dest--] = tmp[cursor2--];
count2++;
count1 = 0;
if (--len2 == 1)
break outer;
}
} while ((count1 | count2) < minGallop);
/*
* One run is winning so consistently that galloping may be a
* huge win. So try that, and continue galloping until (if ever)
* neither run appears to be winning consistently anymore.
*/
do {
assert len1 > 0 && len2 > 1;
count1 = len1 - gallopRight(tmp[cursor2], a, base1, len1, len1 - 1, c);
if (count1 != 0) {
dest -= count1;
cursor1 -= count1;
len1 -= count1;
System.arraycopy(a, cursor1 + 1, a, dest + 1, count1);
if (len1 == 0)
break outer;
}
a[dest--] = tmp[cursor2--];
if (--len2 == 1)
break outer;
count2 = len2 - gallopLeft(a[cursor1], tmp, tmpBase, len2, len2 - 1, c);
if (count2 != 0) {
dest -= count2;
cursor2 -= count2;
len2 -= count2;
System.arraycopy(tmp, cursor2 + 1, a, dest + 1, count2);
if (len2 <= 1) // len2 == 1 || len2 == 0
break outer;
}
a[dest--] = a[cursor1--];
if (--len1 == 0)
break outer;
minGallop--;
} while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
if (minGallop < 0)
minGallop = 0;
minGallop += 2; // Penalize for leaving gallop mode
} // End of "outer" loop
this.minGallop = minGallop < 1 ? 1 : minGallop; // Write back to field
if (len2 == 1) {
assert len1 > 0;
dest -= len1;
cursor1 -= len1;
System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
a[dest] = tmp[cursor2]; // Move first elt of run2 to front of merge
} else if (len2 == 0) {
throw new IllegalArgumentException(
"Comparison method violates its general contract!");
} else {
assert len1 == 0;
assert len2 > 0;
System.arraycopy(tmp, tmpBase, a, dest - (len2 - 1), len2);
}
}
/**
* Ensures that the external array tmp has at least the specified
* number of elements, increasing its size if necessary. The size
* increases exponentially to ensure amortized linear time complexity.
*
* @param minCapacity the minimum required capacity of the tmp array
* @return tmp, whether or not it grew
*/
private T[] ensureCapacity(int minCapacity) {
if (tmpLen < minCapacity) {
// Compute smallest power of 2 > minCapacity
int newSize = minCapacity;
newSize |= newSize >> 1;
newSize |= newSize >> 2;
newSize |= newSize >> 4;
newSize |= newSize >> 8;
newSize |= newSize >> 16;
newSize++;
if (newSize < 0) // Not bloody likely!
newSize = minCapacity;
else
newSize = Math.min(newSize, a.length >>> 1);
@SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
T[] newArray = (T[])java.lang.reflect.Array.newInstance
(a.getClass().getComponentType(), newSize);
tmp = newArray;
tmpLen = newSize;
tmpBase = 0;
}
return tmp;
}
}
|
apache/iotdb | 36,622 | iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/analyze/Analysis.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iotdb.db.queryengine.plan.analyze;
import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
import org.apache.iotdb.common.rpc.thrift.TRegionReplicaSet;
import org.apache.iotdb.common.rpc.thrift.TSStatus;
import org.apache.iotdb.common.rpc.thrift.TSchemaNode;
import org.apache.iotdb.common.rpc.thrift.TTimePartitionSlot;
import org.apache.iotdb.commons.model.ModelInformation;
import org.apache.iotdb.commons.partition.DataPartition;
import org.apache.iotdb.commons.partition.SchemaPartition;
import org.apache.iotdb.commons.path.PartialPath;
import org.apache.iotdb.db.queryengine.common.DeviceContext;
import org.apache.iotdb.db.queryengine.common.MPPQueryContext;
import org.apache.iotdb.db.queryengine.common.NodeRef;
import org.apache.iotdb.db.queryengine.common.TimeseriesContext;
import org.apache.iotdb.db.queryengine.common.header.DatasetHeader;
import org.apache.iotdb.db.queryengine.common.schematree.ISchemaTree;
import org.apache.iotdb.db.queryengine.plan.execution.memory.StatementMemorySource;
import org.apache.iotdb.db.queryengine.plan.execution.memory.StatementMemorySourceContext;
import org.apache.iotdb.db.queryengine.plan.execution.memory.StatementMemorySourceVisitor;
import org.apache.iotdb.db.queryengine.plan.expression.Expression;
import org.apache.iotdb.db.queryengine.plan.expression.ExpressionType;
import org.apache.iotdb.db.queryengine.plan.expression.leaf.TimeSeriesOperand;
import org.apache.iotdb.db.queryengine.plan.planner.plan.TimePredicate;
import org.apache.iotdb.db.queryengine.plan.planner.plan.TreeModelTimePredicate;
import org.apache.iotdb.db.queryengine.plan.planner.plan.node.process.FilterNode;
import org.apache.iotdb.db.queryengine.plan.planner.plan.parameter.DeviceViewIntoPathDescriptor;
import org.apache.iotdb.db.queryengine.plan.planner.plan.parameter.FillDescriptor;
import org.apache.iotdb.db.queryengine.plan.planner.plan.parameter.GroupByParameter;
import org.apache.iotdb.db.queryengine.plan.planner.plan.parameter.GroupByTimeParameter;
import org.apache.iotdb.db.queryengine.plan.planner.plan.parameter.IntoPathDescriptor;
import org.apache.iotdb.db.queryengine.plan.planner.plan.parameter.OrderByParameter;
import org.apache.iotdb.db.queryengine.plan.planner.plan.parameter.model.ModelInferenceDescriptor;
import org.apache.iotdb.db.queryengine.plan.statement.Statement;
import org.apache.iotdb.db.queryengine.plan.statement.StatementType;
import org.apache.iotdb.db.queryengine.plan.statement.component.Ordering;
import org.apache.iotdb.db.queryengine.plan.statement.component.SortItem;
import org.apache.iotdb.db.queryengine.plan.statement.crud.QueryStatement;
import org.apache.iotdb.db.queryengine.plan.statement.sys.ExplainAnalyzeStatement;
import org.apache.iotdb.db.queryengine.plan.statement.sys.ShowQueriesStatement;
import org.apache.iotdb.db.schemaengine.template.Template;
import org.apache.tsfile.enums.TSDataType;
import org.apache.tsfile.file.metadata.IDeviceID;
import org.apache.tsfile.read.common.block.TsBlock;
import org.apache.tsfile.read.filter.basic.Filter;
import org.apache.tsfile.utils.Pair;
import org.apache.tsfile.write.schema.IMeasurementSchema;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
/** Analysis used for planning a query. TODO: This class may need to store more info for a query. */
public class Analysis implements IAnalysis {
/////////////////////////////////////////////////////////////////////////////////////////////////
// Common Analysis
/////////////////////////////////////////////////////////////////////////////////////////////////
private String databaseName;
// Statement
private Statement statement;
private DataPartition dataPartition;
private SchemaPartition schemaPartition;
private ISchemaTree schemaTree;
private List<TEndPoint> redirectNodeList;
// map from output column name (for every node) to its datatype
private final Map<NodeRef<Expression>, TSDataType> expressionTypes = new LinkedHashMap<>();
private boolean finishQueryAfterAnalyze;
// potential fail status when finishQueryAfterAnalyze is true. If failStatus is NULL, means no
// fail.
private TSStatus failStatus;
/////////////////////////////////////////////////////////////////////////////////////////////////
// Query Analysis (used in ALIGN BY TIME)
/////////////////////////////////////////////////////////////////////////////////////////////////
// map from device name to series/aggregation under this device
private Set<Expression> sourceExpressions;
// In order to perform some optimization, when the source expression is
// not used later, nothing will be placed in this structure.
private boolean shouldHaveSourceExpression;
// input expressions of aggregations to be calculated
private Set<Expression> sourceTransformExpressions = new HashSet<>();
private Expression whereExpression;
private Expression groupByExpression;
// all aggregations that need to be calculated
private Set<Expression> aggregationExpressions;
// An ordered map from cross-timeseries aggregation to list of inner-timeseries aggregations. The
// keys' order is the output one.
private Map<Expression, Set<Expression>> crossGroupByExpressions;
// tag keys specified in `GROUP BY TAG` clause
private List<String> tagKeys;
/*
tag values -> (grouped expression -> output expressions)
For different combination of tag keys, the grouped expression may be different. Let's say there
are 3 timeseries root.sg.d1.temperature, root.sg.d1.status, root.sg.d2.temperature, and their
tags are [k1=v1], [k1=v1] and [k1=v2] respectively. For query "SELECT last_value(**) FROM root
GROUP BY k1", timeseries are grouped by their tags into 2 buckets. Bucket [v1] has
[root.sg.d1.temperature, root.sg.d1.status], while bucket [v2] has [root.sg.d2.temperature].
Thus, the aggregation results of bucket [v1] and [v2] are different. Bucket [v1] has 2
aggregation results last_value(temperature) and last_value(status), whereas bucket [v2] only
has [last_value(temperature)].
*/
private Map<List<String>, LinkedHashMap<Expression, List<Expression>>>
tagValuesToGroupedTimeseriesOperands;
/////////////////////////////////////////////////////////////////////////////////////////////////
// Query Analysis (used in ALIGN BY DEVICE)
/////////////////////////////////////////////////////////////////////////////////////////////////
// the list of device names
private List<PartialPath> deviceList;
// map from device name to series/aggregation under this device
private Map<IDeviceID, Set<Expression>> deviceToSourceExpressions;
// input expressions of aggregations to be calculated
private Map<IDeviceID, Set<Expression>> deviceToSourceTransformExpressions = new HashMap<>();
// map from device name to query filter under this device
private Map<IDeviceID, Expression> deviceToWhereExpression;
// all aggregations that need to be calculated
private Map<IDeviceID, Set<Expression>> deviceToAggregationExpressions = new HashMap<>();
// expression of output column to be calculated
private Map<IDeviceID, Set<Expression>> deviceToSelectExpressions;
// expression of group by that need to be calculated
private Map<IDeviceID, Expression> deviceToGroupByExpression;
// expression of order by that need to be calculated
private Map<IDeviceID, Set<Expression>> deviceToOrderByExpressions;
// the sortItems used in order by push down of align by device
private Map<IDeviceID, List<SortItem>> deviceToSortItems;
// e.g. [s1,s2,s3] is query, but [s1, s3] exists in device1, then device1 -> [1, 3], s1 is 1 but
// not 0 because device is the first column
private Map<IDeviceID, List<Integer>> deviceViewInputIndexesMap;
private Set<Expression> deviceViewOutputExpressions;
private Map<IDeviceID, Set<Expression>> deviceToOutputExpressions = new HashMap<>();
// map from output device name to queried devices
private Map<IDeviceID, IDeviceID> outputDeviceToQueriedDevicesMap;
// indicates whether DeviceView need special process when rewriteSource in DistributionPlan,
// you can see SourceRewriter#visitDeviceView to get more information
// deviceViewSpecialProcess equals true when all Aggregation Functions and non-mappable UDTF and
// DIFF
private boolean deviceViewSpecialProcess;
/////////////////////////////////////////////////////////////////////////////////////////////////
// Query Common Analysis (above DeviceView)
/////////////////////////////////////////////////////////////////////////////////////////////////
// indicate is there a value filter
private boolean hasValueFilter = false;
// a global time predicate used in `initQueryDataSource` and filter push down?
private Expression globalTimePredicate;
// expression of output column to be calculated
private Set<Expression> selectExpressions;
private Expression havingExpression;
// The expressions in order by clause
// In align by device orderByExpression is the deviceView of expression which doesn't have
// device-prefix
// for example, in device root.sg1.d1, [root.sg1.d1.s1] is expression and [s1] is the device-view
// one.
private Set<Expression> orderByExpressions;
private boolean hasSortNode = false;
// parameter of `FILL` clause
private FillDescriptor fillDescriptor;
// parameter of `GROUP BY TIME` clause
private GroupByTimeParameter groupByTimeParameter;
// parameter of `GROUP BY VARIATION` clause
private GroupByParameter groupByParameter;
private OrderByParameter mergeOrderParameter;
// This field will be set and used when the order by in last query only indicates the ordering of
// timeseries, otherwise it will be null
private Ordering timeseriesOrderingForLastQuery = null;
// Key: non-writable view expression, Value: corresponding source expressions
private Map<Expression, List<Expression>> lastQueryNonWritableViewSourceExpressionMap;
private Map<IDeviceID, Map<String, Expression>> lastQueryOutputPathToSourceExpressionMap;
private Set<IDeviceID> deviceExistViewSet;
// header of result dataset
private DatasetHeader respDatasetHeader;
// indicate whether the Nodes produce source data are VirtualSourceNodes
private boolean isVirtualSource = false;
private ModelInferenceDescriptor modelInferenceDescriptor;
/////////////////////////////////////////////////////////////////////////////////////////////////
// SELECT INTO Analysis
/////////////////////////////////////////////////////////////////////////////////////////////////
// used in ALIGN BY DEVICE
private DeviceViewIntoPathDescriptor deviceViewIntoPathDescriptor;
// used in ALIGN BY TIME
private IntoPathDescriptor intoPathDescriptor;
/////////////////////////////////////////////////////////////////////////////////////////////////
// Schema Query Analysis
/////////////////////////////////////////////////////////////////////////////////////////////////
// extra message from config node, used for node management
private Set<TSchemaNode> matchedNodes;
// template and paths set template
private Pair<Template, List<PartialPath>> templateSetInfo;
// devicePath -> <template, paths set template>
private Map<PartialPath, Pair<Template, PartialPath>> deviceTemplateSetInfoMap;
// potential template used in timeseries query or fetch
private Map<Integer, Template> relatedTemplateInfo;
// generated by combine the input path pattern and template set path
private List<PartialPath> specifiedTemplateRelatedPathPatternList;
/////////////////////////////////////////////////////////////////////////////////////////////////
// Logical View Analysis
/////////////////////////////////////////////////////////////////////////////////////////////////
private boolean useLogicalView = false;
private List<Pair<Expression, String>> outputExpressions = null;
/////////////////////////////////////////////////////////////////////////////////////////////////
// Show Queries Analysis
/////////////////////////////////////////////////////////////////////////////////////////////////
// extra message from config node, queries wll be sent to these Running DataNodes
private List<TDataNodeLocation> readableDataNodeLocations;
// used for limit and offset push down optimizer, if we select all columns from aligned device, we
// can use statistics to skip
private boolean lastLevelUseWildcard = false;
// if `order by limit N align by device` query use topK optimization
private boolean useTopKNode = false;
/////////////////////////////////////////////////////////////////////////////////////////////////
// All Queries Devices Set In One Template
/////////////////////////////////////////////////////////////////////////////////////////////////
// if all devices are set in one template in align by device query, this variable will not be null
private Template deviceTemplate;
// when deviceTemplate is not empty and all expressions in this query are templated measurements,
// i.e. no aggregation and arithmetic expression
private boolean noWhereAndAggregation = true;
// if it is wildcard query in templated align by device query
private boolean templateWildCardQuery;
// all queried measurementList and schemaList in deviceTemplate.
private List<String> measurementList;
private List<IMeasurementSchema> measurementSchemaList;
// Used for regionScan
private Map<PartialPath, DeviceContext> devicePathToContextMap;
private Map<PartialPath, Map<PartialPath, List<TimeseriesContext>>> deviceToTimeseriesSchemas;
public void setDevicePathToContextMap(Map<PartialPath, DeviceContext> devicePathToContextMap) {
this.devicePathToContextMap = devicePathToContextMap;
}
public Map<PartialPath, DeviceContext> getDevicePathToContextMap() {
return devicePathToContextMap;
}
public void setDeviceToTimeseriesSchemas(
Map<PartialPath, Map<PartialPath, List<TimeseriesContext>>> deviceToTimeseriesSchemas) {
this.deviceToTimeseriesSchemas = deviceToTimeseriesSchemas;
}
public Map<PartialPath, Map<PartialPath, List<TimeseriesContext>>>
getDeviceToTimeseriesSchemas() {
return deviceToTimeseriesSchemas;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// Used in optimizer
/////////////////////////////////////////////////////////////////////////////////////////////////
private final Set<NodeRef<FilterNode>> fromWhereFilterNodes = new HashSet<>();
public Analysis() {
this.finishQueryAfterAnalyze = false;
}
public List<TRegionReplicaSet> getPartitionInfo(PartialPath seriesPath, Filter timefilter) {
return dataPartition.getDataRegionReplicaSetWithTimeFilter(
seriesPath.getIDeviceID(), timefilter);
}
public List<TRegionReplicaSet> getPartitionInfoByDevice(
PartialPath devicePath, Filter timefilter) {
return dataPartition.getDataRegionReplicaSetWithTimeFilter(
devicePath.getIDeviceIDAsFullDevice(), timefilter);
}
public TRegionReplicaSet getPartitionInfo(
PartialPath seriesPath, TTimePartitionSlot tTimePartitionSlot) {
return dataPartition
.getDataRegionReplicaSet(seriesPath.getIDeviceID(), tTimePartitionSlot)
.get(0);
}
/**
* Get all time partition ids and combine adjacent time partition if they belong to same data
* region
*/
public List<List<TTimePartitionSlot>> getTimePartitionRange(
PartialPath seriesPath, Filter timefilter) {
return dataPartition.getTimePartitionRange(seriesPath.getIDeviceID(), timefilter);
}
public List<TRegionReplicaSet> getPartitionInfo(IDeviceID deviceID, Filter globalTimeFilter) {
return dataPartition.getDataRegionReplicaSetWithTimeFilter(deviceID, globalTimeFilter);
}
public QueryStatement getQueryStatement() {
if (statement instanceof ExplainAnalyzeStatement) {
return ((ExplainAnalyzeStatement) statement).getQueryStatement();
}
return (QueryStatement) statement;
}
public Statement getTreeStatement() {
return statement;
}
public void setRealStatement(Statement statement) {
this.statement = statement;
}
@Override
public DataPartition getDataPartitionInfo() {
return dataPartition;
}
public void setDataPartitionInfo(DataPartition dataPartition) {
this.dataPartition = dataPartition;
}
@Override
public SchemaPartition getSchemaPartitionInfo() {
return schemaPartition;
}
public void setSchemaPartitionInfo(SchemaPartition schemaPartition) {
this.schemaPartition = schemaPartition;
}
public ISchemaTree getSchemaTree() {
return schemaTree;
}
public void setSchemaTree(ISchemaTree schemaTree) {
this.schemaTree = schemaTree;
}
@Override
public List<TEndPoint> getRedirectNodeList() {
return redirectNodeList;
}
@Override
public void setRedirectNodeList(List<TEndPoint> redirectNodeList) {
this.redirectNodeList = redirectNodeList;
}
@Override
public void addEndPointToRedirectNodeList(TEndPoint endPoint) {
if (redirectNodeList == null) {
redirectNodeList = new ArrayList<>();
}
redirectNodeList.add(endPoint);
}
public Expression getGlobalTimePredicate() {
return globalTimePredicate;
}
public void setGlobalTimePredicate(final Expression timeFilter) {
this.globalTimePredicate = timeFilter;
}
@Override
public TimePredicate getConvertedTimePredicate() {
return globalTimePredicate == null ? null : new TreeModelTimePredicate(globalTimePredicate);
}
@Override
public DatasetHeader getRespDatasetHeader() {
return respDatasetHeader;
}
public void setRespDatasetHeader(final DatasetHeader respDatasetHeader) {
this.respDatasetHeader = respDatasetHeader;
}
public TSDataType getType(final Expression expression) {
// NULL_Operand needn't check
if (expression.getExpressionType().equals(ExpressionType.NULL)) {
return null;
}
if (allDevicesInOneTemplate()
&& (noWhereAndAggregation() || expression instanceof TimeSeriesOperand)) {
TimeSeriesOperand seriesOperand = (TimeSeriesOperand) expression;
return deviceTemplate.getSchemaMap().get(seriesOperand.getPath().getMeasurement()).getType();
}
final TSDataType type = expressionTypes.get(NodeRef.of(expression));
checkArgument(type != null, "Expression is not analyzed: %s", expression);
return type;
}
@Override
public boolean canSkipExecute(final MPPQueryContext context) {
return isFinishQueryAfterAnalyze() || (context.isQuery() && !hasDataSource());
}
private boolean hasDataSource() {
return (dataPartition != null && !dataPartition.isEmpty())
|| (schemaPartition != null && !schemaPartition.isEmpty())
|| statement instanceof ShowQueriesStatement
|| (statement instanceof QueryStatement
&& ((QueryStatement) statement).isAggregationQuery());
}
@Override
public TsBlock constructResultForMemorySource(final MPPQueryContext context) {
final StatementMemorySource memorySource =
new StatementMemorySourceVisitor()
.process(getTreeStatement(), new StatementMemorySourceContext(context, this));
setRespDatasetHeader(memorySource.getDatasetHeader());
return memorySource.getTsBlock();
}
@Override
public boolean isQuery() {
return statement.isQuery();
}
@Override
public boolean needSetHighestPriority() {
// if is this Statement is ShowQueryStatement, set its instances to the highest priority, so
// that the sub-tasks of the ShowQueries instances could be executed first.
return StatementType.SHOW_QUERIES.equals(statement.getType());
}
@Override
public String getStatementType() {
return statement.getType().name();
}
public Map<Expression, Set<Expression>> getCrossGroupByExpressions() {
return crossGroupByExpressions;
}
public void setCrossGroupByExpressions(
final Map<Expression, Set<Expression>> crossGroupByExpressions) {
this.crossGroupByExpressions = crossGroupByExpressions;
}
public FillDescriptor getFillDescriptor() {
return fillDescriptor;
}
public void setFillDescriptor(final FillDescriptor fillDescriptor) {
this.fillDescriptor = fillDescriptor;
}
public boolean hasValueFilter() {
return hasValueFilter;
}
public void setHasValueFilter(final boolean hasValueFilter) {
this.hasValueFilter = hasValueFilter;
}
public Expression getWhereExpression() {
return whereExpression;
}
public void setWhereExpression(final Expression whereExpression) {
this.whereExpression = whereExpression;
}
public Map<IDeviceID, Expression> getDeviceToWhereExpression() {
return deviceToWhereExpression;
}
public void setDeviceToWhereExpression(final Map<IDeviceID, Expression> deviceToWhereExpression) {
this.deviceToWhereExpression = deviceToWhereExpression;
}
public GroupByTimeParameter getGroupByTimeParameter() {
return groupByTimeParameter;
}
public Expression getHavingExpression() {
return havingExpression;
}
public void setHavingExpression(Expression havingExpression) {
this.havingExpression = havingExpression;
}
public void setGroupByTimeParameter(GroupByTimeParameter groupByTimeParameter) {
this.groupByTimeParameter = groupByTimeParameter;
}
public void setGroupByParameter(GroupByParameter groupByParameter) {
this.groupByParameter = groupByParameter;
}
public GroupByParameter getGroupByParameter() {
return groupByParameter;
}
public boolean hasGroupByParameter() {
return groupByParameter != null;
}
public boolean isFinishQueryAfterAnalyze() {
return finishQueryAfterAnalyze;
}
public void setFinishQueryAfterAnalyze(boolean finishQueryAfterAnalyze) {
this.finishQueryAfterAnalyze = finishQueryAfterAnalyze;
}
@Override
public boolean isFailed() {
return failStatus != null;
}
@Override
public TSStatus getFailStatus() {
return this.failStatus;
}
public void setFailStatus(TSStatus status) {
this.failStatus = status;
}
public void setDeviceViewInputIndexesMap(
Map<IDeviceID, List<Integer>> deviceViewInputIndexesMap) {
this.deviceViewInputIndexesMap = deviceViewInputIndexesMap;
}
public Map<IDeviceID, List<Integer>> getDeviceViewInputIndexesMap() {
return deviceViewInputIndexesMap;
}
public Set<Expression> getSourceExpressions() {
return sourceExpressions;
}
public void setSourceExpressions(Set<Expression> sourceExpressions) {
this.sourceExpressions = sourceExpressions;
}
public void setShouldHaveSourceExpression(boolean shouldHaveSourceExpression) {
this.shouldHaveSourceExpression = shouldHaveSourceExpression;
}
public boolean shouldHaveSourceExpression() {
return shouldHaveSourceExpression;
}
public Set<Expression> getSourceTransformExpressions() {
return sourceTransformExpressions;
}
public void setSourceTransformExpressions(Set<Expression> sourceTransformExpressions) {
this.sourceTransformExpressions = sourceTransformExpressions;
}
public Set<Expression> getAggregationExpressions() {
return aggregationExpressions;
}
public void setAggregationExpressions(Set<Expression> aggregationExpressions) {
this.aggregationExpressions = aggregationExpressions;
}
public Set<Expression> getSelectExpressions() {
return selectExpressions;
}
public void setSelectExpressions(Set<Expression> selectExpressions) {
this.selectExpressions = selectExpressions;
}
public Map<IDeviceID, Set<Expression>> getDeviceToSourceExpressions() {
return deviceToSourceExpressions;
}
public void setDeviceToSourceExpressions(
Map<IDeviceID, Set<Expression>> deviceToSourceExpressions) {
this.deviceToSourceExpressions = deviceToSourceExpressions;
}
public Map<IDeviceID, Set<Expression>> getDeviceToSourceTransformExpressions() {
return deviceToSourceTransformExpressions;
}
public void setDeviceToSourceTransformExpressions(
Map<IDeviceID, Set<Expression>> deviceToSourceTransformExpressions) {
this.deviceToSourceTransformExpressions = deviceToSourceTransformExpressions;
}
public Map<IDeviceID, Set<Expression>> getDeviceToAggregationExpressions() {
return deviceToAggregationExpressions;
}
public void setDeviceToAggregationExpressions(
Map<IDeviceID, Set<Expression>> deviceToAggregationExpressions) {
this.deviceToAggregationExpressions = deviceToAggregationExpressions;
}
public Map<IDeviceID, Set<Expression>> getDeviceToSelectExpressions() {
return deviceToSelectExpressions;
}
public void setDeviceToSelectExpressions(
Map<IDeviceID, Set<Expression>> deviceToSelectExpressions) {
this.deviceToSelectExpressions = deviceToSelectExpressions;
}
public Expression getGroupByExpression() {
return groupByExpression;
}
public void setGroupByExpression(Expression groupByExpression) {
this.groupByExpression = groupByExpression;
}
public Map<IDeviceID, Expression> getDeviceToGroupByExpression() {
return deviceToGroupByExpression;
}
public void setDeviceToGroupByExpression(Map<IDeviceID, Expression> deviceToGroupByExpression) {
this.deviceToGroupByExpression = deviceToGroupByExpression;
}
public Set<TSchemaNode> getMatchedNodes() {
return matchedNodes;
}
public void setMatchedNodes(Set<TSchemaNode> matchedNodes) {
this.matchedNodes = matchedNodes;
}
public OrderByParameter getMergeOrderParameter() {
return mergeOrderParameter;
}
public void setMergeOrderParameter(OrderByParameter mergeOrderParameter) {
this.mergeOrderParameter = mergeOrderParameter;
}
public Pair<Template, List<PartialPath>> getTemplateSetInfo() {
return templateSetInfo;
}
public void setTemplateSetInfo(Pair<Template, List<PartialPath>> templateSetInfo) {
this.templateSetInfo = templateSetInfo;
}
public Map<PartialPath, Pair<Template, PartialPath>> getDeviceTemplateSetInfoMap() {
return deviceTemplateSetInfoMap;
}
public void setDeviceTemplateSetInfoMap(
Map<PartialPath, Pair<Template, PartialPath>> deviceTemplateSetInfoMap) {
this.deviceTemplateSetInfoMap = deviceTemplateSetInfoMap;
}
public Map<Integer, Template> getRelatedTemplateInfo() {
return relatedTemplateInfo;
}
public void setRelatedTemplateInfo(Map<Integer, Template> relatedTemplateInfo) {
this.relatedTemplateInfo = relatedTemplateInfo;
}
public List<PartialPath> getSpecifiedTemplateRelatedPathPatternList() {
return specifiedTemplateRelatedPathPatternList;
}
public void setSpecifiedTemplateRelatedPathPatternList(
List<PartialPath> specifiedTemplateRelatedPathPatternList) {
this.specifiedTemplateRelatedPathPatternList = specifiedTemplateRelatedPathPatternList;
}
public void addTypes(Map<NodeRef<Expression>, TSDataType> types) {
this.expressionTypes.putAll(types);
}
public void setExpressionType(Expression expression, TSDataType type) {
this.expressionTypes.put(NodeRef.of(expression), type);
}
public Set<Expression> getDeviceViewOutputExpressions() {
return deviceViewOutputExpressions;
}
public void setDeviceViewOutputExpressions(Set<Expression> deviceViewOutputExpressions) {
this.deviceViewOutputExpressions = deviceViewOutputExpressions;
}
public boolean isDeviceViewSpecialProcess() {
return deviceViewSpecialProcess;
}
public void setDeviceViewSpecialProcess(boolean deviceViewSpecialProcess) {
this.deviceViewSpecialProcess = deviceViewSpecialProcess;
}
public DeviceViewIntoPathDescriptor getDeviceViewIntoPathDescriptor() {
return deviceViewIntoPathDescriptor;
}
public void setDeviceViewIntoPathDescriptor(
DeviceViewIntoPathDescriptor deviceViewIntoPathDescriptor) {
this.deviceViewIntoPathDescriptor = deviceViewIntoPathDescriptor;
}
public IntoPathDescriptor getIntoPathDescriptor() {
return intoPathDescriptor;
}
public void setIntoPathDescriptor(IntoPathDescriptor intoPathDescriptor) {
this.intoPathDescriptor = intoPathDescriptor;
}
public List<String> getTagKeys() {
return tagKeys;
}
public void setTagKeys(List<String> tagKeys) {
this.tagKeys = tagKeys;
}
public Map<List<String>, LinkedHashMap<Expression, List<Expression>>>
getTagValuesToGroupedTimeseriesOperands() {
return tagValuesToGroupedTimeseriesOperands;
}
public void setTagValuesToGroupedTimeseriesOperands(
Map<List<String>, LinkedHashMap<Expression, List<Expression>>>
tagValuesToGroupedTimeseriesOperands) {
this.tagValuesToGroupedTimeseriesOperands = tagValuesToGroupedTimeseriesOperands;
}
public List<TDataNodeLocation> getReadableDataNodeLocations() {
return readableDataNodeLocations;
}
public void setReadableDataNodeLocations(List<TDataNodeLocation> readableDataNodeLocations) {
this.readableDataNodeLocations = readableDataNodeLocations;
}
public boolean isVirtualSource() {
return isVirtualSource;
}
public void setVirtualSource(boolean virtualSource) {
isVirtualSource = virtualSource;
}
public Map<NodeRef<Expression>, TSDataType> getExpressionTypes() {
return expressionTypes;
}
public void setOrderByExpressions(Set<Expression> orderByExpressions) {
this.orderByExpressions = orderByExpressions;
}
public Set<Expression> getOrderByExpressions() {
return orderByExpressions;
}
public Map<IDeviceID, Set<Expression>> getDeviceToOrderByExpressions() {
return deviceToOrderByExpressions;
}
public void setDeviceToOrderByExpressions(
Map<IDeviceID, Set<Expression>> deviceToOrderByExpressions) {
this.deviceToOrderByExpressions = deviceToOrderByExpressions;
}
public void setHasSortNode(boolean hasSortNode) {
this.hasSortNode = hasSortNode;
}
public boolean isHasSortNode() {
return hasSortNode;
}
public Map<IDeviceID, List<SortItem>> getDeviceToSortItems() {
return deviceToSortItems;
}
public void setDeviceToSortItems(Map<IDeviceID, List<SortItem>> deviceToSortItems) {
this.deviceToSortItems = deviceToSortItems;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// Logical View Analysis
/////////////////////////////////////////////////////////////////////////////////////////////////
public void setUseLogicalView(boolean useLogicalView) {
this.useLogicalView = useLogicalView;
}
public boolean useLogicalView() {
return this.useLogicalView;
}
public void setOutputExpressions(List<Pair<Expression, String>> outputExpressions) {
this.outputExpressions = outputExpressions;
}
public List<Pair<Expression, String>> getOutputExpressions() {
return this.outputExpressions;
}
public Ordering getTimeseriesOrderingForLastQuery() {
return timeseriesOrderingForLastQuery;
}
public void setTimeseriesOrderingForLastQuery(Ordering timeseriesOrderingForLastQuery) {
this.timeseriesOrderingForLastQuery = timeseriesOrderingForLastQuery;
}
public Map<IDeviceID, Map<String, Expression>> getLastQueryOutputPathToSourceExpressionMap() {
return lastQueryOutputPathToSourceExpressionMap;
}
public void setLastQueryOutputPathToSourceExpressionMap(
Map<IDeviceID, Map<String, Expression>> lastQueryOutputPathToSourceExpressionMap) {
this.lastQueryOutputPathToSourceExpressionMap = lastQueryOutputPathToSourceExpressionMap;
}
public Set<IDeviceID> getDeviceExistViewSet() {
return deviceExistViewSet;
}
public void setDeviceExistViewSet(Set<IDeviceID> deviceExistViewSet) {
this.deviceExistViewSet = deviceExistViewSet;
}
public Map<Expression, List<Expression>> getLastQueryNonWritableViewSourceExpressionMap() {
return this.lastQueryNonWritableViewSourceExpressionMap;
}
public void setLastQueryNonWritableViewSourceExpressionMap(
Map<Expression, List<Expression>> lastQueryNonWritableViewSourceExpressionMap) {
this.lastQueryNonWritableViewSourceExpressionMap = lastQueryNonWritableViewSourceExpressionMap;
}
public ModelInferenceDescriptor getModelInferenceDescriptor() {
return modelInferenceDescriptor;
}
public ModelInformation getModelInformation() {
if (modelInferenceDescriptor == null) {
return null;
}
return modelInferenceDescriptor.getModelInformation();
}
public void setModelInferenceDescriptor(ModelInferenceDescriptor modelInferenceDescriptor) {
this.modelInferenceDescriptor = modelInferenceDescriptor;
}
public Map<IDeviceID, IDeviceID> getOutputDeviceToQueriedDevicesMap() {
return outputDeviceToQueriedDevicesMap;
}
public void setOutputDeviceToQueriedDevicesMap(
Map<IDeviceID, IDeviceID> outputDeviceToQueriedDevicesMap) {
this.outputDeviceToQueriedDevicesMap = outputDeviceToQueriedDevicesMap;
}
public Map<IDeviceID, Set<Expression>> getDeviceToOutputExpressions() {
return deviceToOutputExpressions;
}
public void setDeviceToOutputExpressions(
Map<IDeviceID, Set<Expression>> deviceToOutputExpressions) {
this.deviceToOutputExpressions = deviceToOutputExpressions;
}
public boolean isLastLevelUseWildcard() {
return lastLevelUseWildcard;
}
public void setLastLevelUseWildcard(boolean lastLevelUseWildcard) {
this.lastLevelUseWildcard = lastLevelUseWildcard;
}
public boolean isUseTopKNode() {
return useTopKNode;
}
public void setUseTopKNode() {
this.useTopKNode = true;
}
public void setDeviceList(List<PartialPath> deviceList) {
this.deviceList = deviceList;
}
public List<PartialPath> getDeviceList() {
return deviceList;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// All Queries Devices Set In One Template
/////////////////////////////////////////////////////////////////////////////////////////////////
public boolean allDevicesInOneTemplate() {
return this.deviceTemplate != null;
}
public Template getDeviceTemplate() {
return this.deviceTemplate;
}
public void setDeviceTemplate(Template template) {
this.deviceTemplate = template;
}
public boolean noWhereAndAggregation() {
return noWhereAndAggregation;
}
public void setNoWhereAndAggregation(boolean value) {
this.noWhereAndAggregation = value;
}
public List<String> getMeasurementList() {
return this.measurementList;
}
public void setMeasurementList(List<String> measurementList) {
this.measurementList = measurementList;
}
public List<IMeasurementSchema> getMeasurementSchemaList() {
return this.measurementSchemaList;
}
public void setMeasurementSchemaList(List<IMeasurementSchema> measurementSchemaList) {
this.measurementSchemaList = measurementSchemaList;
}
public void setTemplateWildCardQuery() {
this.templateWildCardQuery = true;
}
public boolean isTemplateWildCardQuery() {
return this.templateWildCardQuery;
}
public void setFromWhere(FilterNode filterNode) {
this.fromWhereFilterNodes.add(NodeRef.of(filterNode));
}
public boolean fromWhere(FilterNode filterNode) {
return fromWhereFilterNodes.contains(NodeRef.of(filterNode));
}
@Override
public void setDatabaseName(String database) {
this.databaseName = database;
}
@Override
public String getDatabaseName() {
return databaseName;
}
}
|
google/gapid | 36,496 | gapic/src/main/com/google/gapid/widgets/TabComposite.java | /*
* Copyright (C) 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gapid.widgets;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.gapid.models.Analytics;
import com.google.gapid.models.Analytics.View;
import com.google.gapid.util.Events;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.graphics.Region;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Shell;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
public class TabComposite extends Composite {
private static final int TITLE_WIDTH = 50;
private static final int SEP_HEIGHT = 2;
private static final int BAR_MARGIN = 6;
private static final int TAB_MARGIN = 10;
private static final int FOLDER_MARGIN = 5; // needs to be odd.
private static final int ICON_SIZE = 24;
private static final int MIN_WIDTH = 50;
private static final int MIN_HEIGHT = 75;
protected final Theme theme;
private final Group group;
private final Events.ListenerCollection<Listener> listeners = Events.listeners(Listener.class);
private Folder maximizedFolder = null;
protected Hover hovered = Hover.NONE;
private Hover mouseDown = Hover.NONE;
protected Dragger dragger = null;
public TabComposite(Composite parent, Theme theme, boolean horizontal) {
super(parent, SWT.BORDER | SWT.DOUBLE_BUFFERED);
this.theme = theme;
this.group = horizontal ? new HorizontalGroup(1) : new VerticalGroup(1);
setLayout(new Layout() {
@Override
protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) {
return layoutComputeSize(wHint, hHint, flushCache);
}
@Override
protected void layout(Composite composite, boolean flushCache) {
layoutLayout();
}
@Override
protected boolean flushCache(Control control) {
return true;
}
});
addListener(SWT.Paint, e -> {
getElement().draw(e.gc, false, false);
});
addListener(SWT.MouseDown, e -> {
if (e.button == 1) {
mouseDown = hovered;
switch (mouseDown.type) {
case Button:
if (maximizedFolder == null) {
mouseDown.folder.maximized = true;
maximizedFolder = mouseDown.folder;
} else {
mouseDown.folder.maximized = false;
maximizedFolder = null;
}
requestLayout();
break;
case Tab:
if (mouseDown.folder.updateCurrent(mouseDown.tab.control)) {
listeners.fire().onTabShown(mouseDown.tab.info);
}
break;
default:
// Do nothing.
}
}
});
addListener(SWT.MouseMove, e -> {
switch (mouseDown.type) {
case Tab:
if (dragger == null) {
dragger = new Dragger(theme, getShell(), getDisplay().map(this, null, getClientArea()),
theme.tabFolderPlaceholderFill(), mouseDown);
setCursor(getDisplay().getSystemCursor(SWT.CURSOR_SIZEALL));
mouseDown.folder.redrawBar();
}
dragger.shell.setLocation(getDisplay().getCursorLocation());
getElement().redrawBar(dragger.location.x, dragger.location.y, e.x, e.y);
dragger.location.x = e.x;
dragger.location.y = e.y;
Hover current = group.find(group, 0, e.x, e.y, false);
if (current.isFolder()) {
Location location = getLocation(current.folder, e.x, e.y);
if (location != null) {
dragger.overlay.show(location.highlight(current.folder));
dragger.shell.setActive();
} else {
dragger.overlay.hide();
}
} else {
dragger.overlay.hide();
}
break;
case Separator:
mouseDown.group.moveSeparator(mouseDown.index, e.x, e.y);
setRedraw(false);
try {
layoutLayout();
} finally {
setRedraw(true);
}
update();
break;
default:
updateHover(getElement().find(group, 0, e.x, e.y, false));
}
});
addListener(SWT.MouseUp, e -> {
mouseDown = Hover.NONE;
if (dragger != null) {
Hover src = dragger.tab;
Hover dst = getElement().find(group, 0, e.x, e.y, true);
dragger.close();
setCursor(null);
dragger = null;
switch (dst.type) {
case Tab:
listeners.fire().onTabMoved(src.tab.info);
if (dst.tab == null) {
src.folder.removeTab(src.tab);
dst.folder.addTab(src.tab);
src.folder.redrawBar();
if (src.folder != dst.folder) {
dst.folder.redrawBar();
}
} else if (src.folder != dst.folder) {
src.folder.removeTab(src.tab);
dst.folder.addTab(src.tab, dst.tab);
src.folder.redrawBar();
dst.folder.redrawBar();
} else {
dst.folder.moveTab(src.tab, dst.tab);
src.folder.redrawBar();
}
group.merge();
dst.folder.updateCurrent(src.tab.control);
break;
case Folder:
Location location = getLocation(dst.folder, e.x, e.y);
if (location != null) {
Folder newFolder = dst.group.newSubFolder(location, dst.index);
src.folder.removeTab(src.tab);
newFolder.addTab(src.tab);
src.folder.redrawBar();
newFolder.redrawBar();
group.merge();
requestLayout();
}
break;
default:
// Do nothing.
}
}
updateHover(getElement().find(group, 0, e.x, e.y, false));
});
addListener(SWT.MouseExit, e -> updateHover(Hover.NONE));
}
private static Location getLocation(Folder folder, int x, int y) {
switch (3 * (x - folder.x) / folder.w) {
case 0: return Location.Left;
case 1:
switch (3 * (y - folder.y) / folder.h) {
case 0: return Location.Top;
case 2: return Location.Bottom;
default: return null;
}
case 2: return Location.Right;
default: return null;
}
}
private void updateHover(Hover newHover) {
if (!hovered.isTab()) {
if (newHover.isTab()) {
newHover.folder.redrawBar();
}
} else if (!newHover.isTab()) {
hovered.folder.redrawBar();
} else if (hovered.folder != newHover.folder) {
hovered.folder.redrawBar();
newHover.folder.redrawBar();
} else {
newHover.folder.redrawBar();
}
hovered = newHover;
if (hovered.isSeparator()) {
setCursor(getDisplay().getSystemCursor(hovered.cursor));
} else {
setCursor(null);
}
}
public Group getRoot() {
return group;
}
public boolean showTab(Object id) {
return group.showTab(id);
}
public void addTabToFirstFolder(TabInfo info) {
group.addTabToFirstFolder(info);
}
public void addTabToLargestFolder(TabInfo info) {
group.addTabToLargestFolder(info);
}
public boolean disposeTab(Object id) {
if (group.disposeTab(id)) {
group.merge();
return true;
}
return false;
}
public void visit(Visitor visitor) {
group.visit(visitor);
}
public void addListener(Listener listener) {
listeners.addListener(listener);
}
public void removeListener(Listener listener) {
listeners.removeListener(listener);
}
protected Point layoutComputeSize(int wHint, int hHint, boolean flushCache) {
int w = 0, h = 0;
for (Control child : getChildren()) {
Point size = child.computeSize(wHint, hHint, flushCache);
w = Math.max(size.x, w);
h = Math.max(size.y, h);
}
return new Point((wHint == SWT.DEFAULT) ? w : wHint, (hHint == SWT.DEFAULT) ? h : hHint);
}
protected void layoutLayout() {
Rectangle size = getClientArea();
Set<Control> controls = Sets.newIdentityHashSet();
controls.addAll(Arrays.asList(getChildren()));
getElement().setBounds(controls, 0, 0, size.width, size.height);
for (Control child : controls) {
child.setVisible(false);
}
}
private Element getElement() {
return (maximizedFolder == null) ? group : maximizedFolder;
}
/**
* Information about a single tab in a folder.
*/
public static class TabInfo {
public final Object id;
public final Analytics.View view;
public final String label;
public final Function<Composite, Control> contentFactory;
public TabInfo(
Object id, View view, String label, Function<Composite, Control> contentFactory) {
this.id = id;
this.view = view;
this.label = label;
this.contentFactory = contentFactory;
}
}
@SuppressWarnings("unused")
public interface Visitor {
public default void group(boolean horizontal, int weight) { /* do nothing */ }
public default void endGroup() { /* do nothing */ }
public default void folder(int weight) { /* do nothing */ }
public default void tab(TabInfo tab) { /* do nothing */ }
public default void endFolder() { /* do nothing */ }
}
private abstract class Element {
protected int x, y, w, h;
protected int weight = -1;
public Element() {
}
public abstract boolean showTab(Object id);
public abstract void addTabToFirstFolder(TabInfo tab);
public abstract void addTabToLargestFolder(TabInfo tab);
public abstract boolean disposeTab(Object id);
public abstract void setBounds(Set<Control> controls, int x, int y, int w, int h);
protected void setBounds(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
protected boolean contains(int ex, int ey) {
return ex >= x && ex < x + w && ey >= y && ey < y + h;
}
protected void draw(GC gc, boolean hBorder, boolean vBorder) {
if (hBorder) {
gc.setForeground(theme.tabFolderLine());
gc.drawLine(x, y - FOLDER_MARGIN / 2 - 1, x + w, y - FOLDER_MARGIN / 2 - 1);
}
if (vBorder) {
gc.setForeground(theme.tabFolderLine());
gc.drawLine(x - FOLDER_MARGIN / 2 - 1, y, x - FOLDER_MARGIN / 2 - 1, y + h);
}
draw(gc);
}
protected abstract void draw(GC gc);
protected abstract Hover find(Group parent, int index, int mx, int my, boolean includeTrailing);
protected abstract void redrawBar(int x1, int y1, int x2, int y2);
protected abstract MergeState merge();
protected abstract void visit(Visitor visitor);
}
public abstract class Group extends Element {
protected final List<Element> children = Lists.newArrayList();
private final boolean childHBorder, childVBorder;
public Group(int weight, boolean childHBorder, boolean childVBorder) {
this.weight = weight;
this.childHBorder = childHBorder;
this.childVBorder = childVBorder;
}
public Folder newFolder(int folderWeight) {
Folder folder = new Folder(folderWeight);
children.add(folder);
return folder;
}
public Group newGroup(int groupWeight) {
Group result = createGroup(groupWeight);
children.add(result);
return result;
}
@Override
public boolean showTab(Object id) {
for (Element child : children) {
if (child.showTab(id)) {
return true;
}
}
return false;
}
@Override
public void addTabToFirstFolder(TabInfo tab) {
Element firstChild = children.get(0);
if (firstChild instanceof Folder) {
((Folder)firstChild).newTab(tab);
} else {
firstChild.weight /= 2;
Folder folder = new Folder(firstChild.weight);
children.add(0, folder);
folder.newTab(tab);
}
}
@Override
public void addTabToLargestFolder(TabInfo tab) {
int max = 0;
for (int i = 1; i < children.size(); i++) {
if (children.get(i).weight > children.get(max).weight) {
max = i;
}
}
children.get(max).addTabToLargestFolder(tab);
}
@Override
public boolean disposeTab(Object id) {
for (Element child : children) {
if (child.disposeTab(id)) {
return true;
}
}
return false;
}
protected abstract Group createGroup(int newWeight);
protected abstract Folder newSubFolder(Location location, int index);
@Override
public void setBounds(Set<Control> controls, int x, int y, int w, int h) {
setBounds(x, y, w, h);
if (children.size() == 1) {
children.get(0).setBounds(controls, x, y, w, h);
} else {
int weightSum = 0;
for (Element child : children) {
if (child.weight <= 0) {
weightSum = -1;
break;
}
weightSum += child.weight;
}
setChildBounds(controls, weightSum);
}
}
protected abstract void setChildBounds(Set<Control> controls, int weightTotal);
@Override
protected void draw(GC gc) {
for (int i = 0; i < children.size(); i++) {
children.get(i).draw(gc, childHBorder && i > 0, childVBorder && i > 0);
}
}
@Override
protected void redrawBar(int x1, int y1, int x2, int y2) {
boolean firstDone = x1 < 0 || y1 < 0, secondDone = x2 < 0 || y2 < 0;
if (firstDone && secondDone) {
return;
}
for (Element child : children) {
boolean first = child.contains(x1, y1);
boolean second = child.contains(x2, y2);
if (first && second) {
child.redrawBar(x1, y1, x2, y2);
return;
} else if (first) {
child.redrawBar(x1, y1, -1, -1);
if (secondDone) {
return;
}
firstDone = true;
} else if (second) {
child.redrawBar(x2, y2, -1, -1);
if (firstDone) {
return;
}
secondDone = true;
}
}
}
@Override
protected Hover find(Group parent, int index, int mx, int my, boolean includeTrailing) {
for (int i = 0; i < children.size(); i++) {
Element child = children.get(i);
if (mx >= child.x && mx < child.x + child.w &&
my >= child.y && my < child.y + child.h) {
return child.find(this, i, mx, my, includeTrailing);
}
}
return Hover.NONE;
}
protected abstract void moveSeparator(int index, int sx, int sy);
@Override
protected MergeState merge() {
for (ListIterator<Element> it = children.listIterator(); it.hasNext(); ) {
Element current = it.next();
MergeState state = current.merge();
if (state == MergeState.REMOVE) {
it.remove();
} else if (state == MergeState.DO_NOTHING) {
// Do nothing.
} else {
if (state.replacement instanceof Folder) {
state.replacement.weight = current.weight;
it.set(state.replacement);
} else {
// The current child (C) is a group where it's only child is also a group (G). Thus,
// C is superfluous and can be removed. However, G can not just become our child, since
// it has the same horizontal vs. vertical layout as us, while our children must have
// the opposite from us. This does mean, however, that G, too, is superfluous and all
// it's children - our great-grand-children - can just become our children.
it.remove(); // Has to be done before we add any new children.
int totalWeight = 0;
for (Element child : ((Group)state.replacement).children) {
it.add(child);
totalWeight += child.weight;
}
for (Element child : ((Group)state.replacement).children) {
child.weight = (int)((child.weight * current.weight) / (double)totalWeight);
}
}
}
}
switch (children.size()) {
case 0: return MergeState.REMOVE;
case 1: return MergeState.replace(children.get(0));
default: return MergeState.DO_NOTHING;
}
}
}
private static enum Location {
Left, Right, Top, Bottom;
public Rectangle highlight(Folder f) {
switch (this) {
case Left: return new Rectangle(f.x, f.y, f.w / 3, f.h);
case Right: return new Rectangle(f.x + 2 * f.w / 3, f.y, f.w / 3, f.h);
case Top: return new Rectangle(f.x, f.y, f.w, f.h / 3);
case Bottom: return new Rectangle(f.x, f.y + 2 * f.h / 3, f.w, f.h / 3);
default: throw new AssertionError();
}
}
}
private class HorizontalGroup extends Group {
public HorizontalGroup(int weight) {
super(weight, false, true);
}
@Override
protected void setChildBounds(Set<Control> controls, int weightTotal) {
int cw = w - (children.size() - 1) * FOLDER_MARGIN;
if (weightTotal <= 0) {
int fw = cw / children.size();
int rem = cw % children.size();
for (int i = 0, fx = x; i < children.size(); i++, rem--) {
int add = rem > 0 ? 1 : 0;
children.get(i).setBounds(controls, fx, y, fw + add, h);
children.get(i).weight = fw;
fx += fw + add + FOLDER_MARGIN;
}
} else {
int diff = 0;
if (weightTotal != cw) {
for (Element child : children) {
child.weight = (int)((child.weight * cw) / (double)weightTotal);
diff += child.weight;
}
diff = cw - diff;
if (diff >= children.size()) {
for (Element child : children) {
child.weight++;
}
diff -= children.size();
}
}
for (int i = 0, fx = x; i < children.size(); i++, diff--) {
int add = diff > 0 ? 1 : 0;
int nw = children.get(i).weight + add;
children.get(i).setBounds(controls, fx, y, nw, h);
fx += nw + FOLDER_MARGIN;
}
}
}
@Override
protected Group createGroup(int newWeight) {
return new VerticalGroup(newWeight);
}
@Override
protected Folder newSubFolder(Location location, int index) {
switch (location) {
case Left: {
int nw = children.get(index).weight /= 2;
Folder folder = new Folder(nw);
children.add(index, folder);
return folder;
}
case Right: {
int nw = children.get(index).weight /= 2;
Folder folder = new Folder(nw);
children.add(index + 1, folder);
return folder;
}
case Top: {
Element old = children.get(index);
Group g = createGroup(old.weight);
children.set(index, g);
Folder folder = g.newFolder(old.weight);
g.children.add(old);
return folder;
}
case Bottom:{
Element old = children.get(index);
Group g = createGroup(old.weight);
children.set(index, g);
g.children.add(old);
return g.newFolder(old.weight);
}
default:
throw new AssertionError();
}
}
@Override
protected Hover find(Group parent, int index, int mx, int my, boolean includeTrailing) {
Hover result = super.find(parent, index, mx, my, includeTrailing);
if (result == Hover.NONE && children.size() > 1) {
Element before = children.get(0);
for (int i = 1; i < children.size(); i++) {
Element now = children.get(i);
if (mx >= before.x + before.w && mx < now.x) {
return Hover.separator(this, i, SWT.CURSOR_SIZEWE);
}
before = now;
}
}
return result;
}
@Override
protected void moveSeparator(int index, int sx, int sy) {
Element before = children.get(index - 1);
Element after = children.get(index);
int newBeforeW = sx - FOLDER_MARGIN / 2 - before.x;
int newAfterW = after.x + after.w - sx - FOLDER_MARGIN / 2 - 1;
if (newBeforeW >= MIN_WIDTH && newAfterW >= MIN_WIDTH) {
before.weight = newBeforeW;
after.weight = newAfterW;
}
}
@Override
protected void visit(Visitor visitor) {
visitor.group(true, weight);
for (Element child : children) {
child.visit(visitor);
}
visitor.endGroup();
}
}
private class VerticalGroup extends Group {
public VerticalGroup(int weight) {
super(weight, true, false);
}
@Override
protected void setChildBounds(Set<Control> controls, int weightTotal) {
int ch = h - (children.size() - 1) * FOLDER_MARGIN;
if (weightTotal <= 0) {
int fh = ch / children.size();
int rem = ch % children.size();
for (int i = 0, fy = y; i < children.size(); i++, rem--) {
int add = rem > 0 ? 1 : 0;
children.get(i).setBounds(controls, x, fy, w, fh + add);
children.get(i).weight = fh;
fy += fh + add + FOLDER_MARGIN;
}
} else {
int diff = 0;
if (weightTotal != ch) {
for (Element child : children) {
child.weight = (int)((child.weight * ch) / (double)weightTotal);
diff += child.weight;
}
diff = ch - diff;
if (diff >= children.size()) {
for (Element child : children) {
child.weight++;
}
diff -= children.size();
}
}
for (int i = 0, fy = y; i < children.size(); i++, diff--) {
int add = diff > 0 ? 1 : 0;
int nh = children.get(i).weight + add;
children.get(i).setBounds(controls, x, fy, w, nh);
fy += nh + FOLDER_MARGIN;
}
}
}
@Override
protected Group createGroup(int newWeight) {
return new HorizontalGroup(newWeight);
}
@Override
protected Folder newSubFolder(Location location, int index) {
switch (location) {
case Left: {
Element old = children.get(index);
Group g = createGroup(old.weight);
children.set(index, g);
Folder folder = g.newFolder(old.weight);
g.children.add(old);
return folder;
}
case Right:{
Element old = children.get(index);
Group g = createGroup(old.weight);
children.set(index, g);
g.children.add(old);
return g.newFolder(old.weight);
}
case Top: {
int nw = children.get(index).weight /= 2;
Folder folder = new Folder(nw);
children.add(index, folder);
return folder;
}
case Bottom: {
int nw = children.get(index).weight /= 2;
Folder folder = new Folder(nw);
children.add(index + 1, folder);
return folder;
}
default:
throw new AssertionError();
}
}
@Override
protected Hover find(Group parent, int index, int mx, int my, boolean includeTrailing) {
Hover result = super.find(parent, index, mx, my, includeTrailing);
if (result == Hover.NONE && children.size() > 1) {
Element before = children.get(0);
for (int i = 1; i < children.size(); i++) {
Element now = children.get(i);
if (my >= before.y + before.h && my < now.y) {
return Hover.separator(this, i, SWT.CURSOR_SIZENS);
}
before = now;
}
}
return result;
}
@Override
protected void moveSeparator(int index, int sx, int sy) {
Element before = children.get(index - 1);
Element after = children.get(index);
int newBeforeH = sy - FOLDER_MARGIN / 2 - before.y;
int newAfterH = after.y + after.h - sy - FOLDER_MARGIN / 2 - 1;
if (newBeforeH >= MIN_HEIGHT && newAfterH >= MIN_HEIGHT) {
before.weight = newBeforeH;
after.weight = newAfterH;
}
}
@Override
protected void visit(Visitor visitor) {
visitor.group(false, weight);
for (Element child : children) {
child.visit(visitor);
}
visitor.endGroup();
}
}
public class Folder extends Element {
private final List<Tab> tabs = Lists.newArrayList();
private int titleHeight;
private Control current;
protected boolean maximized;
public Folder(int weight) {
this.weight = weight;
}
public void newTab(TabInfo info) {
GC gc = new GC(TabComposite.this);
gc.setFont(theme.selectedTabTitleFont());
Point size = gc.textExtent(info.label);
gc.dispose();
addTab(new Tab(info, info.contentFactory.apply(TabComposite.this), size));
}
@Override
public boolean showTab(Object id) {
for (Tab tab : tabs) {
if (Objects.equals(tab.info.id, id)) {
updateCurrent(tab.control);
return true;
}
}
return false;
}
@Override
public void addTabToFirstFolder(TabInfo tab) {
newTab(tab);
}
@Override
public void addTabToLargestFolder(TabInfo tab) {
newTab(tab);
}
@Override
public boolean disposeTab(Object id) {
for (Tab tab : tabs) {
if (Objects.equals(tab.info.id, id)) {
removeTab(tab);
tab.control.dispose();
return true;
}
}
return false;
}
@Override
public void setBounds(Set<Control> controls, int x, int y, int w, int h) {
redrawBar(); // redraw the old area
setBounds(x, y, w, h);
this.titleHeight = getMaxTitleHeight();
int barH = BAR_MARGIN + titleHeight + BAR_MARGIN + SEP_HEIGHT + BAR_MARGIN;
for (Tab tab : tabs) {
tab.control.setBounds(x, y + barH, w, h - barH);
tab.control.setVisible(tab.control == current);
controls.remove(tab.control);
}
redrawBar(); // redraw the new area
}
private int getMaxTitleHeight() {
int height = 0;
for (Tab tab : tabs) {
height = Math.max(height, tab.titleSize.y);
}
return height;
}
protected void addTab(Tab tab) {
tabs.add(tab);
if (current == null) {
current = tab.control;
}
}
protected void addTab(Tab tab, Tab before) {
for (int i = 0; i < tabs.size(); i++) {
if (tabs.get(i) == before) {
tabs.add(i, tab);
return;
}
}
}
protected void moveTab(Tab from, Tab to) {
for (int i = 0; i < tabs.size(); i++) {
if (tabs.get(i) == to) {
tabs.remove(from);
tabs.add(i, from);
return;
}
}
}
protected void removeTab(Tab tab) {
tabs.remove(tab);
if (current == tab.control) {
current = tabs.isEmpty() ? null : tabs.get(0).control;
requestLayout();
}
redrawBar();
}
protected boolean updateCurrent(Control newCurrent) {
if (current != newCurrent) {
current = newCurrent;
requestLayout();
redrawBar();
return true;
}
return false;
}
@Override
protected void redrawBar(int x1, int y1, int x2, int y2) {
int tabH = BAR_MARGIN + titleHeight + BAR_MARGIN;
if ((x1 >= x && x1 < x + w && y1 >= y && y1 < y + tabH) ||
(x2 >= x && x2 < x + w && y2 >= y && y2 < y + tabH)) {
redrawBar();
}
}
void redrawBar() {
redraw(x, y, w, BAR_MARGIN + titleHeight + BAR_MARGIN + SEP_HEIGHT + BAR_MARGIN, false);
}
@Override
protected void draw(GC gc) {
int tabH = BAR_MARGIN + titleHeight + BAR_MARGIN;
gc.setBackground(theme.tabBackgound());
gc.fillRectangle(x, y, w, tabH + SEP_HEIGHT);
gc.setForeground(theme.tabFolderLine());
gc.drawLine(x, y + tabH + SEP_HEIGHT - 1, x + w, y + tabH + SEP_HEIGHT - 1);
gc.setClipping(x, y, w - ICON_SIZE, h);
int tabX = x;
for (Tab tab : tabs) {
int tabW = TAB_MARGIN + Math.max(TITLE_WIDTH, tab.titleSize.x) + TAB_MARGIN;
if (dragger != null) {
if (dragger.tab.tab == tab) {
continue;
} else if (dragger.contains(tabX, y, tabW, tabH)) {
drawPlaceholder(gc, tabX, y, tabW);
tabX += tabW;
}
}
if (hovered != null && tab == hovered.tab) {
gc.setBackground(theme.tabFolderHovered());
gc.fillRectangle(tabX, y, tabW, tabH + 1);
} else if (tab.control == current) {
gc.setBackground(theme.tabFolderSelected());
gc.fillRectangle(tabX, y, tabW, tabH + 1);
}
int dx = (tabW - tab.titleSize.x) / 2;
gc.setForeground(theme.tabTitle());
if (tab.control == current) {
gc.setBackground(theme.tabFolderLineSelected());
gc.fillRectangle(tabX, y + tabH, tabW, SEP_HEIGHT);
gc.setFont(theme.selectedTabTitleFont());
gc.drawText(tab.info.label, tabX + dx, y + BAR_MARGIN, SWT.DRAW_TRANSPARENT);
gc.setFont(null);
} else {
gc.drawText(tab.info.label, tabX + dx, y + BAR_MARGIN, SWT.DRAW_TRANSPARENT);
}
tabX += tabW;
}
if (dragger != null &&
dragger.location.x >= tabX && dragger.location.x < x + w &&
dragger.location.y >= y && dragger.location.y < y + tabH) {
int tabW = Math.max(TITLE_WIDTH, dragger.tab.tab.titleSize.x);
drawPlaceholder(gc, tabX, y, tabW);
}
gc.setClipping((Rectangle)null);
gc.drawImage(maximized ? theme.fullscreenExit() : theme.fullscreen(),
x + w - ICON_SIZE, y + (tabH - ICON_SIZE) / 2);
}
private void drawPlaceholder(GC gc, int px, int py, int pw) {
gc.setBackground(theme.tabFolderPlaceholderFill());
gc.setForeground(theme.tabFolderPlaceholderStroke());
gc.fillRectangle(px, py, pw, 2 * BAR_MARGIN + titleHeight + 1);
gc.drawRectangle(px, py, pw, 2 * BAR_MARGIN + titleHeight + 1);
}
@Override
protected Hover find(Group parent, int index, int mx, int my, boolean includeTrailing) {
int tabH = BAR_MARGIN + titleHeight + BAR_MARGIN;
if (mx < x || mx >= x + w || my < y || my >= y + h) {
return Hover.NONE;
} else if (my >= y + tabH) {
return Hover.folder(parent, index, this);
}
if (mx >= x + w - ICON_SIZE) {
return Hover.button(this);
}
int tabX = x;
for (Tab tab : tabs) {
int tabW = TAB_MARGIN + Math.max(TITLE_WIDTH, tab.titleSize.x) + TAB_MARGIN;
if (mx >= tabX && mx < tabX + tabW) {
return Hover.tab(this, tab);
}
tabX += tabW;
}
return includeTrailing ? Hover.tab(this, null) : Hover.NONE;
}
@Override
protected MergeState merge() {
return tabs.isEmpty() ? MergeState.REMOVE : MergeState.DO_NOTHING;
}
@Override
protected void visit(Visitor visitor) {
visitor.folder(weight);
for (Tab tab : tabs) {
visitor.tab(tab.info);
}
visitor.endFolder();
}
}
public static interface Listener extends Events.Listener {
public void onTabShown(TabInfo tab);
public void onTabMoved(TabInfo tab);
}
private static class Tab {
public final TabInfo info;
public final Control control;
public final Point titleSize;
public Tab(TabInfo info, Control control, Point titleSize) {
this.info = info;
this.control = control;
this.titleSize = titleSize;
}
}
private static class Hover {
public static final Hover NONE = new Hover(Type.None, null, 0, 0, null, null);
public final Type type;
public final Group group;
public final int index;
public final int cursor;
public final Folder folder;
public final Tab tab;
private Hover(Type type, Group group, int index, int cursor, Folder folder, Tab tab) {
this.type = type;
this.group = group;
this.index = index;
this.cursor = cursor;
this.folder = folder;
this.tab = tab;
}
public static Hover separator(Group group, int index, int cursor) {
return new Hover(Type.Separator, group, index, cursor, null, null);
}
public static Hover button(Folder folder) {
return new Hover(Type.Button, null, 0, 0, folder, null);
}
public static Hover folder(Group parent, int index, Folder folder) {
return new Hover(Type.Folder, parent, index, 0, folder, null);
}
public static Hover tab(Folder folder, Tab tab) {
return new Hover(Type.Tab, null, 0, 0, folder, tab);
}
public boolean isSeparator() {
return type == Type.Separator;
}
public boolean isFolder() {
return type == Type.Folder;
}
public boolean isTab() {
return type == Type.Tab;
}
public static enum Type {
None, Separator, Button, Folder, Tab;
}
}
private static class MergeState {
public static final MergeState DO_NOTHING = new MergeState(null);
public static final MergeState REMOVE = new MergeState(null);
public final Element replacement;
private MergeState(Element replacement) {
this.replacement = replacement;
}
public static MergeState replace(Element replacement) {
return new MergeState(replacement);
}
}
private static class Overlay {
private final Shell shell;
private Region region = null;
public Overlay(Shell parent, Rectangle bounds, Color bg) {
this.shell = new Shell(parent, SWT.NO_TRIM | SWT.MODELESS | SWT.NO_FOCUS | SWT.ON_TOP);
shell.setBounds(bounds);
shell.setEnabled(false);
shell.setAlpha(128);
shell.setBackground(bg);
}
public void hide() {
shell.setVisible(false);
}
public void show(Rectangle highlight) {
if (region != null) {
region.dispose();
}
region = new Region();
region.add(highlight);
shell.setRegion(region);
shell.setEnabled(false);
shell.setVisible(true);
}
public void close() {
shell.dispose();
if (region != null) {
region.dispose();
}
}
}
private static class Dragger {
public final Overlay overlay;
public final Shell shell;
public final Hover tab;
public final Point location = new Point(-1, -1);
public Dragger(Theme theme, Shell parent, Rectangle bounds, Color bg, Hover tab) {
this.overlay = new Overlay(parent, bounds, bg);
this.shell = new Shell(parent, SWT.NO_TRIM | SWT.MODELESS | SWT.NO_FOCUS | SWT.ON_TOP);
this.tab = tab;
shell.setLayout(new FillLayout());
shell.setSize(tab.tab.titleSize.x + 2 * TAB_MARGIN, tab.tab.titleSize.y + 2 * BAR_MARGIN);
shell.setEnabled(false);
Canvas canvas = new Canvas(shell, SWT.NONE);
canvas.addListener(SWT.Paint, e -> {
e.gc.setFont(theme.selectedTabTitleFont());
e.gc.drawText(tab.tab.info.label, TAB_MARGIN, BAR_MARGIN, SWT.DRAW_TRANSPARENT);
});
shell.setVisible(true);
}
public boolean contains(int x, int y, int w, int h) {
return location.x >= 0 && location.y >= 0 &&
x <= location.x && x + w > location.x &&
y <= location.y && y + h > location.y;
}
public void close() {
overlay.close();
shell.dispose();
}
}
}
|
googleapis/google-cloud-java | 36,387 | java-speech/google-cloud-speech/src/test/java/com/google/cloud/speech/v1p1beta1/AdaptationClientTest.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.speech.v1p1beta1;
import static com.google.cloud.speech.v1p1beta1.AdaptationClient.ListCustomClassesPagedResponse;
import static com.google.cloud.speech.v1p1beta1.AdaptationClient.ListPhraseSetPagedResponse;
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.protobuf.AbstractMessage;
import com.google.protobuf.Empty;
import com.google.protobuf.FieldMask;
import com.google.protobuf.Timestamp;
import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import 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 AdaptationClientTest {
private static MockAdaptation mockAdaptation;
private static MockServiceHelper mockServiceHelper;
private LocalChannelProvider channelProvider;
private AdaptationClient client;
@BeforeClass
public static void startStaticServer() {
mockAdaptation = new MockAdaptation();
mockServiceHelper =
new MockServiceHelper(
UUID.randomUUID().toString(), Arrays.<MockGrpcService>asList(mockAdaptation));
mockServiceHelper.start();
}
@AfterClass
public static void stopServer() {
mockServiceHelper.stop();
}
@Before
public void setUp() throws IOException {
mockServiceHelper.reset();
channelProvider = mockServiceHelper.createChannelProvider();
AdaptationSettings settings =
AdaptationSettings.newBuilder()
.setTransportChannelProvider(channelProvider)
.setCredentialsProvider(NoCredentialsProvider.create())
.build();
client = AdaptationClient.create(settings);
}
@After
public void tearDown() throws Exception {
client.close();
}
@Test
public void createPhraseSetTest() throws Exception {
PhraseSet expectedResponse =
PhraseSet.newBuilder()
.setName(PhraseSetName.of("[PROJECT]", "[LOCATION]", "[PHRASE_SET]").toString())
.addAllPhrases(new ArrayList<PhraseSet.Phrase>())
.setBoost(93922211)
.setKmsKeyName("kmsKeyName412586233")
.setKmsKeyVersionName("kmsKeyVersionName-1798811307")
.setUid("uid115792")
.setDisplayName("displayName1714148973")
.setDeleteTime(Timestamp.newBuilder().build())
.setExpireTime(Timestamp.newBuilder().build())
.putAllAnnotations(new HashMap<String, String>())
.setEtag("etag3123477")
.setReconciling(true)
.build();
mockAdaptation.addResponse(expectedResponse);
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
PhraseSet phraseSet = PhraseSet.newBuilder().build();
String phraseSetId = "phraseSetId959902180";
PhraseSet actualResponse = client.createPhraseSet(parent, phraseSet, phraseSetId);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
CreatePhraseSetRequest actualRequest = ((CreatePhraseSetRequest) actualRequests.get(0));
Assert.assertEquals(parent.toString(), actualRequest.getParent());
Assert.assertEquals(phraseSet, actualRequest.getPhraseSet());
Assert.assertEquals(phraseSetId, actualRequest.getPhraseSetId());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void createPhraseSetExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
PhraseSet phraseSet = PhraseSet.newBuilder().build();
String phraseSetId = "phraseSetId959902180";
client.createPhraseSet(parent, phraseSet, phraseSetId);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void createPhraseSetTest2() throws Exception {
PhraseSet expectedResponse =
PhraseSet.newBuilder()
.setName(PhraseSetName.of("[PROJECT]", "[LOCATION]", "[PHRASE_SET]").toString())
.addAllPhrases(new ArrayList<PhraseSet.Phrase>())
.setBoost(93922211)
.setKmsKeyName("kmsKeyName412586233")
.setKmsKeyVersionName("kmsKeyVersionName-1798811307")
.setUid("uid115792")
.setDisplayName("displayName1714148973")
.setDeleteTime(Timestamp.newBuilder().build())
.setExpireTime(Timestamp.newBuilder().build())
.putAllAnnotations(new HashMap<String, String>())
.setEtag("etag3123477")
.setReconciling(true)
.build();
mockAdaptation.addResponse(expectedResponse);
String parent = "parent-995424086";
PhraseSet phraseSet = PhraseSet.newBuilder().build();
String phraseSetId = "phraseSetId959902180";
PhraseSet actualResponse = client.createPhraseSet(parent, phraseSet, phraseSetId);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
CreatePhraseSetRequest actualRequest = ((CreatePhraseSetRequest) actualRequests.get(0));
Assert.assertEquals(parent, actualRequest.getParent());
Assert.assertEquals(phraseSet, actualRequest.getPhraseSet());
Assert.assertEquals(phraseSetId, actualRequest.getPhraseSetId());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void createPhraseSetExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
String parent = "parent-995424086";
PhraseSet phraseSet = PhraseSet.newBuilder().build();
String phraseSetId = "phraseSetId959902180";
client.createPhraseSet(parent, phraseSet, phraseSetId);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getPhraseSetTest() throws Exception {
PhraseSet expectedResponse =
PhraseSet.newBuilder()
.setName(PhraseSetName.of("[PROJECT]", "[LOCATION]", "[PHRASE_SET]").toString())
.addAllPhrases(new ArrayList<PhraseSet.Phrase>())
.setBoost(93922211)
.setKmsKeyName("kmsKeyName412586233")
.setKmsKeyVersionName("kmsKeyVersionName-1798811307")
.setUid("uid115792")
.setDisplayName("displayName1714148973")
.setDeleteTime(Timestamp.newBuilder().build())
.setExpireTime(Timestamp.newBuilder().build())
.putAllAnnotations(new HashMap<String, String>())
.setEtag("etag3123477")
.setReconciling(true)
.build();
mockAdaptation.addResponse(expectedResponse);
PhraseSetName name = PhraseSetName.of("[PROJECT]", "[LOCATION]", "[PHRASE_SET]");
PhraseSet actualResponse = client.getPhraseSet(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetPhraseSetRequest actualRequest = ((GetPhraseSetRequest) actualRequests.get(0));
Assert.assertEquals(name.toString(), actualRequest.getName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void getPhraseSetExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
PhraseSetName name = PhraseSetName.of("[PROJECT]", "[LOCATION]", "[PHRASE_SET]");
client.getPhraseSet(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getPhraseSetTest2() throws Exception {
PhraseSet expectedResponse =
PhraseSet.newBuilder()
.setName(PhraseSetName.of("[PROJECT]", "[LOCATION]", "[PHRASE_SET]").toString())
.addAllPhrases(new ArrayList<PhraseSet.Phrase>())
.setBoost(93922211)
.setKmsKeyName("kmsKeyName412586233")
.setKmsKeyVersionName("kmsKeyVersionName-1798811307")
.setUid("uid115792")
.setDisplayName("displayName1714148973")
.setDeleteTime(Timestamp.newBuilder().build())
.setExpireTime(Timestamp.newBuilder().build())
.putAllAnnotations(new HashMap<String, String>())
.setEtag("etag3123477")
.setReconciling(true)
.build();
mockAdaptation.addResponse(expectedResponse);
String name = "name3373707";
PhraseSet actualResponse = client.getPhraseSet(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetPhraseSetRequest actualRequest = ((GetPhraseSetRequest) actualRequests.get(0));
Assert.assertEquals(name, actualRequest.getName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void getPhraseSetExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
String name = "name3373707";
client.getPhraseSet(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listPhraseSetTest() throws Exception {
PhraseSet responsesElement = PhraseSet.newBuilder().build();
ListPhraseSetResponse expectedResponse =
ListPhraseSetResponse.newBuilder()
.setNextPageToken("")
.addAllPhraseSets(Arrays.asList(responsesElement))
.build();
mockAdaptation.addResponse(expectedResponse);
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
ListPhraseSetPagedResponse pagedListResponse = client.listPhraseSet(parent);
List<PhraseSet> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getPhraseSetsList().get(0), resources.get(0));
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
ListPhraseSetRequest actualRequest = ((ListPhraseSetRequest) actualRequests.get(0));
Assert.assertEquals(parent.toString(), actualRequest.getParent());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void listPhraseSetExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
client.listPhraseSet(parent);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listPhraseSetTest2() throws Exception {
PhraseSet responsesElement = PhraseSet.newBuilder().build();
ListPhraseSetResponse expectedResponse =
ListPhraseSetResponse.newBuilder()
.setNextPageToken("")
.addAllPhraseSets(Arrays.asList(responsesElement))
.build();
mockAdaptation.addResponse(expectedResponse);
String parent = "parent-995424086";
ListPhraseSetPagedResponse pagedListResponse = client.listPhraseSet(parent);
List<PhraseSet> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getPhraseSetsList().get(0), resources.get(0));
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
ListPhraseSetRequest actualRequest = ((ListPhraseSetRequest) actualRequests.get(0));
Assert.assertEquals(parent, actualRequest.getParent());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void listPhraseSetExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
String parent = "parent-995424086";
client.listPhraseSet(parent);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void updatePhraseSetTest() throws Exception {
PhraseSet expectedResponse =
PhraseSet.newBuilder()
.setName(PhraseSetName.of("[PROJECT]", "[LOCATION]", "[PHRASE_SET]").toString())
.addAllPhrases(new ArrayList<PhraseSet.Phrase>())
.setBoost(93922211)
.setKmsKeyName("kmsKeyName412586233")
.setKmsKeyVersionName("kmsKeyVersionName-1798811307")
.setUid("uid115792")
.setDisplayName("displayName1714148973")
.setDeleteTime(Timestamp.newBuilder().build())
.setExpireTime(Timestamp.newBuilder().build())
.putAllAnnotations(new HashMap<String, String>())
.setEtag("etag3123477")
.setReconciling(true)
.build();
mockAdaptation.addResponse(expectedResponse);
PhraseSet phraseSet = PhraseSet.newBuilder().build();
FieldMask updateMask = FieldMask.newBuilder().build();
PhraseSet actualResponse = client.updatePhraseSet(phraseSet, updateMask);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
UpdatePhraseSetRequest actualRequest = ((UpdatePhraseSetRequest) actualRequests.get(0));
Assert.assertEquals(phraseSet, actualRequest.getPhraseSet());
Assert.assertEquals(updateMask, actualRequest.getUpdateMask());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void updatePhraseSetExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
PhraseSet phraseSet = PhraseSet.newBuilder().build();
FieldMask updateMask = FieldMask.newBuilder().build();
client.updatePhraseSet(phraseSet, updateMask);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void deletePhraseSetTest() throws Exception {
Empty expectedResponse = Empty.newBuilder().build();
mockAdaptation.addResponse(expectedResponse);
PhraseSetName name = PhraseSetName.of("[PROJECT]", "[LOCATION]", "[PHRASE_SET]");
client.deletePhraseSet(name);
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
DeletePhraseSetRequest actualRequest = ((DeletePhraseSetRequest) actualRequests.get(0));
Assert.assertEquals(name.toString(), actualRequest.getName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void deletePhraseSetExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
PhraseSetName name = PhraseSetName.of("[PROJECT]", "[LOCATION]", "[PHRASE_SET]");
client.deletePhraseSet(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void deletePhraseSetTest2() throws Exception {
Empty expectedResponse = Empty.newBuilder().build();
mockAdaptation.addResponse(expectedResponse);
String name = "name3373707";
client.deletePhraseSet(name);
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
DeletePhraseSetRequest actualRequest = ((DeletePhraseSetRequest) actualRequests.get(0));
Assert.assertEquals(name, actualRequest.getName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void deletePhraseSetExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
String name = "name3373707";
client.deletePhraseSet(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void createCustomClassTest() throws Exception {
CustomClass expectedResponse =
CustomClass.newBuilder()
.setName(CustomClassName.of("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]").toString())
.setCustomClassId("customClassId1871032322")
.addAllItems(new ArrayList<CustomClass.ClassItem>())
.setKmsKeyName("kmsKeyName412586233")
.setKmsKeyVersionName("kmsKeyVersionName-1798811307")
.setUid("uid115792")
.setDisplayName("displayName1714148973")
.setDeleteTime(Timestamp.newBuilder().build())
.setExpireTime(Timestamp.newBuilder().build())
.putAllAnnotations(new HashMap<String, String>())
.setEtag("etag3123477")
.setReconciling(true)
.build();
mockAdaptation.addResponse(expectedResponse);
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
CustomClass customClass = CustomClass.newBuilder().build();
String customClassId = "customClassId1871032322";
CustomClass actualResponse = client.createCustomClass(parent, customClass, customClassId);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
CreateCustomClassRequest actualRequest = ((CreateCustomClassRequest) actualRequests.get(0));
Assert.assertEquals(parent.toString(), actualRequest.getParent());
Assert.assertEquals(customClass, actualRequest.getCustomClass());
Assert.assertEquals(customClassId, actualRequest.getCustomClassId());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void createCustomClassExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
CustomClass customClass = CustomClass.newBuilder().build();
String customClassId = "customClassId1871032322";
client.createCustomClass(parent, customClass, customClassId);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void createCustomClassTest2() throws Exception {
CustomClass expectedResponse =
CustomClass.newBuilder()
.setName(CustomClassName.of("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]").toString())
.setCustomClassId("customClassId1871032322")
.addAllItems(new ArrayList<CustomClass.ClassItem>())
.setKmsKeyName("kmsKeyName412586233")
.setKmsKeyVersionName("kmsKeyVersionName-1798811307")
.setUid("uid115792")
.setDisplayName("displayName1714148973")
.setDeleteTime(Timestamp.newBuilder().build())
.setExpireTime(Timestamp.newBuilder().build())
.putAllAnnotations(new HashMap<String, String>())
.setEtag("etag3123477")
.setReconciling(true)
.build();
mockAdaptation.addResponse(expectedResponse);
String parent = "parent-995424086";
CustomClass customClass = CustomClass.newBuilder().build();
String customClassId = "customClassId1871032322";
CustomClass actualResponse = client.createCustomClass(parent, customClass, customClassId);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
CreateCustomClassRequest actualRequest = ((CreateCustomClassRequest) actualRequests.get(0));
Assert.assertEquals(parent, actualRequest.getParent());
Assert.assertEquals(customClass, actualRequest.getCustomClass());
Assert.assertEquals(customClassId, actualRequest.getCustomClassId());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void createCustomClassExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
String parent = "parent-995424086";
CustomClass customClass = CustomClass.newBuilder().build();
String customClassId = "customClassId1871032322";
client.createCustomClass(parent, customClass, customClassId);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getCustomClassTest() throws Exception {
CustomClass expectedResponse =
CustomClass.newBuilder()
.setName(CustomClassName.of("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]").toString())
.setCustomClassId("customClassId1871032322")
.addAllItems(new ArrayList<CustomClass.ClassItem>())
.setKmsKeyName("kmsKeyName412586233")
.setKmsKeyVersionName("kmsKeyVersionName-1798811307")
.setUid("uid115792")
.setDisplayName("displayName1714148973")
.setDeleteTime(Timestamp.newBuilder().build())
.setExpireTime(Timestamp.newBuilder().build())
.putAllAnnotations(new HashMap<String, String>())
.setEtag("etag3123477")
.setReconciling(true)
.build();
mockAdaptation.addResponse(expectedResponse);
CustomClassName name = CustomClassName.of("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]");
CustomClass actualResponse = client.getCustomClass(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetCustomClassRequest actualRequest = ((GetCustomClassRequest) actualRequests.get(0));
Assert.assertEquals(name.toString(), actualRequest.getName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void getCustomClassExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
CustomClassName name = CustomClassName.of("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]");
client.getCustomClass(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getCustomClassTest2() throws Exception {
CustomClass expectedResponse =
CustomClass.newBuilder()
.setName(CustomClassName.of("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]").toString())
.setCustomClassId("customClassId1871032322")
.addAllItems(new ArrayList<CustomClass.ClassItem>())
.setKmsKeyName("kmsKeyName412586233")
.setKmsKeyVersionName("kmsKeyVersionName-1798811307")
.setUid("uid115792")
.setDisplayName("displayName1714148973")
.setDeleteTime(Timestamp.newBuilder().build())
.setExpireTime(Timestamp.newBuilder().build())
.putAllAnnotations(new HashMap<String, String>())
.setEtag("etag3123477")
.setReconciling(true)
.build();
mockAdaptation.addResponse(expectedResponse);
String name = "name3373707";
CustomClass actualResponse = client.getCustomClass(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetCustomClassRequest actualRequest = ((GetCustomClassRequest) actualRequests.get(0));
Assert.assertEquals(name, actualRequest.getName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void getCustomClassExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
String name = "name3373707";
client.getCustomClass(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listCustomClassesTest() throws Exception {
CustomClass responsesElement = CustomClass.newBuilder().build();
ListCustomClassesResponse expectedResponse =
ListCustomClassesResponse.newBuilder()
.setNextPageToken("")
.addAllCustomClasses(Arrays.asList(responsesElement))
.build();
mockAdaptation.addResponse(expectedResponse);
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
ListCustomClassesPagedResponse pagedListResponse = client.listCustomClasses(parent);
List<CustomClass> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getCustomClassesList().get(0), resources.get(0));
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
ListCustomClassesRequest actualRequest = ((ListCustomClassesRequest) actualRequests.get(0));
Assert.assertEquals(parent.toString(), actualRequest.getParent());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void listCustomClassesExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
client.listCustomClasses(parent);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listCustomClassesTest2() throws Exception {
CustomClass responsesElement = CustomClass.newBuilder().build();
ListCustomClassesResponse expectedResponse =
ListCustomClassesResponse.newBuilder()
.setNextPageToken("")
.addAllCustomClasses(Arrays.asList(responsesElement))
.build();
mockAdaptation.addResponse(expectedResponse);
String parent = "parent-995424086";
ListCustomClassesPagedResponse pagedListResponse = client.listCustomClasses(parent);
List<CustomClass> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getCustomClassesList().get(0), resources.get(0));
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
ListCustomClassesRequest actualRequest = ((ListCustomClassesRequest) actualRequests.get(0));
Assert.assertEquals(parent, actualRequest.getParent());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void listCustomClassesExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
String parent = "parent-995424086";
client.listCustomClasses(parent);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void updateCustomClassTest() throws Exception {
CustomClass expectedResponse =
CustomClass.newBuilder()
.setName(CustomClassName.of("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]").toString())
.setCustomClassId("customClassId1871032322")
.addAllItems(new ArrayList<CustomClass.ClassItem>())
.setKmsKeyName("kmsKeyName412586233")
.setKmsKeyVersionName("kmsKeyVersionName-1798811307")
.setUid("uid115792")
.setDisplayName("displayName1714148973")
.setDeleteTime(Timestamp.newBuilder().build())
.setExpireTime(Timestamp.newBuilder().build())
.putAllAnnotations(new HashMap<String, String>())
.setEtag("etag3123477")
.setReconciling(true)
.build();
mockAdaptation.addResponse(expectedResponse);
CustomClass customClass = CustomClass.newBuilder().build();
FieldMask updateMask = FieldMask.newBuilder().build();
CustomClass actualResponse = client.updateCustomClass(customClass, updateMask);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
UpdateCustomClassRequest actualRequest = ((UpdateCustomClassRequest) actualRequests.get(0));
Assert.assertEquals(customClass, actualRequest.getCustomClass());
Assert.assertEquals(updateMask, actualRequest.getUpdateMask());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void updateCustomClassExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
CustomClass customClass = CustomClass.newBuilder().build();
FieldMask updateMask = FieldMask.newBuilder().build();
client.updateCustomClass(customClass, updateMask);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void deleteCustomClassTest() throws Exception {
Empty expectedResponse = Empty.newBuilder().build();
mockAdaptation.addResponse(expectedResponse);
CustomClassName name = CustomClassName.of("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]");
client.deleteCustomClass(name);
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
DeleteCustomClassRequest actualRequest = ((DeleteCustomClassRequest) actualRequests.get(0));
Assert.assertEquals(name.toString(), actualRequest.getName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void deleteCustomClassExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
CustomClassName name = CustomClassName.of("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]");
client.deleteCustomClass(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void deleteCustomClassTest2() throws Exception {
Empty expectedResponse = Empty.newBuilder().build();
mockAdaptation.addResponse(expectedResponse);
String name = "name3373707";
client.deleteCustomClass(name);
List<AbstractMessage> actualRequests = mockAdaptation.getRequests();
Assert.assertEquals(1, actualRequests.size());
DeleteCustomClassRequest actualRequest = ((DeleteCustomClassRequest) actualRequests.get(0));
Assert.assertEquals(name, actualRequest.getName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void deleteCustomClassExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockAdaptation.addException(exception);
try {
String name = "name3373707";
client.deleteCustomClass(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
}
|
googleads/google-ads-java | 36,686 | google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/common/ChainSet.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v19/common/asset_set_types.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v19.common;
/**
* <pre>
* Data used to configure a location set populated with the specified chains.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.common.ChainSet}
*/
public final class ChainSet extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v19.common.ChainSet)
ChainSetOrBuilder {
private static final long serialVersionUID = 0L;
// Use ChainSet.newBuilder() to construct.
private ChainSet(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ChainSet() {
relationshipType_ = 0;
chains_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new ChainSet();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.common.AssetSetTypesProto.internal_static_google_ads_googleads_v19_common_ChainSet_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.common.AssetSetTypesProto.internal_static_google_ads_googleads_v19_common_ChainSet_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.common.ChainSet.class, com.google.ads.googleads.v19.common.ChainSet.Builder.class);
}
public static final int RELATIONSHIP_TYPE_FIELD_NUMBER = 1;
private int relationshipType_ = 0;
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @return The enum numeric value on the wire for relationshipType.
*/
@java.lang.Override public int getRelationshipTypeValue() {
return relationshipType_;
}
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @return The relationshipType.
*/
@java.lang.Override public com.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType getRelationshipType() {
com.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType result = com.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType.forNumber(relationshipType_);
return result == null ? com.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType.UNRECOGNIZED : result;
}
public static final int CHAINS_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private java.util.List<com.google.ads.googleads.v19.common.ChainFilter> chains_;
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public java.util.List<com.google.ads.googleads.v19.common.ChainFilter> getChainsList() {
return chains_;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.ads.googleads.v19.common.ChainFilterOrBuilder>
getChainsOrBuilderList() {
return chains_;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public int getChainsCount() {
return chains_.size();
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v19.common.ChainFilter getChains(int index) {
return chains_.get(index);
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v19.common.ChainFilterOrBuilder getChainsOrBuilder(
int index) {
return chains_.get(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (relationshipType_ != com.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType.UNSPECIFIED.getNumber()) {
output.writeEnum(1, relationshipType_);
}
for (int i = 0; i < chains_.size(); i++) {
output.writeMessage(2, chains_.get(i));
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (relationshipType_ != com.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType.UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(1, relationshipType_);
}
for (int i = 0; i < chains_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, chains_.get(i));
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v19.common.ChainSet)) {
return super.equals(obj);
}
com.google.ads.googleads.v19.common.ChainSet other = (com.google.ads.googleads.v19.common.ChainSet) obj;
if (relationshipType_ != other.relationshipType_) return false;
if (!getChainsList()
.equals(other.getChainsList())) 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) + RELATIONSHIP_TYPE_FIELD_NUMBER;
hash = (53 * hash) + relationshipType_;
if (getChainsCount() > 0) {
hash = (37 * hash) + CHAINS_FIELD_NUMBER;
hash = (53 * hash) + getChainsList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v19.common.ChainSet parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.common.ChainSet 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.common.ChainSet parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.common.ChainSet 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.common.ChainSet parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.common.ChainSet 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.common.ChainSet parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.common.ChainSet 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.common.ChainSet parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.common.ChainSet 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.common.ChainSet 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.common.ChainSet 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.common.ChainSet prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Data used to configure a location set populated with the specified chains.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.common.ChainSet}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.common.ChainSet)
com.google.ads.googleads.v19.common.ChainSetOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.common.AssetSetTypesProto.internal_static_google_ads_googleads_v19_common_ChainSet_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.common.AssetSetTypesProto.internal_static_google_ads_googleads_v19_common_ChainSet_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.common.ChainSet.class, com.google.ads.googleads.v19.common.ChainSet.Builder.class);
}
// Construct using com.google.ads.googleads.v19.common.ChainSet.newBuilder()
private Builder() {
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
relationshipType_ = 0;
if (chainsBuilder_ == null) {
chains_ = java.util.Collections.emptyList();
} else {
chains_ = null;
chainsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v19.common.AssetSetTypesProto.internal_static_google_ads_googleads_v19_common_ChainSet_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v19.common.ChainSet getDefaultInstanceForType() {
return com.google.ads.googleads.v19.common.ChainSet.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v19.common.ChainSet build() {
com.google.ads.googleads.v19.common.ChainSet result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v19.common.ChainSet buildPartial() {
com.google.ads.googleads.v19.common.ChainSet result = new com.google.ads.googleads.v19.common.ChainSet(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartialRepeatedFields(com.google.ads.googleads.v19.common.ChainSet result) {
if (chainsBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)) {
chains_ = java.util.Collections.unmodifiableList(chains_);
bitField0_ = (bitField0_ & ~0x00000002);
}
result.chains_ = chains_;
} else {
result.chains_ = chainsBuilder_.build();
}
}
private void buildPartial0(com.google.ads.googleads.v19.common.ChainSet result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.relationshipType_ = relationshipType_;
}
}
@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.common.ChainSet) {
return mergeFrom((com.google.ads.googleads.v19.common.ChainSet)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v19.common.ChainSet other) {
if (other == com.google.ads.googleads.v19.common.ChainSet.getDefaultInstance()) return this;
if (other.relationshipType_ != 0) {
setRelationshipTypeValue(other.getRelationshipTypeValue());
}
if (chainsBuilder_ == null) {
if (!other.chains_.isEmpty()) {
if (chains_.isEmpty()) {
chains_ = other.chains_;
bitField0_ = (bitField0_ & ~0x00000002);
} else {
ensureChainsIsMutable();
chains_.addAll(other.chains_);
}
onChanged();
}
} else {
if (!other.chains_.isEmpty()) {
if (chainsBuilder_.isEmpty()) {
chainsBuilder_.dispose();
chainsBuilder_ = null;
chains_ = other.chains_;
bitField0_ = (bitField0_ & ~0x00000002);
chainsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getChainsFieldBuilder() : null;
} else {
chainsBuilder_.addAllMessages(other.chains_);
}
}
}
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: {
relationshipType_ = input.readEnum();
bitField0_ |= 0x00000001;
break;
} // case 8
case 18: {
com.google.ads.googleads.v19.common.ChainFilter m =
input.readMessage(
com.google.ads.googleads.v19.common.ChainFilter.parser(),
extensionRegistry);
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
chains_.add(m);
} else {
chainsBuilder_.addMessage(m);
}
break;
} // case 18
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private int relationshipType_ = 0;
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @return The enum numeric value on the wire for relationshipType.
*/
@java.lang.Override public int getRelationshipTypeValue() {
return relationshipType_;
}
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @param value The enum numeric value on the wire for relationshipType to set.
* @return This builder for chaining.
*/
public Builder setRelationshipTypeValue(int value) {
relationshipType_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @return The relationshipType.
*/
@java.lang.Override
public com.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType getRelationshipType() {
com.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType result = com.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType.forNumber(relationshipType_);
return result == null ? com.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType.UNRECOGNIZED : result;
}
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @param value The relationshipType to set.
* @return This builder for chaining.
*/
public Builder setRelationshipType(com.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
relationshipType_ = value.getNumber();
onChanged();
return this;
}
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v19.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @return This builder for chaining.
*/
public Builder clearRelationshipType() {
bitField0_ = (bitField0_ & ~0x00000001);
relationshipType_ = 0;
onChanged();
return this;
}
private java.util.List<com.google.ads.googleads.v19.common.ChainFilter> chains_ =
java.util.Collections.emptyList();
private void ensureChainsIsMutable() {
if (!((bitField0_ & 0x00000002) != 0)) {
chains_ = new java.util.ArrayList<com.google.ads.googleads.v19.common.ChainFilter>(chains_);
bitField0_ |= 0x00000002;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v19.common.ChainFilter, com.google.ads.googleads.v19.common.ChainFilter.Builder, com.google.ads.googleads.v19.common.ChainFilterOrBuilder> chainsBuilder_;
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public java.util.List<com.google.ads.googleads.v19.common.ChainFilter> getChainsList() {
if (chainsBuilder_ == null) {
return java.util.Collections.unmodifiableList(chains_);
} else {
return chainsBuilder_.getMessageList();
}
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public int getChainsCount() {
if (chainsBuilder_ == null) {
return chains_.size();
} else {
return chainsBuilder_.getCount();
}
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v19.common.ChainFilter getChains(int index) {
if (chainsBuilder_ == null) {
return chains_.get(index);
} else {
return chainsBuilder_.getMessage(index);
}
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setChains(
int index, com.google.ads.googleads.v19.common.ChainFilter value) {
if (chainsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureChainsIsMutable();
chains_.set(index, value);
onChanged();
} else {
chainsBuilder_.setMessage(index, value);
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setChains(
int index, com.google.ads.googleads.v19.common.ChainFilter.Builder builderForValue) {
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
chains_.set(index, builderForValue.build());
onChanged();
} else {
chainsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addChains(com.google.ads.googleads.v19.common.ChainFilter value) {
if (chainsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureChainsIsMutable();
chains_.add(value);
onChanged();
} else {
chainsBuilder_.addMessage(value);
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addChains(
int index, com.google.ads.googleads.v19.common.ChainFilter value) {
if (chainsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureChainsIsMutable();
chains_.add(index, value);
onChanged();
} else {
chainsBuilder_.addMessage(index, value);
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addChains(
com.google.ads.googleads.v19.common.ChainFilter.Builder builderForValue) {
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
chains_.add(builderForValue.build());
onChanged();
} else {
chainsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addChains(
int index, com.google.ads.googleads.v19.common.ChainFilter.Builder builderForValue) {
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
chains_.add(index, builderForValue.build());
onChanged();
} else {
chainsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addAllChains(
java.lang.Iterable<? extends com.google.ads.googleads.v19.common.ChainFilter> values) {
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, chains_);
onChanged();
} else {
chainsBuilder_.addAllMessages(values);
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder clearChains() {
if (chainsBuilder_ == null) {
chains_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
} else {
chainsBuilder_.clear();
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder removeChains(int index) {
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
chains_.remove(index);
onChanged();
} else {
chainsBuilder_.remove(index);
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v19.common.ChainFilter.Builder getChainsBuilder(
int index) {
return getChainsFieldBuilder().getBuilder(index);
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v19.common.ChainFilterOrBuilder getChainsOrBuilder(
int index) {
if (chainsBuilder_ == null) {
return chains_.get(index); } else {
return chainsBuilder_.getMessageOrBuilder(index);
}
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public java.util.List<? extends com.google.ads.googleads.v19.common.ChainFilterOrBuilder>
getChainsOrBuilderList() {
if (chainsBuilder_ != null) {
return chainsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(chains_);
}
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v19.common.ChainFilter.Builder addChainsBuilder() {
return getChainsFieldBuilder().addBuilder(
com.google.ads.googleads.v19.common.ChainFilter.getDefaultInstance());
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v19.common.ChainFilter.Builder addChainsBuilder(
int index) {
return getChainsFieldBuilder().addBuilder(
index, com.google.ads.googleads.v19.common.ChainFilter.getDefaultInstance());
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v19.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public java.util.List<com.google.ads.googleads.v19.common.ChainFilter.Builder>
getChainsBuilderList() {
return getChainsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v19.common.ChainFilter, com.google.ads.googleads.v19.common.ChainFilter.Builder, com.google.ads.googleads.v19.common.ChainFilterOrBuilder>
getChainsFieldBuilder() {
if (chainsBuilder_ == null) {
chainsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v19.common.ChainFilter, com.google.ads.googleads.v19.common.ChainFilter.Builder, com.google.ads.googleads.v19.common.ChainFilterOrBuilder>(
chains_,
((bitField0_ & 0x00000002) != 0),
getParentForChildren(),
isClean());
chains_ = null;
}
return chainsBuilder_;
}
@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.common.ChainSet)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v19.common.ChainSet)
private static final com.google.ads.googleads.v19.common.ChainSet DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v19.common.ChainSet();
}
public static com.google.ads.googleads.v19.common.ChainSet getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ChainSet>
PARSER = new com.google.protobuf.AbstractParser<ChainSet>() {
@java.lang.Override
public ChainSet 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<ChainSet> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ChainSet> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v19.common.ChainSet getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 36,686 | google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/common/ChainSet.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v20/common/asset_set_types.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v20.common;
/**
* <pre>
* Data used to configure a location set populated with the specified chains.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.common.ChainSet}
*/
public final class ChainSet extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v20.common.ChainSet)
ChainSetOrBuilder {
private static final long serialVersionUID = 0L;
// Use ChainSet.newBuilder() to construct.
private ChainSet(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ChainSet() {
relationshipType_ = 0;
chains_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new ChainSet();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.common.AssetSetTypesProto.internal_static_google_ads_googleads_v20_common_ChainSet_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.common.AssetSetTypesProto.internal_static_google_ads_googleads_v20_common_ChainSet_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.common.ChainSet.class, com.google.ads.googleads.v20.common.ChainSet.Builder.class);
}
public static final int RELATIONSHIP_TYPE_FIELD_NUMBER = 1;
private int relationshipType_ = 0;
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @return The enum numeric value on the wire for relationshipType.
*/
@java.lang.Override public int getRelationshipTypeValue() {
return relationshipType_;
}
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @return The relationshipType.
*/
@java.lang.Override public com.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType getRelationshipType() {
com.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType result = com.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType.forNumber(relationshipType_);
return result == null ? com.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType.UNRECOGNIZED : result;
}
public static final int CHAINS_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private java.util.List<com.google.ads.googleads.v20.common.ChainFilter> chains_;
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public java.util.List<com.google.ads.googleads.v20.common.ChainFilter> getChainsList() {
return chains_;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.ads.googleads.v20.common.ChainFilterOrBuilder>
getChainsOrBuilderList() {
return chains_;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public int getChainsCount() {
return chains_.size();
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v20.common.ChainFilter getChains(int index) {
return chains_.get(index);
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v20.common.ChainFilterOrBuilder getChainsOrBuilder(
int index) {
return chains_.get(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (relationshipType_ != com.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType.UNSPECIFIED.getNumber()) {
output.writeEnum(1, relationshipType_);
}
for (int i = 0; i < chains_.size(); i++) {
output.writeMessage(2, chains_.get(i));
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (relationshipType_ != com.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType.UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(1, relationshipType_);
}
for (int i = 0; i < chains_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, chains_.get(i));
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v20.common.ChainSet)) {
return super.equals(obj);
}
com.google.ads.googleads.v20.common.ChainSet other = (com.google.ads.googleads.v20.common.ChainSet) obj;
if (relationshipType_ != other.relationshipType_) return false;
if (!getChainsList()
.equals(other.getChainsList())) 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) + RELATIONSHIP_TYPE_FIELD_NUMBER;
hash = (53 * hash) + relationshipType_;
if (getChainsCount() > 0) {
hash = (37 * hash) + CHAINS_FIELD_NUMBER;
hash = (53 * hash) + getChainsList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v20.common.ChainSet parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.common.ChainSet 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.common.ChainSet parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.common.ChainSet 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.common.ChainSet parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.common.ChainSet 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.common.ChainSet parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.common.ChainSet 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.common.ChainSet parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.common.ChainSet 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.common.ChainSet 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.common.ChainSet 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.common.ChainSet prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Data used to configure a location set populated with the specified chains.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.common.ChainSet}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.common.ChainSet)
com.google.ads.googleads.v20.common.ChainSetOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.common.AssetSetTypesProto.internal_static_google_ads_googleads_v20_common_ChainSet_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.common.AssetSetTypesProto.internal_static_google_ads_googleads_v20_common_ChainSet_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.common.ChainSet.class, com.google.ads.googleads.v20.common.ChainSet.Builder.class);
}
// Construct using com.google.ads.googleads.v20.common.ChainSet.newBuilder()
private Builder() {
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
relationshipType_ = 0;
if (chainsBuilder_ == null) {
chains_ = java.util.Collections.emptyList();
} else {
chains_ = null;
chainsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v20.common.AssetSetTypesProto.internal_static_google_ads_googleads_v20_common_ChainSet_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v20.common.ChainSet getDefaultInstanceForType() {
return com.google.ads.googleads.v20.common.ChainSet.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v20.common.ChainSet build() {
com.google.ads.googleads.v20.common.ChainSet result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v20.common.ChainSet buildPartial() {
com.google.ads.googleads.v20.common.ChainSet result = new com.google.ads.googleads.v20.common.ChainSet(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartialRepeatedFields(com.google.ads.googleads.v20.common.ChainSet result) {
if (chainsBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)) {
chains_ = java.util.Collections.unmodifiableList(chains_);
bitField0_ = (bitField0_ & ~0x00000002);
}
result.chains_ = chains_;
} else {
result.chains_ = chainsBuilder_.build();
}
}
private void buildPartial0(com.google.ads.googleads.v20.common.ChainSet result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.relationshipType_ = relationshipType_;
}
}
@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.common.ChainSet) {
return mergeFrom((com.google.ads.googleads.v20.common.ChainSet)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v20.common.ChainSet other) {
if (other == com.google.ads.googleads.v20.common.ChainSet.getDefaultInstance()) return this;
if (other.relationshipType_ != 0) {
setRelationshipTypeValue(other.getRelationshipTypeValue());
}
if (chainsBuilder_ == null) {
if (!other.chains_.isEmpty()) {
if (chains_.isEmpty()) {
chains_ = other.chains_;
bitField0_ = (bitField0_ & ~0x00000002);
} else {
ensureChainsIsMutable();
chains_.addAll(other.chains_);
}
onChanged();
}
} else {
if (!other.chains_.isEmpty()) {
if (chainsBuilder_.isEmpty()) {
chainsBuilder_.dispose();
chainsBuilder_ = null;
chains_ = other.chains_;
bitField0_ = (bitField0_ & ~0x00000002);
chainsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getChainsFieldBuilder() : null;
} else {
chainsBuilder_.addAllMessages(other.chains_);
}
}
}
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: {
relationshipType_ = input.readEnum();
bitField0_ |= 0x00000001;
break;
} // case 8
case 18: {
com.google.ads.googleads.v20.common.ChainFilter m =
input.readMessage(
com.google.ads.googleads.v20.common.ChainFilter.parser(),
extensionRegistry);
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
chains_.add(m);
} else {
chainsBuilder_.addMessage(m);
}
break;
} // case 18
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private int relationshipType_ = 0;
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @return The enum numeric value on the wire for relationshipType.
*/
@java.lang.Override public int getRelationshipTypeValue() {
return relationshipType_;
}
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @param value The enum numeric value on the wire for relationshipType to set.
* @return This builder for chaining.
*/
public Builder setRelationshipTypeValue(int value) {
relationshipType_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @return The relationshipType.
*/
@java.lang.Override
public com.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType getRelationshipType() {
com.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType result = com.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType.forNumber(relationshipType_);
return result == null ? com.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType.UNRECOGNIZED : result;
}
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @param value The relationshipType to set.
* @return This builder for chaining.
*/
public Builder setRelationshipType(com.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
relationshipType_ = value.getNumber();
onChanged();
return this;
}
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v20.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @return This builder for chaining.
*/
public Builder clearRelationshipType() {
bitField0_ = (bitField0_ & ~0x00000001);
relationshipType_ = 0;
onChanged();
return this;
}
private java.util.List<com.google.ads.googleads.v20.common.ChainFilter> chains_ =
java.util.Collections.emptyList();
private void ensureChainsIsMutable() {
if (!((bitField0_ & 0x00000002) != 0)) {
chains_ = new java.util.ArrayList<com.google.ads.googleads.v20.common.ChainFilter>(chains_);
bitField0_ |= 0x00000002;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v20.common.ChainFilter, com.google.ads.googleads.v20.common.ChainFilter.Builder, com.google.ads.googleads.v20.common.ChainFilterOrBuilder> chainsBuilder_;
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public java.util.List<com.google.ads.googleads.v20.common.ChainFilter> getChainsList() {
if (chainsBuilder_ == null) {
return java.util.Collections.unmodifiableList(chains_);
} else {
return chainsBuilder_.getMessageList();
}
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public int getChainsCount() {
if (chainsBuilder_ == null) {
return chains_.size();
} else {
return chainsBuilder_.getCount();
}
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v20.common.ChainFilter getChains(int index) {
if (chainsBuilder_ == null) {
return chains_.get(index);
} else {
return chainsBuilder_.getMessage(index);
}
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setChains(
int index, com.google.ads.googleads.v20.common.ChainFilter value) {
if (chainsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureChainsIsMutable();
chains_.set(index, value);
onChanged();
} else {
chainsBuilder_.setMessage(index, value);
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setChains(
int index, com.google.ads.googleads.v20.common.ChainFilter.Builder builderForValue) {
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
chains_.set(index, builderForValue.build());
onChanged();
} else {
chainsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addChains(com.google.ads.googleads.v20.common.ChainFilter value) {
if (chainsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureChainsIsMutable();
chains_.add(value);
onChanged();
} else {
chainsBuilder_.addMessage(value);
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addChains(
int index, com.google.ads.googleads.v20.common.ChainFilter value) {
if (chainsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureChainsIsMutable();
chains_.add(index, value);
onChanged();
} else {
chainsBuilder_.addMessage(index, value);
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addChains(
com.google.ads.googleads.v20.common.ChainFilter.Builder builderForValue) {
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
chains_.add(builderForValue.build());
onChanged();
} else {
chainsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addChains(
int index, com.google.ads.googleads.v20.common.ChainFilter.Builder builderForValue) {
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
chains_.add(index, builderForValue.build());
onChanged();
} else {
chainsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addAllChains(
java.lang.Iterable<? extends com.google.ads.googleads.v20.common.ChainFilter> values) {
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, chains_);
onChanged();
} else {
chainsBuilder_.addAllMessages(values);
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder clearChains() {
if (chainsBuilder_ == null) {
chains_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
} else {
chainsBuilder_.clear();
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder removeChains(int index) {
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
chains_.remove(index);
onChanged();
} else {
chainsBuilder_.remove(index);
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v20.common.ChainFilter.Builder getChainsBuilder(
int index) {
return getChainsFieldBuilder().getBuilder(index);
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v20.common.ChainFilterOrBuilder getChainsOrBuilder(
int index) {
if (chainsBuilder_ == null) {
return chains_.get(index); } else {
return chainsBuilder_.getMessageOrBuilder(index);
}
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public java.util.List<? extends com.google.ads.googleads.v20.common.ChainFilterOrBuilder>
getChainsOrBuilderList() {
if (chainsBuilder_ != null) {
return chainsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(chains_);
}
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v20.common.ChainFilter.Builder addChainsBuilder() {
return getChainsFieldBuilder().addBuilder(
com.google.ads.googleads.v20.common.ChainFilter.getDefaultInstance());
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v20.common.ChainFilter.Builder addChainsBuilder(
int index) {
return getChainsFieldBuilder().addBuilder(
index, com.google.ads.googleads.v20.common.ChainFilter.getDefaultInstance());
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v20.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public java.util.List<com.google.ads.googleads.v20.common.ChainFilter.Builder>
getChainsBuilderList() {
return getChainsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v20.common.ChainFilter, com.google.ads.googleads.v20.common.ChainFilter.Builder, com.google.ads.googleads.v20.common.ChainFilterOrBuilder>
getChainsFieldBuilder() {
if (chainsBuilder_ == null) {
chainsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v20.common.ChainFilter, com.google.ads.googleads.v20.common.ChainFilter.Builder, com.google.ads.googleads.v20.common.ChainFilterOrBuilder>(
chains_,
((bitField0_ & 0x00000002) != 0),
getParentForChildren(),
isClean());
chains_ = null;
}
return chainsBuilder_;
}
@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.common.ChainSet)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v20.common.ChainSet)
private static final com.google.ads.googleads.v20.common.ChainSet DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v20.common.ChainSet();
}
public static com.google.ads.googleads.v20.common.ChainSet getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ChainSet>
PARSER = new com.google.protobuf.AbstractParser<ChainSet>() {
@java.lang.Override
public ChainSet 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<ChainSet> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ChainSet> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v20.common.ChainSet getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 36,686 | google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/common/ChainSet.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v21/common/asset_set_types.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v21.common;
/**
* <pre>
* Data used to configure a location set populated with the specified chains.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.common.ChainSet}
*/
public final class ChainSet extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v21.common.ChainSet)
ChainSetOrBuilder {
private static final long serialVersionUID = 0L;
// Use ChainSet.newBuilder() to construct.
private ChainSet(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ChainSet() {
relationshipType_ = 0;
chains_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new ChainSet();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.common.AssetSetTypesProto.internal_static_google_ads_googleads_v21_common_ChainSet_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.common.AssetSetTypesProto.internal_static_google_ads_googleads_v21_common_ChainSet_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.common.ChainSet.class, com.google.ads.googleads.v21.common.ChainSet.Builder.class);
}
public static final int RELATIONSHIP_TYPE_FIELD_NUMBER = 1;
private int relationshipType_ = 0;
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @return The enum numeric value on the wire for relationshipType.
*/
@java.lang.Override public int getRelationshipTypeValue() {
return relationshipType_;
}
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @return The relationshipType.
*/
@java.lang.Override public com.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType getRelationshipType() {
com.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType result = com.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType.forNumber(relationshipType_);
return result == null ? com.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType.UNRECOGNIZED : result;
}
public static final int CHAINS_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private java.util.List<com.google.ads.googleads.v21.common.ChainFilter> chains_;
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public java.util.List<com.google.ads.googleads.v21.common.ChainFilter> getChainsList() {
return chains_;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.ads.googleads.v21.common.ChainFilterOrBuilder>
getChainsOrBuilderList() {
return chains_;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public int getChainsCount() {
return chains_.size();
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v21.common.ChainFilter getChains(int index) {
return chains_.get(index);
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v21.common.ChainFilterOrBuilder getChainsOrBuilder(
int index) {
return chains_.get(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (relationshipType_ != com.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType.UNSPECIFIED.getNumber()) {
output.writeEnum(1, relationshipType_);
}
for (int i = 0; i < chains_.size(); i++) {
output.writeMessage(2, chains_.get(i));
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (relationshipType_ != com.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType.UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(1, relationshipType_);
}
for (int i = 0; i < chains_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, chains_.get(i));
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v21.common.ChainSet)) {
return super.equals(obj);
}
com.google.ads.googleads.v21.common.ChainSet other = (com.google.ads.googleads.v21.common.ChainSet) obj;
if (relationshipType_ != other.relationshipType_) return false;
if (!getChainsList()
.equals(other.getChainsList())) 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) + RELATIONSHIP_TYPE_FIELD_NUMBER;
hash = (53 * hash) + relationshipType_;
if (getChainsCount() > 0) {
hash = (37 * hash) + CHAINS_FIELD_NUMBER;
hash = (53 * hash) + getChainsList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v21.common.ChainSet parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.common.ChainSet 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.common.ChainSet parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.common.ChainSet 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.common.ChainSet parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.common.ChainSet 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.common.ChainSet parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.common.ChainSet 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.common.ChainSet parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.common.ChainSet 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.common.ChainSet 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.common.ChainSet 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.common.ChainSet prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Data used to configure a location set populated with the specified chains.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.common.ChainSet}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.common.ChainSet)
com.google.ads.googleads.v21.common.ChainSetOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.common.AssetSetTypesProto.internal_static_google_ads_googleads_v21_common_ChainSet_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.common.AssetSetTypesProto.internal_static_google_ads_googleads_v21_common_ChainSet_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.common.ChainSet.class, com.google.ads.googleads.v21.common.ChainSet.Builder.class);
}
// Construct using com.google.ads.googleads.v21.common.ChainSet.newBuilder()
private Builder() {
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
relationshipType_ = 0;
if (chainsBuilder_ == null) {
chains_ = java.util.Collections.emptyList();
} else {
chains_ = null;
chainsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v21.common.AssetSetTypesProto.internal_static_google_ads_googleads_v21_common_ChainSet_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v21.common.ChainSet getDefaultInstanceForType() {
return com.google.ads.googleads.v21.common.ChainSet.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v21.common.ChainSet build() {
com.google.ads.googleads.v21.common.ChainSet result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v21.common.ChainSet buildPartial() {
com.google.ads.googleads.v21.common.ChainSet result = new com.google.ads.googleads.v21.common.ChainSet(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartialRepeatedFields(com.google.ads.googleads.v21.common.ChainSet result) {
if (chainsBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)) {
chains_ = java.util.Collections.unmodifiableList(chains_);
bitField0_ = (bitField0_ & ~0x00000002);
}
result.chains_ = chains_;
} else {
result.chains_ = chainsBuilder_.build();
}
}
private void buildPartial0(com.google.ads.googleads.v21.common.ChainSet result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.relationshipType_ = relationshipType_;
}
}
@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.common.ChainSet) {
return mergeFrom((com.google.ads.googleads.v21.common.ChainSet)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v21.common.ChainSet other) {
if (other == com.google.ads.googleads.v21.common.ChainSet.getDefaultInstance()) return this;
if (other.relationshipType_ != 0) {
setRelationshipTypeValue(other.getRelationshipTypeValue());
}
if (chainsBuilder_ == null) {
if (!other.chains_.isEmpty()) {
if (chains_.isEmpty()) {
chains_ = other.chains_;
bitField0_ = (bitField0_ & ~0x00000002);
} else {
ensureChainsIsMutable();
chains_.addAll(other.chains_);
}
onChanged();
}
} else {
if (!other.chains_.isEmpty()) {
if (chainsBuilder_.isEmpty()) {
chainsBuilder_.dispose();
chainsBuilder_ = null;
chains_ = other.chains_;
bitField0_ = (bitField0_ & ~0x00000002);
chainsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getChainsFieldBuilder() : null;
} else {
chainsBuilder_.addAllMessages(other.chains_);
}
}
}
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: {
relationshipType_ = input.readEnum();
bitField0_ |= 0x00000001;
break;
} // case 8
case 18: {
com.google.ads.googleads.v21.common.ChainFilter m =
input.readMessage(
com.google.ads.googleads.v21.common.ChainFilter.parser(),
extensionRegistry);
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
chains_.add(m);
} else {
chainsBuilder_.addMessage(m);
}
break;
} // case 18
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private int relationshipType_ = 0;
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @return The enum numeric value on the wire for relationshipType.
*/
@java.lang.Override public int getRelationshipTypeValue() {
return relationshipType_;
}
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @param value The enum numeric value on the wire for relationshipType to set.
* @return This builder for chaining.
*/
public Builder setRelationshipTypeValue(int value) {
relationshipType_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @return The relationshipType.
*/
@java.lang.Override
public com.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType getRelationshipType() {
com.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType result = com.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType.forNumber(relationshipType_);
return result == null ? com.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType.UNRECOGNIZED : result;
}
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @param value The relationshipType to set.
* @return This builder for chaining.
*/
public Builder setRelationshipType(com.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
relationshipType_ = value.getNumber();
onChanged();
return this;
}
/**
* <pre>
* Required. Immutable. Relationship type the specified chains have with this
* advertiser.
* </pre>
*
* <code>.google.ads.googleads.v21.enums.ChainRelationshipTypeEnum.ChainRelationshipType relationship_type = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.field_behavior) = IMMUTABLE];</code>
* @return This builder for chaining.
*/
public Builder clearRelationshipType() {
bitField0_ = (bitField0_ & ~0x00000001);
relationshipType_ = 0;
onChanged();
return this;
}
private java.util.List<com.google.ads.googleads.v21.common.ChainFilter> chains_ =
java.util.Collections.emptyList();
private void ensureChainsIsMutable() {
if (!((bitField0_ & 0x00000002) != 0)) {
chains_ = new java.util.ArrayList<com.google.ads.googleads.v21.common.ChainFilter>(chains_);
bitField0_ |= 0x00000002;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v21.common.ChainFilter, com.google.ads.googleads.v21.common.ChainFilter.Builder, com.google.ads.googleads.v21.common.ChainFilterOrBuilder> chainsBuilder_;
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public java.util.List<com.google.ads.googleads.v21.common.ChainFilter> getChainsList() {
if (chainsBuilder_ == null) {
return java.util.Collections.unmodifiableList(chains_);
} else {
return chainsBuilder_.getMessageList();
}
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public int getChainsCount() {
if (chainsBuilder_ == null) {
return chains_.size();
} else {
return chainsBuilder_.getCount();
}
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v21.common.ChainFilter getChains(int index) {
if (chainsBuilder_ == null) {
return chains_.get(index);
} else {
return chainsBuilder_.getMessage(index);
}
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setChains(
int index, com.google.ads.googleads.v21.common.ChainFilter value) {
if (chainsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureChainsIsMutable();
chains_.set(index, value);
onChanged();
} else {
chainsBuilder_.setMessage(index, value);
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setChains(
int index, com.google.ads.googleads.v21.common.ChainFilter.Builder builderForValue) {
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
chains_.set(index, builderForValue.build());
onChanged();
} else {
chainsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addChains(com.google.ads.googleads.v21.common.ChainFilter value) {
if (chainsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureChainsIsMutable();
chains_.add(value);
onChanged();
} else {
chainsBuilder_.addMessage(value);
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addChains(
int index, com.google.ads.googleads.v21.common.ChainFilter value) {
if (chainsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureChainsIsMutable();
chains_.add(index, value);
onChanged();
} else {
chainsBuilder_.addMessage(index, value);
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addChains(
com.google.ads.googleads.v21.common.ChainFilter.Builder builderForValue) {
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
chains_.add(builderForValue.build());
onChanged();
} else {
chainsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addChains(
int index, com.google.ads.googleads.v21.common.ChainFilter.Builder builderForValue) {
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
chains_.add(index, builderForValue.build());
onChanged();
} else {
chainsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addAllChains(
java.lang.Iterable<? extends com.google.ads.googleads.v21.common.ChainFilter> values) {
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, chains_);
onChanged();
} else {
chainsBuilder_.addAllMessages(values);
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder clearChains() {
if (chainsBuilder_ == null) {
chains_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
} else {
chainsBuilder_.clear();
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder removeChains(int index) {
if (chainsBuilder_ == null) {
ensureChainsIsMutable();
chains_.remove(index);
onChanged();
} else {
chainsBuilder_.remove(index);
}
return this;
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v21.common.ChainFilter.Builder getChainsBuilder(
int index) {
return getChainsFieldBuilder().getBuilder(index);
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v21.common.ChainFilterOrBuilder getChainsOrBuilder(
int index) {
if (chainsBuilder_ == null) {
return chains_.get(index); } else {
return chainsBuilder_.getMessageOrBuilder(index);
}
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public java.util.List<? extends com.google.ads.googleads.v21.common.ChainFilterOrBuilder>
getChainsOrBuilderList() {
if (chainsBuilder_ != null) {
return chainsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(chains_);
}
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v21.common.ChainFilter.Builder addChainsBuilder() {
return getChainsFieldBuilder().addBuilder(
com.google.ads.googleads.v21.common.ChainFilter.getDefaultInstance());
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v21.common.ChainFilter.Builder addChainsBuilder(
int index) {
return getChainsFieldBuilder().addBuilder(
index, com.google.ads.googleads.v21.common.ChainFilter.getDefaultInstance());
}
/**
* <pre>
* Required. A list of chain level filters, all filters are OR'ed together.
* </pre>
*
* <code>repeated .google.ads.googleads.v21.common.ChainFilter chains = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public java.util.List<com.google.ads.googleads.v21.common.ChainFilter.Builder>
getChainsBuilderList() {
return getChainsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v21.common.ChainFilter, com.google.ads.googleads.v21.common.ChainFilter.Builder, com.google.ads.googleads.v21.common.ChainFilterOrBuilder>
getChainsFieldBuilder() {
if (chainsBuilder_ == null) {
chainsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v21.common.ChainFilter, com.google.ads.googleads.v21.common.ChainFilter.Builder, com.google.ads.googleads.v21.common.ChainFilterOrBuilder>(
chains_,
((bitField0_ & 0x00000002) != 0),
getParentForChildren(),
isClean());
chains_ = null;
}
return chainsBuilder_;
}
@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.common.ChainSet)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v21.common.ChainSet)
private static final com.google.ads.googleads.v21.common.ChainSet DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v21.common.ChainSet();
}
public static com.google.ads.googleads.v21.common.ChainSet getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ChainSet>
PARSER = new com.google.protobuf.AbstractParser<ChainSet>() {
@java.lang.Override
public ChainSet 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<ChainSet> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ChainSet> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v21.common.ChainSet getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/commons-jexl | 36,168 | src/test/java/org/apache/commons/jexl3/Issues200Test.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.jexl3;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.jexl3.internal.TemplateDebugger;
import org.apache.commons.jexl3.introspection.JexlSandbox;
import org.apache.commons.logging.Log;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test cases for reported issue between JEXL-200 and JEXL-299.
*/
@SuppressWarnings({"boxing", "UnnecessaryBoxing", "AssertEqualsBetweenInconvertibleTypes"})
class Issues200Test extends JexlTestCase {
public static class Arithmetic266 extends JexlArithmetic {
static final ThreadLocal<Deque<Iterator266>> TLS_FOREACH = new ThreadLocal<Deque<Iterator266>>() {
@Override
public Deque<Iterator266> initialValue() {
return new LinkedList<>();
}
};
static void closeIterator(final Iterator266 i266) {
final Deque<Iterator266> queue = TLS_FOREACH.get();
if (queue != null) {
queue.remove(i266);
}
}
public Arithmetic266(final boolean strict) {
super(strict);
}
public Iterator<?> forEach(final Iterable<?> collection) {
final Iterator266 it266 = new Iterator266((Iterator<Object>) collection.iterator());
final Deque<Iterator266> queue = TLS_FOREACH.get();
queue.addFirst(it266);
return it266;
}
public Iterator<?> forEach(final Map<?,?> collection) {
return forEach(collection.values());
}
public void remove() {
final Deque<Iterator266> queue = TLS_FOREACH.get();
final Iterator266 i266 = queue.getFirst();
if (i266 != null) {
i266.remove();
throw new JexlException.Continue(null);
}
throw new NoSuchElementException();
}
}
public static class Cls298 {
int sz = 42;
public boolean isEmpty() {
return sz <= 0;
}
public int size() {
return sz;
}
public int size(final int x) {
return sz + x;
}
}
public static class Context225 extends MapContext {
public String bar(){
return "bar";
}
}
public static class Context279 extends MapContext {
public Number identity(final Number x) {
return x;
}
public String identity(final String x) {
return x;
}
public String[] spread(final String str) {
if (str == null) {
return null;
}
final String[] a = new String[str.length()];
for(int i = 0; i < str.length(); ++i) {
a[i] = "" + str.charAt(i);
}
return a;
}
}
public static class Eval {
private JexlEngine jexl;
public JexlScript fn(final String src) {
return jexl.createScript(src);
}
void setJexl(final JexlEngine je) {
jexl = je;
}
}
public static class Foo245 {
private Object bar;
public Object getBar() {
return bar;
}
void setBar(final Object bar) {
this.bar = bar;
}
}
/**
* An iterator that implements Closeable (at least implements a close method).
*/
public static class Iterator266 implements /*Closeable,*/ Iterator<Object> {
private Iterator<Object> iterator;
Iterator266(final Iterator<Object> ator) {
iterator = ator;
}
//@Override
public void close() {
if (iterator != null) {
Arithmetic266.closeIterator(this);
iterator = null;
}
}
@Override
protected void finalize() throws Throwable {
close();
super.finalize();
}
@Override
public boolean hasNext() {
if (iterator == null) {
return false;
}
final boolean n = iterator.hasNext();
if (!n) {
close();
}
return n;
}
@Override
public Object next() {
if (iterator == null) {
throw new NoSuchElementException();
}
return iterator.next();
}
@Override
public void remove() {
if (iterator != null) {
iterator.remove();
}
}
}
public static class JexlArithmetic224 extends JexlArithmetic {
public JexlArithmetic224(final boolean astrict) {
super(astrict);
}
public Object arrayGet(final Collection<?> c, final Number n) {
return nth(c, n.intValue());
}
public Object call(final Collection<?> c, final Number n) {
if (c instanceof List) {
return ((List<?>) c).get(n.intValue());
}
return nth(c, n.intValue());
}
protected Object nth(final Collection<?> c, int i) {
if (c instanceof List) {
// tell engine to use default
return JexlEngine.TRY_FAILED;
}
for (final Object o : c) {
if (i-- == 0) {
return o;
}
}
return null;
}
public Object propertyGet(final Collection<?> c, final Number n) {
return nth(c, n.intValue());
}
}
public static class T210 {
public void npe() {
throw new NullPointerException("NPE210");
}
}
private static void handle(final ExecutorService pool, final JexlScript script, final Map<String, Object> payload) {
pool.submit(() -> script.execute(new MapContext(payload)));
}
public Issues200Test() {
super("Issues200Test", null);
}
@BeforeEach
@Override
public void setUp() {
// ensure jul logging is only error to avoid warning in silent mode
java.util.logging.Logger.getLogger(JexlEngine.class.getName()).setLevel(java.util.logging.Level.SEVERE);
}
@Test
void test200() {
final JexlContext jc = new MapContext();
final Map<String, Object> funcs = new HashMap<>();
final Eval eval = new Eval();
funcs.put(null, eval);
final JexlEngine jexl = new JexlBuilder().namespaces(funcs).create();
eval.setJexl(jexl);
final String src = "var f = fn(\'(x)->{x + 42}\'); f(y)";
final JexlScript s200 = jexl.createScript(src, "y");
assertEquals(142, s200.execute(jc, 100));
assertEquals(52, s200.execute(jc, 10));
}
@Test
void test200b() {
final JexlContext jc = new MapContext();
final JexlEngine jexl = new JexlBuilder().create();
final JexlScript e = jexl.createScript("var x = 0; var f = (y)->{ x = y; }; f(42); x");
final Object r = e.execute(jc);
assertEquals(0, r);
}
@Test
void test209a() {
final JexlContext jc = new MapContext();
final JexlEngine jexl = new JexlBuilder().create();
final JexlScript e = jexl.createScript("var x = new('java.util.HashMap'); x.a = ()->{return 1}; x['a']()");
final Object r = e.execute(jc);
assertEquals(1, r);
}
@Test
void test209b() {
final JexlContext jc = new MapContext();
final JexlEngine jexl = new JexlBuilder().create();
final JexlScript e = jexl.createScript("var x = new('java.util.HashMap'); x['a'] = ()->{return 1}; x.a()");
final Object r = e.execute(jc);
assertEquals(1, r);
}
@Test
void test210() {
final JexlContext jc = new MapContext();
jc.set("v210", new T210());
final JexlEngine jexl = new JexlBuilder().strict(false).silent(false).create();
final JexlScript e = jexl.createScript("v210.npe()");
final JexlException xjexl = assertThrows(JexlException.class, () -> e.execute(jc));
final Throwable th = xjexl.getCause();
assertEquals("NPE210", th.getMessage());
}
@Test
void test217() {
final JexlEvalContext jc = new JexlEvalContext();
final JexlOptions options = jc.getEngineOptions();
jc.set("foo", new int[]{0, 1, 2, 42});
JexlEngine jexl;
JexlScript e;
Object r;
jexl = new JexlBuilder().strict(false).silent(false).create();
e = jexl.createScript("foo[3]");
r = e.execute(jc);
assertEquals(42, r);
// cache and fail?
jc.set("foo", new int[]{0, 1});
options.setStrict(true);
assertTrue(options.isStrict());
final JexlException xjexl = assertThrows(JexlException.class, () -> e.execute(jc));
assertEquals(ArrayIndexOutOfBoundsException.class, xjexl.getCause().getClass());
//
options.setStrict(false);
r = e.execute(jc);
assertNull(r, "oob adverted");
}
@Test
void test221() {
final JexlEvalContext jc = new JexlEvalContext();
final Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
jc.set("map", map);
final JexlEngine jexl = new JexlBuilder().cache(256).create();
final JexlScript e = jexl.createScript("(x)->{ map[x] }");
Object r;
r = e.execute(jc, (Object) null);
assertNull(r);
r = e.execute(jc, (Object) null);
assertNull(r);
r = e.execute(jc, "one");
assertEquals(1, r);
}
@Test
void test224() {
final List<String> a0 = Arrays.asList("one", "two");
final Set<String> a1 = new TreeSet<>(a0);
final JexlContext jc = new MapContext();
final JexlEngine jexl = new JexlBuilder().arithmetic(new JexlArithmetic224(true)).create();
Object r;
JexlScript e = jexl.createScript("(map, x)->{ map[x] }");
r = e.execute(jc, a0, 1);
assertEquals("two", r);
r = e.execute(jc, a1, 1);
assertEquals("two", r);
e = jexl.createScript("(map)->{ map.1 }");
r = e.execute(jc, a0);
assertEquals("two", r);
r = e.execute(jc, a1);
assertEquals("two", r);
e = jexl.createScript("(map, x)->{ map(x) }");
r = e.execute(jc, a0, 1);
assertEquals("two", r);
r = e.execute(jc, a1, 1);
assertEquals("two", r);
}
@Test
void test225() {
final Context225 df = new Context225();
final JexlEngine jexl = new JexlBuilder().create();
final JexlExpression expression = jexl.createExpression("bar()");
assertEquals("bar", expression.evaluate(df));
final ObjectContext<Object> context = new ObjectContext<>(jexl, df);
assertEquals("bar", expression.evaluate(context));
}
@Test
void test230() {
final JexlEngine jexl = new JexlBuilder().cache(4).create();
final JexlContext ctxt = new MapContext();
final int[] foo = {42};
ctxt.set("fo o", foo);
Object value;
for (int l = 0; l < 2; ++l) {
value = jexl.createExpression("fo\\ o[0]").evaluate(ctxt);
assertEquals(42, value);
value = jexl.createExpression("fo\\ o[0] = 43").evaluate(ctxt);
assertEquals(43, value);
value = jexl.createExpression("fo\\ o.0").evaluate(ctxt);
assertEquals(43, value);
value = jexl.createExpression("fo\\ o.0 = 42").evaluate(ctxt);
assertEquals(42, value);
}
}
@Test
void test241() {
ExecutorService pool;
final JexlScript script = new JexlBuilder().create().createScript("`${item}`");
pool = Executors.newFixedThreadPool(4);
final Map<String, Object> m1 = new HashMap<>();
m1.put("item", "A");
final Map<String, Object> m2 = new HashMap<>();
m2.put("item", "B");
handle(pool, script, m1);
script.execute(new MapContext(m2));
pool.shutdown();
}
@Test
void test242() {
final Double a = -40.05d;
final Double b = -8.01d;
final Double c = a + b;
final JexlContext context = new MapContext();
context.set("a", a);
context.set("b", b);
final JexlEngine JEXL_ENGINE = new JexlBuilder().strict(true).silent(true).create();
final JexlExpression jsp = JEXL_ENGINE.createExpression("a + b");
final Double e = (Double) jsp.evaluate(context);
assertEquals(c, e, 0.0, () -> Double.doubleToLongBits(e) + " != " + Double.doubleToLongBits(c));
assertEquals(a + b, e, 0.0, () -> Double.doubleToLongBits(e) + " != " + Double.doubleToLongBits(c));
}
@Test
void test243a() {
final JexlEngine jexl = new JexlBuilder().cache(32).create();
final JexlScript script = jexl.createScript("while(true);");
assertThrows(JexlException.class, () -> jexl.createExpression("while(true);"), "expr do not allow 'while' statement");
}
@Test
void test245() {
final MapContext ctx = new MapContext();
final Foo245 foo245 = new Foo245();
ctx.set("foo", foo245);
final JexlEngine engine = new JexlBuilder().strict(true).safe(false).silent(false).create();
final JexlExpression foobar = engine.createExpression("foo.bar");
final JexlExpression foobaz = engine.createExpression("foo.baz");
final JexlExpression foobarbaz = engine.createExpression("foo.bar.baz");
// add ambiguity with null & not-null
final Object[] args = { null, 245 };
for (final Object arg : args) {
foo245.setBar(arg);
// ok
assertEquals(foo245.getBar(), foobar.evaluate(ctx));
// fail level 1
assertThrows(JexlException.Property.class, () -> foobaz.evaluate(ctx), "foo.baz is not solvable, exception expected");
// fail level 2
assertThrows(JexlException.Property.class, () -> foobarbaz.evaluate(ctx), "foo.bar.baz is not solvable, exception expected");
}
}
@Test
void test256() {
final MapContext ctx = new MapContext() {
@Override
public Object get(final String name) {
if ("java".equals(name)) {
return null;
}
return super.get(name);
}
@Override
public boolean has(final String name) {
if ("java".equals(name)) {
return false;
}
return super.has(name);
}
@Override
public void set(final String name, final Object value) {
if ("java".equals(name)) {
throw new JexlException(null, "cannot set " + name);
}
super.set(name, value);
}
};
ctx.set("java.version", 10);
final JexlEngine engine = new JexlBuilder().strict(true).silent(false).create();
final JexlScript script = engine.createScript("java = 3");
assertThrows(JexlException.class, () -> script.execute(ctx));
assertEquals(10, engine.createScript("java.version").execute(ctx));
}
@Test
void test265() {
final JexlEngine jexl = new JexlBuilder().cache(4).create();
final JexlContext ctxt = new MapContext();
ctxt.set("x", 42);
Object result;
JexlScript script;
assertThrows(JexlException.Parsing.class, () -> jexl.createScript("(true) ? x : abs(1)"), "ambiguous, parsing should fail");
script = jexl.createScript("(true) ? (x) : abs(2)");
result = script.execute(ctxt);
assertEquals(42, result);
script = jexl.createScript("(true) ? x : (abs(3))");
result = script.execute(ctxt);
assertEquals(42, result);
script = jexl.createScript("(!true) ? abs(4) : x");
result = script.execute(ctxt);
assertEquals(42, result);
}
@Test
void test266() {
Object result;
JexlScript script;
final JexlEngine jexl = new JexlBuilder().arithmetic(new Arithmetic266(true)).create();
final JexlContext ctxt = new MapContext();
final List<Integer> li = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5 ,6));
ctxt.set("list", li);
script = jexl.createScript("for (var item : list) { if (item <= 3) remove(); } return size(list)");
result = script.execute(ctxt);
assertEquals(3, result);
assertEquals(3, li.size());
final Map<String, Integer> msi = new HashMap<>();
msi.put("a", 1);
msi.put("b", 2);
msi.put("c", 3);
msi.put("d", 4);
msi.put("e", 5);
msi.put("f", 6);
ctxt.set("map", msi);
script = jexl.createScript("for (var item : map) { if (item <= 2) remove(); } return size(map)");
result = script.execute(ctxt);
assertEquals(4, result);
assertEquals(4, msi.size());
}
@Test
void test267() {
Object result;
JexlScript script;
final JexlEngine jexl = new JexlBuilder().create();
final JexlContext ctxt = new MapContext();
// API declared params
script = jexl.createScript("x + y", "x", "y");
result = script.execute(ctxt, 20, 22);
assertEquals(42, result);
// script declared params
script = jexl.createScript("(x, y)->{ x + y}");
result = script.execute(ctxt, 22, 20);
assertEquals(42, result);
// explicitly returning the lambda
script = jexl.createScript("return (x, y)->{ x + y}");
result = script.execute(ctxt);
assertInstanceOf(JexlScript.class, result);
}
@Test
void test274() {
JexlEngine jexl = new JexlBuilder().strict(true).safe(true).stackOverflow(5).create();
final JexlContext ctxt = new MapContext();
final JexlScript script = jexl.createScript("var f = (x)->{ x > 1? x * f(x - 1) : x }; f(a)", "a");
final Object result = script.execute(ctxt, 3);
assertEquals(6, result);
JexlException.StackOverflow xstack = assertThrows(JexlException.StackOverflow.class, () -> script.execute(ctxt, 32));
assertTrue(xstack.toString().contains("jexl"));
jexl = new JexlBuilder().strict(true).create();
final JexlScript script2 = jexl.createScript("var f = (x)->{ x * f(x - 1) }; f(a)", "a");
xstack = assertThrows(JexlException.StackOverflow.class, () -> script2.execute(ctxt, 32));
assertTrue(xstack.toString().contains("jvm"));
}
@Test
void test275a() {
final JexlContext ctxt = new MapContext();
ctxt.set("out", System.out);
final JexlEngine jexl = new JexlBuilder().strict(true).safe(true).create();
final JexlScript e = jexl.createScript("out.println(xyz)");
final JexlException.Variable xvar = assertThrows(JexlException.Variable.class, () -> e.execute(ctxt));
assertEquals("xyz", xvar.getVariable());
}
@Test
void test275b() {
final JexlContext ctxt = new MapContext();
// ctxt.set("out", System.out);
final JexlEngine jexl = new JexlBuilder().strict(true).safe(true).create();
final JexlScript e = jexl.createScript("var xyz = xyz");
final Object o = e.execute(ctxt);
assertNull(o);
}
@Test
void test275c() {
final JexlContext ctxt = new MapContext();
// ctxt.set("out", System.out);
final JexlEngine jexl = new JexlBuilder().strict(true).safe(true).silent(true).create();
JexlScript e;
Object r;
e = jexl.createScript("(s, v)->{ var x = y ; 42; }");
// wont make an error
r = e.execute(ctxt, false, true);
assertEquals(42, r);
}
@Test
void test275d() {
final JexlContext ctxt = new MapContext();
ctxt.set("out", System.out);
final JexlEngine jexl = new JexlBuilder().strict(true).safe(true).create();
final JexlScript e = jexl.createScript("{ var xyz = 42 } out.println(xyz)");
final Object o = e.execute(ctxt);
assertNull(o);
}
@Test
void test278() {
// @formatter:off
final String[] srcs = {
"return union x143('arg',5,6) ",
"return union y143('arg',5,6) ;",
"return union\n z143('arg',5,6) ;",
"var f =()->{ return union 143 } foo[0]"
};
final Object[] ctls = {
"42","42","42", 42
};
// @formatter:on
final JexlEngine jexl = new JexlBuilder().cache(4).create();
final JexlContext ctxt = new MapContext();
final int[] foo = { 42 };
ctxt.set("foo", foo);
ctxt.set("union", "42");
Object value;
JexlScript jc;
for (int i = 0; i < srcs.length; ++i) {
final String src = srcs[i];
final JexlException.Ambiguous xa = assertThrows(JexlException.Ambiguous.class, () -> jexl.createScript(src), src);
final String str = xa.toString();
assertTrue(str.contains("143"));
final String clean = xa.tryCleanSource(src);
jc = jexl.createScript(clean);
value = jc.execute(ctxt);
assertEquals(ctls[i], value, clean);
}
}
@Test
void test279() {
final Log logger = null; // LogFactory.getLog(Issues200Test.class);
Object result;
JexlScript script;
final JexlContext ctxt = new Context279();
// @formatter:off
final String[] srcs = {
"var z = null; identity(z[0]);",
"var z = null; z.0;",
"var z = null; z.foo();",
"z['y']['z']",
"z.y.any()",
"identity(z.any())",
"z[0]",
"z.0",
"z.foo()",
"z.y[0]",
"z.y[0].foo()",
"z.y.0",
"z.y.foo()",
"var z = { 'y' : [42] }; z.y[1]",
"var z = { 'y' : [42] }; z.y.1",
"var z = { 'y' : [-42] }; z.y[1].foo()",
"var z = { 'y' : [42] }; z.y.1.foo()",
"var z = { 'y' : [null, null] }; z.y[1].foo()",
"var z = { 'y' : [null, null] }; z.y.1.foo()"
};
// @formatter:on
for (int i = 0; i < 2; ++i) {
for (final boolean strict : new boolean[] { true, false }) {
final JexlEngine jexl = new JexlBuilder().safe(false).strict(strict).create();
for (final String src : srcs) {
script = jexl.createScript(src);
try {
result = script.execute(ctxt);
if (strict) {
if (logger != null) {
logger.warn(ctxt.has("z") + ": " + src + ": no fail, " + result);
}
fail("should have failed: " + src);
}
// not reachable
assertNull(result, "non-null result ?!");
} catch (final JexlException.Variable xvar) {
if (logger != null) {
logger.warn(ctxt.has("z") + ": " + src + ": fail, " + xvar);
}
if (!strict) {
fail(src + ", should not have thrown " + xvar);
} else {
assertTrue(xvar.toString().contains("z"), () -> src + ": " + xvar.toString());
}
} catch (final JexlException.Property xprop) {
if (logger != null) {
logger.warn(ctxt.has("z") + ": " + src + ": fail, " + xprop);
}
if (!strict) {
fail(src + ", should not have thrown " + xprop);
} else {
assertTrue(xprop.toString().contains("1"), () -> src + ": " + xprop.toString());
}
}
}
}
ctxt.set("z.y", null);
}
}
@Test
void test279b() {
Object result;
JexlScript script;
final JexlContext ctxt = new Context279();
ctxt.set("ctxt", ctxt);
final String src = "(x)->{ spread(x)[0].toString() }";
final JexlEngine jexl = new JexlBuilder().safe(true).strict(true).create();
script = jexl.createScript(src);
result = script.execute(ctxt, "abc");
assertEquals("a", result);
result = script.execute(ctxt, (Object) null);
assertNull(result);
}
@Test
void test285() {
final List<String> out = new ArrayList<>(6);
final JexlContext ctxt = new MapContext();
ctxt.set("$out", out);
// @formatter:off
final String src = "for(var b: ['g','h','i']) {\n"
+ " var c = b;\n"
+ " $out.add(c);\n"
+ "}\n"
+ " \n"
+ "for(var dc: ['j','k','l']) {\n"
+ " $out.add(dc);\n"
+ "}"
+ " \n"
+ "$out.size()";
// @formatter:on
final JexlFeatures features = new JexlFeatures();
features.lexical(true);
final JexlEngine jexl = new JexlBuilder()
//.features(features)
.safe(false).strict(true).lexical(true).create();
final JexlScript script = jexl.createScript(src);
final Object result = script.execute(ctxt, (Object) null);
assertEquals(6, result);
final List<String> ctl = Arrays.asList("g", "h", "i", "j", "k", "l");
assertEquals(ctl, out);
}
@Test
void test285a() {
final List<String> out = new ArrayList<>(6);
final JexlContext ctxt = new MapContext();
ctxt.set("$out", out);
final String src =
"for(var b: ['g','h','i']) { $out.add(b); }\n"
+ "for(b: ['j','k','l']) { $out.add(b);}\n"
+ "$out.size()";
final JexlEngine jexl = new JexlBuilder().safe(false).strict(true).lexical(false).create();
final JexlScript script = jexl.createScript(src);
final Object result = script.execute(ctxt, (Object) null);
assertEquals(6, result);
final List<String> ctl = Arrays.asList("g", "h", "i", "j", "k", "l");
assertEquals(ctl, out);
}
@Test
void test285b() {
final List<String> out = new ArrayList<>(6);
final JexlContext ctxt = new MapContext();
ctxt.set("$out", out);
final String src =
"for(b: ['g','h','i']) { $out.add(b); }\n"
+ "for(var b: ['j','k','l']) { $out.add(b);}\n"
+ "$out.size()";
final JexlEngine jexl = new JexlBuilder().safe(false).strict(true).create();
final JexlScript script = jexl.createScript(src);
final Object result = script.execute(ctxt, (Object) null);
assertEquals(6, result);
final List<String> ctl = Arrays.asList("g", "h", "i", "j", "k", "l");
assertEquals(ctl, out);
}
@Test
void test286() {
final String s286 = "var x = 0; for(x : 1..2){}; return x";
final JexlEngine jexl = new JexlBuilder().strict(true).create();
assertEquals(2, jexl.createScript(s286).execute(null));
}
@Test
void test287() {
final JexlEvalContext ctxt = new JexlEvalContext();
final JexlOptions options = ctxt.getEngineOptions();
final JexlEngine jexl = new JexlBuilder().strict(true).create();
String src;
JexlScript script;
Object result;
// declared, not defined
src = "x = 1; if (false) var x = 2; x";
script = jexl.createScript(src);
result = script.execute(ctxt);
assertEquals(1, result);
// declared and defined
src = "x = 1; if (true) var x = 2; x";
script = jexl.createScript(src);
result = script.execute(ctxt);
assertEquals(2, result);
// definition using shadowed global
src = "x = 1; var x = x + 41; x";
script = jexl.createScript(src);
result = script.execute(ctxt);
assertEquals(42, result);
// definition using shadowed global
options.setLexical(false);
src = "(x)->{ if (x==1) { var y = 2; } else if (x==2) { var y = 3; }; y }";
final JexlScript script1 = jexl.createScript(src);
result = script1.execute(ctxt, 1);
assertEquals(2, result);
result = script1.execute(ctxt, 2);
assertEquals(3, result);
options.setStrict(true);
final JexlException.Variable xvar = assertThrows(JexlException.Variable.class, () -> script1.execute(ctxt, 0));
assertTrue(xvar.getMessage().contains("y"));
options.setStrict(false);
result = script1.execute(ctxt, 0);
assertNull(result);
}
@Test
void test289() {
final JexlContext ctxt = new MapContext();
final JexlEngine jexl = new JexlBuilder().strict(true).create();
String src;
JexlScript script;
Object result;
src = "var x = function(a) { var b; return b}; x(1,2)";
script = jexl.createScript(src);
result = script.execute(ctxt);
assertNull(result);
}
@Test
void test290a() {
Object result;
JexlScript script;
final String[] srcs = {
"(x)->{ x.nothing().toString() }",
"(x)->{ x.toString().nothing() }",
"(x)->{ x.nothing().nothing() }",
};
for (final boolean safe : new boolean[]{true, false}) {
final JexlEngine jexl = new JexlBuilder().safe(safe).strict(true).create();
for (final String src : srcs) {
script = jexl.createScript(src);
try {
result = script.execute(null, "abc");
if (!safe) {
fail("should have failed: " + src);
} else {
assertNull(result, "non-null result ?!");
}
} catch (final JexlException.Method xmethod) {
if (safe) {
fail(src + ", should not have thrown " + xmethod);
} else {
assertTrue(xmethod.toString().contains("nothing"), () -> src + ": " + xmethod.toString());
}
}
}
}
}
@Test
void test290b() {
Object result;
JexlScript script;
final String[] srcs = {
"(x)->{ x?.nothing()?.toString() }",
"(x)->{ x.toString()?.nothing() }",
"(x)->{ x?.nothing().nothing() }",};
final JexlEngine jexl = new JexlBuilder().strict(true).create();
for (final String src : srcs) {
script = jexl.createScript(src);
result = script.execute(null, "abc");
assertNull(result);
}
}
@Test
void test291() {
final String str = "{1:'one'}[1]";
final JexlContext ctxt = new MapContext();
final JexlEngine jexl = new JexlBuilder().create();
JexlExpression e = jexl.createExpression(str);
Object value = e.evaluate(ctxt);
assertEquals("one", value);
final JexlEngine sandboxedJexlEngine = new JexlBuilder().
sandbox(new JexlSandbox(true)). // add a whitebox sandbox
create();
e = sandboxedJexlEngine.createExpression(str);
value = e.evaluate(ctxt);
assertEquals("one", value);
}
@Test
void test298() {
final Cls298 c298 = new Cls298();
final JexlContext ctxt = new MapContext();
final JexlEngine jexl = new JexlBuilder().create();
String str = "c.size()";
JexlScript e = jexl.createScript(str, "c");
Object value = e.execute(ctxt, c298);
assertEquals(42, value, str);
str = "size c";
e = jexl.createScript(str, "c");
value = e.execute(ctxt, c298);
assertEquals(42, value, str);
str = "c.size(127)";
e = jexl.createScript(str, "c");
value = e.execute(ctxt, c298);
assertEquals(169, value, str);
}
@Test
void testTemplate6565a() {
final JexlEngine jexl = new JexlBuilder().create();
final JxltEngine jexlt = jexl.createJxltEngine();
final String source =
"$$ var res = '';\n" +
"$$ var meta = session.data['METADATA'];\n" +
"$$ if (meta) {\n" +
"$$ var entry = meta['ID'];\n" +
"$$ if (entry) {\n" +
"$$ var value = session.data[entry];\n" +
"$$ res = value?: '';\n" +
"$$ }\n" +
"$$ }\n" +
"${res}\n";
final JxltEngine.Template script = jexlt.createTemplate("$$", new StringReader(source));
assertNotNull(script);
final TemplateDebugger dbg = new TemplateDebugger();
final String refactored = dbg.debug(script) ? dbg.toString() : "";
assertNotNull(refactored);
assertEquals(source, refactored);
}
@Test
void testTemplate6565b() {
final JexlEngine jexl = new JexlBuilder().create();
final JxltEngine jexlt = jexl.createJxltEngine();
final String source =
"$$ var res = '';\n" +
"$$ var meta = session.data['METADATA'];\n" +
"$$ if (meta) {\n" +
"$$ var entry = meta['ID'];\n" +
"$$ if (entry) {\n" +
"$$ var value = session.data[entry];\n" +
"$$ res = value?: '';\n" +
"${res}\n" +
"$$ }\n" +
"$$ }\n";
final JxltEngine.Template script = jexlt.createTemplate("$$", new StringReader(source));
assertNotNull(script);
final TemplateDebugger dbg = new TemplateDebugger();
final String refactored = dbg.debug(script) ? dbg.toString() : "";
assertNotNull(refactored);
assertEquals(source, refactored);
}
}
|
apache/ozone | 36,526 | hadoop-ozone/mini-cluster/src/main/java/org/apache/hadoop/ozone/MiniOzoneHAClusterImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.ozone;
import static java.util.Collections.singletonList;
import static org.apache.hadoop.hdds.HddsConfigKeys.OZONE_METADATA_DIRS;
import static org.apache.ozone.test.GenericTestUtils.PortAllocator.getFreePort;
import static org.apache.ozone.test.GenericTestUtils.PortAllocator.localhostWithFreePort;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.net.BindException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hdds.ExitManager;
import org.apache.hadoop.hdds.conf.ConfigurationTarget;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.hdds.scm.HddsTestUtils;
import org.apache.hadoop.hdds.scm.ScmConfigKeys;
import org.apache.hadoop.hdds.scm.safemode.HealthyPipelineSafeModeRule;
import org.apache.hadoop.hdds.scm.safemode.SafeModeRuleFactory;
import org.apache.hadoop.hdds.scm.server.SCMConfigurator;
import org.apache.hadoop.hdds.scm.server.StorageContainerManager;
import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
import org.apache.hadoop.ozone.client.OzoneClient;
import org.apache.hadoop.ozone.client.OzoneClientFactory;
import org.apache.hadoop.ozone.container.common.utils.DatanodeStoreCache;
import org.apache.hadoop.ozone.ha.ConfUtils;
import org.apache.hadoop.ozone.om.OMConfigKeys;
import org.apache.hadoop.ozone.om.OzoneManager;
import org.apache.hadoop.ozone.om.ratis.OzoneManagerRatisServer;
import org.apache.hadoop.security.authentication.client.AuthenticationException;
import org.apache.ozone.test.GenericTestUtils;
import org.apache.ratis.util.function.CheckedConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* MiniOzoneHAClusterImpl creates a complete in-process Ozone cluster
* with OM HA and SCM HA suitable for running tests.
* The cluster consists of a set of
* OzoneManagers, StorageContainerManagers and multiple DataNodes.
*/
public class MiniOzoneHAClusterImpl extends MiniOzoneClusterImpl {
private static final Logger LOG =
LoggerFactory.getLogger(MiniOzoneHAClusterImpl.class);
private final OMHAService omhaService;
private final SCMHAService scmhaService;
private final String clusterMetaPath;
private int waitForClusterToBeReadyTimeout = 120000; // 2 min
private static final int RATIS_RPC_TIMEOUT = 1000; // 1 second
public static final int NODE_FAILURE_TIMEOUT = 2000; // 2 seconds
public MiniOzoneHAClusterImpl(
OzoneConfiguration conf,
SCMConfigurator scmConfigurator,
OMHAService omhaService,
SCMHAService scmhaService,
List<HddsDatanodeService> hddsDatanodes,
String clusterPath,
List<Service> services) {
super(conf, scmConfigurator, hddsDatanodes, services);
this.omhaService = omhaService;
this.scmhaService = scmhaService;
this.clusterMetaPath = clusterPath;
}
/**
* Returns the first OzoneManager from the list.
*/
@Override
public OzoneManager getOzoneManager() {
return this.omhaService.getServices().get(0);
}
@Override
protected OzoneClient createClient() throws IOException {
String omServiceId = omhaService.getServiceId();
if (omServiceId == null) {
// Non-HA cluster.
return OzoneClientFactory.getRpcClient(getConf());
} else {
// HA cluster
return OzoneClientFactory.getRpcClient(omServiceId, getConf());
}
}
public boolean isOMActive(String omNodeId) {
return omhaService.isServiceActive(omNodeId);
}
public Iterator<StorageContainerManager> getInactiveSCM() {
return scmhaService.inactiveServices();
}
public StorageContainerManager getSCM(String scmNodeId) {
return this.scmhaService.getServiceById(scmNodeId);
}
public OzoneManager getOzoneManager(int index) {
return this.omhaService.getServiceByIndex(index);
}
public OzoneManager getOzoneManager(String omNodeId) {
return this.omhaService.getServiceById(omNodeId);
}
public List<OzoneManager> getOzoneManagersList() {
return omhaService.getServices();
}
public List<StorageContainerManager> getStorageContainerManagersList() {
return scmhaService.getServices();
}
public StorageContainerManager getStorageContainerManager(int index) {
return this.scmhaService.getServiceByIndex(index);
}
public StorageContainerManager getScmLeader() {
return getStorageContainerManagers().stream()
.filter(StorageContainerManager::checkLeader)
.findFirst().orElse(null);
}
public OzoneManager waitForLeaderOM()
throws TimeoutException, InterruptedException {
final OzoneManager[] om = new OzoneManager[1];
GenericTestUtils.waitFor(() -> {
om[0] = getOMLeader();
return om[0] != null;
}, 200, waitForClusterToBeReadyTimeout);
return om[0];
}
/**
* Get OzoneManager leader object.
* @return OzoneManager object, null if there isn't one or more than one
*/
public OzoneManager getOMLeader() {
OzoneManager res = null;
for (OzoneManager ozoneManager : this.omhaService.getActiveServices()) {
if (ozoneManager.isLeaderReady()) {
if (res != null) {
// Found more than one leader
// Return null, expect the caller to retry in a while
return null;
}
// Found a leader
res = ozoneManager;
}
}
return res;
}
/**
* Start a previously inactive OM.
*/
public void startInactiveOM(String omNodeID) throws IOException {
omhaService.startInactiveService(omNodeID, OzoneManager::start);
}
/**
* Start a previously inactive SCM.
*/
public void startInactiveSCM(String scmNodeId) throws IOException {
scmhaService
.startInactiveService(scmNodeId, StorageContainerManager::start);
}
@Override
public void restartOzoneManager() throws IOException {
for (OzoneManager ozoneManager : omhaService.getServices()) {
try {
stopOM(ozoneManager);
} catch (Exception e) {
LOG.warn("Failed to stop OM: {}", ozoneManager.getOMServiceId());
}
}
omhaService.inactiveServices().forEachRemaining(omhaService::activate);
for (OzoneManager ozoneManager : omhaService.getServices()) {
ozoneManager.restart();
}
}
public void shutdownOzoneManager(OzoneManager ozoneManager) {
LOG.info("Shutting down OzoneManager " + ozoneManager.getOMNodeId());
ozoneManager.stop();
}
public void restartOzoneManager(OzoneManager ozoneManager, boolean waitForOM)
throws IOException, TimeoutException, InterruptedException {
LOG.info("Restarting OzoneManager " + ozoneManager.getOMNodeId());
ozoneManager.restart();
if (waitForOM) {
GenericTestUtils.waitFor(ozoneManager::isRunning,
1000, waitForClusterToBeReadyTimeout);
}
}
public void shutdownStorageContainerManager(StorageContainerManager scm) {
LOG.info("Shutting down StorageContainerManager " + scm.getScmId());
scm.stop();
scmhaService.removeInstance(scm);
}
public StorageContainerManager restartStorageContainerManager(
StorageContainerManager scm, boolean waitForSCM)
throws IOException, TimeoutException,
InterruptedException, AuthenticationException {
LOG.info("Restarting SCM in cluster " + this.getClass());
scmhaService.removeInstance(scm);
OzoneConfiguration scmConf = scm.getConfiguration();
shutdownStorageContainerManager(scm);
scm.join();
scm = HddsTestUtils.getScmSimple(scmConf, getSCMConfigurator());
scmhaService.addInstance(scm, true);
scm.start();
if (waitForSCM) {
waitForClusterToBeReady();
}
return scm;
}
@Override
public String getClusterId() {
return scmhaService.getServices().get(0)
.getClientProtocolServer().getScmInfo().getClusterId();
}
@Override
public StorageContainerManager getActiveSCM() {
for (StorageContainerManager scm : scmhaService.getServices()) {
if (scm.checkLeader()) {
return scm;
}
}
return null;
}
@Override
public void waitForSCMToBeReady()
throws TimeoutException, InterruptedException {
GenericTestUtils.waitFor(() -> {
for (StorageContainerManager scm : scmhaService.getServices()) {
if (scm.checkLeader()) {
return true;
}
}
return false;
}, 1000, waitForClusterToBeReadyTimeout);
}
@Override
public void stop() {
for (OzoneManager ozoneManager : this.omhaService.getServices()) {
if (ozoneManager != null) {
LOG.info("Stopping the OzoneManager {}", ozoneManager.getOMNodeId());
stopOM(ozoneManager);
}
}
for (StorageContainerManager scm : this.scmhaService.getServices()) {
if (scm != null) {
LOG.info("Stopping the StorageContainerManager {}", scm.getScmId());
scm.stop();
scm.join();
}
}
super.stop();
}
public void stopOzoneManager(int index) {
stopAndDeactivate(omhaService.getServices().get(index));
}
private void stopAndDeactivate(OzoneManager om) {
stopOM(om);
omhaService.deactivate(om);
}
public void stopOzoneManager(String omNodeId) {
stopAndDeactivate(omhaService.getServiceById(omNodeId));
}
private static void configureOMPorts(ConfigurationTarget conf,
String omServiceId, String omNodeId) {
String omAddrKey = ConfUtils.addKeySuffixes(
OMConfigKeys.OZONE_OM_ADDRESS_KEY, omServiceId, omNodeId);
String omHttpAddrKey = ConfUtils.addKeySuffixes(
OMConfigKeys.OZONE_OM_HTTP_ADDRESS_KEY, omServiceId, omNodeId);
String omHttpsAddrKey = ConfUtils.addKeySuffixes(
OMConfigKeys.OZONE_OM_HTTPS_ADDRESS_KEY, omServiceId, omNodeId);
String omRatisPortKey = ConfUtils.addKeySuffixes(
OMConfigKeys.OZONE_OM_RATIS_PORT_KEY, omServiceId, omNodeId);
conf.set(omAddrKey, localhostWithFreePort());
conf.set(omHttpAddrKey, localhostWithFreePort());
conf.set(omHttpsAddrKey, localhostWithFreePort());
conf.setInt(omRatisPortKey, getFreePort());
}
/**
* Builder for configuring the MiniOzoneCluster to run.
*/
public static class Builder extends MiniOzoneClusterImpl.Builder {
private static final String OM_NODE_ID_PREFIX = "omNode-";
private final List<OzoneManager> activeOMs = new ArrayList<>();
private final List<OzoneManager> inactiveOMs = new ArrayList<>();
private static final String SCM_NODE_ID_PREFIX = "scmNode-";
private final List<StorageContainerManager> activeSCMs = new ArrayList<>();
private final List<StorageContainerManager> inactiveSCMs = new ArrayList<>();
private String omServiceId;
private int numOfOMs;
private int numOfActiveOMs = ACTIVE_OMS_NOT_SET;
private String scmServiceId;
private int numOfSCMs;
private int numOfActiveSCMs = ACTIVE_SCMS_NOT_SET;
/**
* Creates a new Builder.
*
* @param conf configuration
*/
public Builder(OzoneConfiguration conf) {
super(conf);
}
public Builder setNumOfOzoneManagers(int numOMs) {
this.numOfOMs = numOMs;
return this;
}
public Builder setNumOfActiveOMs(int numActiveOMs) {
this.numOfActiveOMs = numActiveOMs;
return this;
}
public Builder setOMServiceId(String serviceId) {
this.omServiceId = serviceId;
return this;
}
public Builder setNumOfStorageContainerManagers(int numSCMs) {
this.numOfSCMs = numSCMs;
return this;
}
public Builder setNumOfActiveSCMs(int numActiveSCMs) {
this.numOfActiveSCMs = numActiveSCMs;
return this;
}
public Builder setSCMServiceId(String serviceId) {
this.scmServiceId = serviceId;
return this;
}
@Override
public MiniOzoneHAClusterImpl build() throws IOException {
if (numOfActiveOMs > numOfOMs) {
throw new IllegalArgumentException("Number of active OMs cannot be " +
"more than the total number of OMs");
}
// If num of ActiveOMs is not set, set it to numOfOMs.
if (numOfActiveOMs == ACTIVE_OMS_NOT_SET) {
numOfActiveOMs = numOfOMs;
}
// If num of SCMs it not set, set it to 1.
if (numOfSCMs == 0) {
numOfSCMs = 1;
}
// If num of ActiveSCMs is not set, set it to numOfSCMs.
if (numOfActiveSCMs == ACTIVE_SCMS_NOT_SET) {
numOfActiveSCMs = numOfSCMs;
}
DefaultMetricsSystem.setMiniClusterMode(true);
DatanodeStoreCache.setMiniClusterMode();
initializeConfiguration();
initOMRatisConf();
SCMHAService scmService;
OMHAService omService;
try {
scmService = createSCMService();
omService = createOMService();
} catch (AuthenticationException ex) {
throw new IOException("Unable to build MiniOzoneCluster. ", ex);
}
final List<HddsDatanodeService> hddsDatanodes = createHddsDatanodes();
MiniOzoneHAClusterImpl cluster = new MiniOzoneHAClusterImpl(conf,
scmConfigurator, omService, scmService, hddsDatanodes, path, getServices());
try {
cluster.startServices();
} catch (Exception e) {
throw new IOException("Unable to start services", e);
}
if (startDataNodes) {
cluster.startHddsDatanodes();
}
prepareForNextBuild();
return cluster;
}
protected int numberOfOzoneManagers() {
return numOfOMs;
}
protected void initOMRatisConf() {
// If test change the following config values we will respect,
// otherwise we will set lower timeout values.
long defaultDuration = OMConfigKeys.OZONE_OM_RATIS_MINIMUM_TIMEOUT_DEFAULT
.getDuration();
long curRatisRpcTimeout = conf.getTimeDuration(
OMConfigKeys.OZONE_OM_RATIS_MINIMUM_TIMEOUT_KEY,
defaultDuration, TimeUnit.MILLISECONDS);
conf.setTimeDuration(OMConfigKeys.OZONE_OM_RATIS_MINIMUM_TIMEOUT_KEY,
defaultDuration == curRatisRpcTimeout ?
RATIS_RPC_TIMEOUT : curRatisRpcTimeout, TimeUnit.MILLISECONDS);
long defaultNodeFailureTimeout =
OMConfigKeys.OZONE_OM_RATIS_SERVER_FAILURE_TIMEOUT_DURATION_DEFAULT.
getDuration();
long curNodeFailureTimeout = conf.getTimeDuration(
OMConfigKeys.OZONE_OM_RATIS_SERVER_FAILURE_TIMEOUT_DURATION_KEY,
defaultNodeFailureTimeout,
OMConfigKeys.OZONE_OM_RATIS_SERVER_FAILURE_TIMEOUT_DURATION_DEFAULT.
getUnit());
conf.setTimeDuration(
OMConfigKeys.OZONE_OM_RATIS_SERVER_FAILURE_TIMEOUT_DURATION_KEY,
curNodeFailureTimeout == defaultNodeFailureTimeout ?
NODE_FAILURE_TIMEOUT : curNodeFailureTimeout,
TimeUnit.MILLISECONDS);
}
/**
* Start OM service with multiple OMs.
*/
protected OMHAService createOMService() throws IOException,
AuthenticationException {
if (omServiceId == null) {
OzoneManager om = createAndStartSingleOM();
return new OMHAService(singletonList(om), null, null);
}
List<OzoneManager> omList = Lists.newArrayList();
int retryCount = 0;
while (true) {
try {
initOMHAConfig();
for (int i = 1; i <= numOfOMs; i++) {
// Set nodeId
String nodeId = OM_NODE_ID_PREFIX + i;
OzoneConfiguration config = new OzoneConfiguration(conf);
config.set(OMConfigKeys.OZONE_OM_NODE_ID_KEY, nodeId);
// Set the OM http(s) address to null so that the cluster picks
// up the address set with service ID and node ID in initHAConfig
config.set(OMConfigKeys.OZONE_OM_HTTP_ADDRESS_KEY, "");
config.set(OMConfigKeys.OZONE_OM_HTTPS_ADDRESS_KEY, "");
// Set metadata/DB dir base path
String metaDirPath = path + "/" + nodeId;
config.set(OZONE_METADATA_DIRS, metaDirPath);
OzoneManager.omInit(config);
OzoneManager om = OzoneManager.createOm(config);
setClients(om);
omList.add(om);
if (i <= numOfActiveOMs) {
om.start();
activeOMs.add(om);
LOG.info("Started OzoneManager {} RPC server at {}", nodeId,
om.getOmRpcServerAddr());
} else {
inactiveOMs.add(om);
LOG.info("Initialized OzoneManager at {}. This OM is currently "
+ "inactive (not running).", om.getOmRpcServerAddr());
}
}
break;
} catch (BindException e) {
for (OzoneManager om : omList) {
stopOM(om);
LOG.info("Stopping OzoneManager server at {}",
om.getOmRpcServerAddr());
}
omList.clear();
++retryCount;
LOG.info("MiniOzoneHACluster port conflicts, retried {} times",
retryCount, e);
}
}
return new OMHAService(activeOMs, inactiveOMs, omServiceId);
}
/**
* Start SCM service with multiple SCMs.
*/
protected SCMHAService createSCMService()
throws IOException, AuthenticationException {
if (scmServiceId == null) {
StorageContainerManager scm = createAndStartSingleSCM();
return new SCMHAService(singletonList(scm), null, null);
}
List<StorageContainerManager> scmList = Lists.newArrayList();
int retryCount = 0;
while (true) {
try {
initSCMHAConfig();
for (int i = 1; i <= numOfSCMs; i++) {
// Set nodeId
String nodeId = SCM_NODE_ID_PREFIX + i;
String metaDirPath = path + "/" + nodeId;
OzoneConfiguration scmConfig = new OzoneConfiguration(conf);
scmConfig.set(OZONE_METADATA_DIRS, metaDirPath);
scmConfig.set(ScmConfigKeys.OZONE_SCM_NODE_ID_KEY, nodeId);
configureSCM(true);
if (i == 1) {
StorageContainerManager.scmInit(scmConfig, clusterId);
} else {
StorageContainerManager.scmBootstrap(scmConfig);
}
StorageContainerManager scm =
HddsTestUtils.getScmSimple(scmConfig, scmConfigurator);
HealthyPipelineSafeModeRule rule = SafeModeRuleFactory.getInstance()
.getSafeModeRule(HealthyPipelineSafeModeRule.class);
if (rule != null) {
// Set threshold to wait for safe mode exit -
// this is needed since a pipeline is marked open only after
// leader election.
rule.setHealthyPipelineThresholdCount(numOfDatanodes / 3);
}
scmList.add(scm);
if (i <= numOfActiveSCMs) {
scm.start();
activeSCMs.add(scm);
LOG.info("Started SCM RPC server at {}",
scm.getClientRpcAddress());
} else {
inactiveSCMs.add(scm);
LOG.info("Initialized SCM at {}. This SCM is currently "
+ "inactive (not running).", scm.getClientRpcAddress());
}
}
break;
} catch (BindException e) {
for (StorageContainerManager scm : scmList) {
scm.stop();
scm.join();
LOG.info("Stopping StorageContainerManager server at {}",
scm.getClientRpcAddress());
}
scmList.clear();
++retryCount;
LOG.info("MiniOzoneHACluster port conflicts, retried {} times",
retryCount, e);
}
}
configureScmDatanodeAddress(activeSCMs);
return new SCMHAService(activeSCMs, inactiveSCMs, scmServiceId);
}
/**
* Initialize HA related configurations.
*/
private void initSCMHAConfig() {
// Set configurations required for starting SCM HA service, because that
// is the serviceID being passed to start Ozone HA cluster.
// Here setting internal service and OZONE_SCM_SERVICE_IDS_KEY, in this
// way in SCM start it uses internal service id to find it's service id.
conf.set(ScmConfigKeys.OZONE_SCM_SERVICE_IDS_KEY, scmServiceId);
conf.set(ScmConfigKeys.OZONE_SCM_DEFAULT_SERVICE_ID, scmServiceId);
String scmNodesKey = ConfUtils.addKeySuffixes(
ScmConfigKeys.OZONE_SCM_NODES_KEY, scmServiceId);
StringBuilder scmNodesKeyValue = new StringBuilder();
StringBuilder scmNames = new StringBuilder();
for (int i = 1; i <= numOfSCMs; i++) {
String scmNodeId = SCM_NODE_ID_PREFIX + i;
if (i == 1) {
conf.set(ScmConfigKeys.OZONE_SCM_PRIMORDIAL_NODE_ID_KEY, scmNodeId);
}
scmNodesKeyValue.append(',').append(scmNodeId);
String scmAddrKey = ConfUtils.addKeySuffixes(
ScmConfigKeys.OZONE_SCM_ADDRESS_KEY, scmServiceId, scmNodeId);
String scmHttpAddrKey = ConfUtils.addKeySuffixes(
ScmConfigKeys.OZONE_SCM_HTTP_ADDRESS_KEY, scmServiceId, scmNodeId);
String scmHttpsAddrKey = ConfUtils.addKeySuffixes(
ScmConfigKeys.OZONE_SCM_HTTPS_ADDRESS_KEY, scmServiceId, scmNodeId);
String scmRatisPortKey = ConfUtils.addKeySuffixes(
ScmConfigKeys.OZONE_SCM_RATIS_PORT_KEY, scmServiceId, scmNodeId);
String dnPortKey = ConfUtils.addKeySuffixes(
ScmConfigKeys.OZONE_SCM_DATANODE_ADDRESS_KEY,
scmServiceId, scmNodeId);
String blockClientKey = ConfUtils.addKeySuffixes(
ScmConfigKeys.OZONE_SCM_BLOCK_CLIENT_ADDRESS_KEY,
scmServiceId, scmNodeId);
String ssClientKey = ConfUtils.addKeySuffixes(
ScmConfigKeys.OZONE_SCM_CLIENT_ADDRESS_KEY,
scmServiceId, scmNodeId);
String scmGrpcPortKey = ConfUtils.addKeySuffixes(
ScmConfigKeys.OZONE_SCM_GRPC_PORT_KEY, scmServiceId, scmNodeId);
String scmSecurityAddrKey = ConfUtils.addKeySuffixes(
ScmConfigKeys.OZONE_SCM_SECURITY_SERVICE_ADDRESS_KEY, scmServiceId,
scmNodeId);
conf.set(scmAddrKey, "127.0.0.1");
conf.set(scmHttpAddrKey, localhostWithFreePort());
conf.set(scmHttpsAddrKey, localhostWithFreePort());
conf.set(scmSecurityAddrKey, localhostWithFreePort());
int ratisPort = getFreePort();
conf.setInt(scmRatisPortKey, ratisPort);
//conf.setInt("ozone.scm.ha.ratis.bind.port", ratisPort);
int dnPort = getFreePort();
conf.set(dnPortKey, "127.0.0.1:" + dnPort);
scmNames.append(",localhost:").append(dnPort);
conf.set(ssClientKey, localhostWithFreePort());
conf.setInt(scmGrpcPortKey, getFreePort());
String blockAddress = localhostWithFreePort();
conf.set(blockClientKey, blockAddress);
conf.set(ScmConfigKeys.OZONE_SCM_BLOCK_CLIENT_ADDRESS_KEY,
blockAddress);
}
conf.set(scmNodesKey, scmNodesKeyValue.substring(1));
conf.set(ScmConfigKeys.OZONE_SCM_NAMES, scmNames.substring(1));
}
/**
* Initialize HA related configurations.
*/
private void initOMHAConfig() {
// Set configurations required for starting OM HA service, because that
// is the serviceID being passed to start Ozone HA cluster.
// Here setting internal service and OZONE_OM_SERVICE_IDS_KEY, in this
// way in OM start it uses internal service id to find it's service id.
conf.set(OMConfigKeys.OZONE_OM_SERVICE_IDS_KEY, omServiceId);
conf.set(OMConfigKeys.OZONE_OM_INTERNAL_SERVICE_ID, omServiceId);
String omNodesKey = ConfUtils.addKeySuffixes(
OMConfigKeys.OZONE_OM_NODES_KEY, omServiceId);
List<String> omNodeIds = new ArrayList<>();
for (int i = 1; i <= numOfOMs; i++) {
String omNodeId = OM_NODE_ID_PREFIX + i;
omNodeIds.add(omNodeId);
configureOMPorts(conf, omServiceId, omNodeId);
}
conf.set(omNodesKey, String.join(",", omNodeIds));
}
}
/**
* Bootstrap new OM by updating existing OM configs.
*/
public void bootstrapOzoneManager(String omNodeId) throws Exception {
bootstrapOzoneManager(omNodeId, true, false);
}
/**
* Bootstrap new OM and add to existing OM HA service ring.
* @param omNodeId nodeId of new OM
* @param updateConfigs if true, update the old OM configs with new node
* information
* @param force if true, start new OM with FORCE_BOOTSTRAP option.
* Otherwise, start new OM with BOOTSTRAP option.
*/
public void bootstrapOzoneManager(String omNodeId,
boolean updateConfigs, boolean force) throws Exception {
bootstrapOzoneManager(omNodeId, updateConfigs, force, false);
}
public void bootstrapOzoneManager(String omNodeId,
boolean updateConfigs, boolean force, boolean isListener) throws Exception {
// Set testReloadConfigFlag to true so that
// OzoneManager#reloadConfiguration does not reload config as it will
// return the default configurations.
OzoneManager.setTestReloadConfigFlag(true);
int retryCount = 0;
OzoneManager om = null;
OzoneManager omLeader = waitForLeaderOM();
long leaderSnapshotIndex = omLeader.getRatisSnapshotIndex();
while (true) {
try {
OzoneConfiguration newConf = addNewOMToConfig(omhaService.getServiceId(),
omNodeId, isListener);
if (updateConfigs) {
updateOMConfigs(newConf);
}
om = bootstrapNewOM(omNodeId, newConf, force);
LOG.info("Bootstrapped OzoneManager {} RPC server at {}", omNodeId,
om.getOmRpcServerAddr());
// Add new OMs to cluster's in memory map and update existing OMs conf.
setConf(newConf);
break;
} catch (IOException e) {
// Existing OM config could have been updated with new conf. Reset it.
for (OzoneManager existingOM : omhaService.getServices()) {
existingOM.setConfiguration(getConf());
}
if (e instanceof BindException ||
e.getCause() instanceof BindException) {
++retryCount;
LOG.info("MiniOzoneHACluster port conflicts, retried {} times",
retryCount, e);
} else {
throw e;
}
}
}
waitForBootstrappedNodeToBeReady(om, leaderSnapshotIndex);
if (updateConfigs) {
waitForConfigUpdateOnActiveOMs(omNodeId);
}
}
/**
* Set the configs for new OMs.
*/
private OzoneConfiguration addNewOMToConfig(String omServiceId,
String omNodeId, boolean isListener) {
OzoneConfiguration newConf = new OzoneConfiguration(getConf());
configureOMPorts(newConf, omServiceId, omNodeId);
String omNodesKey = ConfUtils.addKeySuffixes(
OMConfigKeys.OZONE_OM_NODES_KEY, omServiceId);
newConf.set(omNodesKey, newConf.get(omNodesKey) + "," + omNodeId);
if (isListener) {
// append to listener nodes list config
String listenerOmNodesKey = ConfUtils.addKeySuffixes(
OMConfigKeys.OZONE_OM_LISTENER_NODES_KEY, omServiceId);
String existingListenerNodes = newConf.get(listenerOmNodesKey);
if (StringUtils.isNotEmpty(existingListenerNodes)) {
newConf.set(listenerOmNodesKey, existingListenerNodes + "," + omNodeId);
} else {
newConf.set(listenerOmNodesKey, omNodeId);
}
}
return newConf;
}
/**
* Update the configurations of the given list of OMs.
*/
private void updateOMConfigs(OzoneConfiguration newConf) {
for (OzoneManager om : omhaService.getActiveServices()) {
om.setConfiguration(newConf);
}
}
/**
* Start a new OM in Bootstrap mode. Configs (address and ports) for the new
* OM must already be set in the newConf.
*/
private OzoneManager bootstrapNewOM(String nodeId, OzoneConfiguration newConf,
boolean force) throws IOException, AuthenticationException {
OzoneConfiguration config = new OzoneConfiguration(newConf);
// For bootstrapping node, set the nodeId config also.
config.set(OMConfigKeys.OZONE_OM_NODE_ID_KEY, nodeId);
// Set metadata/DB dir base path
String metaDirPath = clusterMetaPath + "/" + nodeId;
config.set(OZONE_METADATA_DIRS, metaDirPath);
OzoneManager.omInit(config);
OzoneManager om;
if (force) {
om = OzoneManager.createOm(config,
OzoneManager.StartupOption.FORCE_BOOTSTRAP);
} else {
om = OzoneManager.createOm(config, OzoneManager.StartupOption.BOOTSTRAP);
}
ExitManagerForOM exitManager = new ExitManagerForOM(this, nodeId);
om.setExitManagerForTesting(exitManager);
omhaService.addInstance(om, false);
startInactiveOM(nodeId);
return om;
}
/**
* Wait for AddOM command to execute on all OMs.
*/
private void waitForBootstrappedNodeToBeReady(OzoneManager newOM,
long leaderSnapshotIndex) throws Exception {
// Wait for bootstrapped nodes to catch up with others
GenericTestUtils.waitFor(() -> {
try {
if (newOM.getRatisSnapshotIndex() >= leaderSnapshotIndex) {
return true;
}
} catch (IOException e) {
return false;
}
return false;
}, 1000, waitForClusterToBeReadyTimeout);
}
private void waitForConfigUpdateOnActiveOMs(String newOMNodeId)
throws Exception {
OzoneManager newOMNode = omhaService.getServiceById(newOMNodeId);
OzoneManagerRatisServer newOMRatisServer = newOMNode.getOmRatisServer();
GenericTestUtils.waitFor(() -> {
// Each existing active OM should contain the new OM in its peerList.
// Also, the new OM should contain each existing active OM in it's OM
// peer list and RatisServer peerList.
for (OzoneManager om : omhaService.getActiveServices()) {
if (!om.doesPeerExist(newOMNodeId)) {
return false;
}
if (!newOMNode.doesPeerExist(om.getOMNodeId())) {
return false;
}
if (!newOMRatisServer.doesPeerExist(om.getOMNodeId())) {
return false;
}
}
return true;
}, 1000, waitForClusterToBeReadyTimeout);
}
public void setupExitManagerForTesting() {
for (OzoneManager om : omhaService.getServices()) {
om.setExitManagerForTesting(new ExitManagerForOM(this, om.getOMNodeId()));
}
}
/**
* MiniOzoneHAService is a helper class used for both SCM and OM HA.
* This class keeps track of active and inactive OM/SCM services
* @param <Type>
*/
static class MiniOzoneHAService<Type> {
private final Map<String, Type> serviceMap;
private final List<Type> services;
private final String serviceId;
private final String serviceName;
// Active services s denote OM/SCM services which are up and running
private final List<Type> activeServices;
private final List<Type> inactiveServices;
// Function to extract the Id from service
private final Function<Type, String> serviceIdProvider;
MiniOzoneHAService(String name, List<Type> activeList,
List<Type> inactiveList, String serviceId,
Function<Type, String> idProvider) {
this.serviceName = name;
this.serviceMap = Maps.newHashMap();
this.serviceIdProvider = idProvider;
if (activeList != null) {
for (Type service : activeList) {
this.serviceMap.put(idProvider.apply(service), service);
}
}
if (inactiveList != null) {
for (Type service : inactiveList) {
this.serviceMap.put(idProvider.apply(service), service);
}
}
this.services = new ArrayList<>(serviceMap.values());
this.activeServices = activeList;
this.inactiveServices = inactiveList;
this.serviceId = serviceId;
// If the serviceID is null, then this should be a non-HA cluster.
if (serviceId == null) {
Preconditions.checkArgument(services.size() <= 1);
}
}
public String getServiceId() {
return serviceId;
}
public List<Type> getServices() {
return services;
}
public List<Type> getActiveServices() {
return activeServices;
}
public boolean removeInstance(Type t) {
boolean result = services.remove(t);
serviceMap.remove(serviceIdProvider.apply(t));
activeServices.remove(t);
inactiveServices.remove(t);
return result;
}
public void addInstance(Type t, boolean isActive) {
services.add(t);
serviceMap.put(serviceIdProvider.apply(t), t);
if (isActive) {
activeServices.add(t);
} else {
inactiveServices.add(t);
}
}
public void activate(Type t) {
activeServices.add(t);
inactiveServices.remove(t);
}
public void deactivate(Type t) {
activeServices.remove(t);
inactiveServices.add(t);
}
public boolean isServiceActive(String id) {
return activeServices.contains(serviceMap.get(id));
}
public Iterator<Type> inactiveServices() {
return new ArrayList<>(inactiveServices).iterator();
}
public Type getServiceByIndex(int index) {
return this.services.get(index);
}
public Type getServiceById(String id) {
return this.serviceMap.get(id);
}
public void startInactiveService(String id,
CheckedConsumer<Type, IOException> serviceStarter) throws IOException {
Type service = serviceMap.get(id);
if (!inactiveServices.contains(service)) {
throw new IOException(serviceName + " is already active.");
} else {
serviceStarter.accept(service);
activeServices.add(service);
inactiveServices.remove(service);
}
}
}
static class OMHAService extends MiniOzoneHAService<OzoneManager> {
OMHAService(List<OzoneManager> activeList, List<OzoneManager> inactiveList,
String serviceId) {
super("OM", activeList, inactiveList, serviceId,
OzoneManager::getOMNodeId);
}
}
static class SCMHAService extends
MiniOzoneHAService<StorageContainerManager> {
SCMHAService(List<StorageContainerManager> activeList,
List<StorageContainerManager> inactiveList,
String serviceId) {
super("SCM", activeList, inactiveList, serviceId,
StorageContainerManager::getSCMNodeId);
}
}
public List<StorageContainerManager> getStorageContainerManagers() {
return new ArrayList<>(this.scmhaService.getServices());
}
@Override
public StorageContainerManager getStorageContainerManager() {
return getStorageContainerManagers().get(0);
}
private static final class ExitManagerForOM extends ExitManager {
private final MiniOzoneHAClusterImpl cluster;
private final String omNodeId;
private ExitManagerForOM(MiniOzoneHAClusterImpl cluster, String nodeId) {
this.cluster = cluster;
this.omNodeId = nodeId;
}
@Override
public void exitSystem(int status, String message, Throwable throwable,
Logger log) throws IOException {
LOG.error(omNodeId + " - System Exit: " + message, throwable);
cluster.stopOzoneManager(omNodeId);
throw new IOException(throwable);
}
@Override
public void exitSystem(int status, String message, Logger log)
throws IOException {
LOG.error(omNodeId + " - System Exit: " + message);
cluster.stopOzoneManager(omNodeId);
throw new IOException(message);
}
}
}
|
googleapis/google-cloud-java | 36,450 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/ListStudiesResponse.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.ListStudies][google.cloud.aiplatform.v1beta1.VizierService.ListStudies].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.ListStudiesResponse}
*/
public final class ListStudiesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.ListStudiesResponse)
ListStudiesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListStudiesResponse.newBuilder() to construct.
private ListStudiesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListStudiesResponse() {
studies_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListStudiesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.VizierServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListStudiesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.VizierServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListStudiesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.ListStudiesResponse.class,
com.google.cloud.aiplatform.v1beta1.ListStudiesResponse.Builder.class);
}
public static final int STUDIES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.aiplatform.v1beta1.Study> studies_;
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.aiplatform.v1beta1.Study> getStudiesList() {
return studies_;
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.StudyOrBuilder>
getStudiesOrBuilderList() {
return studies_;
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
@java.lang.Override
public int getStudiesCount() {
return studies_.size();
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.Study getStudies(int index) {
return studies_.get(index);
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.StudyOrBuilder getStudiesOrBuilder(int index) {
return studies_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Passes this token as the `page_token` field of the request for a
* subsequent call.
* 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>
* Passes this token as the `page_token` field of the request for a
* subsequent call.
* 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 < studies_.size(); i++) {
output.writeMessage(1, studies_.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 < studies_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, studies_.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.ListStudiesResponse)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.ListStudiesResponse other =
(com.google.cloud.aiplatform.v1beta1.ListStudiesResponse) obj;
if (!getStudiesList().equals(other.getStudiesList())) 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 (getStudiesCount() > 0) {
hash = (37 * hash) + STUDIES_FIELD_NUMBER;
hash = (53 * hash) + getStudiesList().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.ListStudiesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListStudiesResponse 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.ListStudiesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListStudiesResponse 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.ListStudiesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListStudiesResponse 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.ListStudiesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.ListStudiesResponse 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.ListStudiesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.ListStudiesResponse 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.ListStudiesResponse 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.ListStudiesResponse 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.ListStudiesResponse 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.ListStudies][google.cloud.aiplatform.v1beta1.VizierService.ListStudies].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.ListStudiesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.ListStudiesResponse)
com.google.cloud.aiplatform.v1beta1.ListStudiesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.VizierServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListStudiesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.VizierServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListStudiesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.ListStudiesResponse.class,
com.google.cloud.aiplatform.v1beta1.ListStudiesResponse.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.ListStudiesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (studiesBuilder_ == null) {
studies_ = java.util.Collections.emptyList();
} else {
studies_ = null;
studiesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
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_ListStudiesResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListStudiesResponse getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.ListStudiesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListStudiesResponse build() {
com.google.cloud.aiplatform.v1beta1.ListStudiesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListStudiesResponse buildPartial() {
com.google.cloud.aiplatform.v1beta1.ListStudiesResponse result =
new com.google.cloud.aiplatform.v1beta1.ListStudiesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.aiplatform.v1beta1.ListStudiesResponse result) {
if (studiesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
studies_ = java.util.Collections.unmodifiableList(studies_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.studies_ = studies_;
} else {
result.studies_ = studiesBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.aiplatform.v1beta1.ListStudiesResponse 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.ListStudiesResponse) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.ListStudiesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.ListStudiesResponse other) {
if (other == com.google.cloud.aiplatform.v1beta1.ListStudiesResponse.getDefaultInstance())
return this;
if (studiesBuilder_ == null) {
if (!other.studies_.isEmpty()) {
if (studies_.isEmpty()) {
studies_ = other.studies_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureStudiesIsMutable();
studies_.addAll(other.studies_);
}
onChanged();
}
} else {
if (!other.studies_.isEmpty()) {
if (studiesBuilder_.isEmpty()) {
studiesBuilder_.dispose();
studiesBuilder_ = null;
studies_ = other.studies_;
bitField0_ = (bitField0_ & ~0x00000001);
studiesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getStudiesFieldBuilder()
: null;
} else {
studiesBuilder_.addAllMessages(other.studies_);
}
}
}
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.Study m =
input.readMessage(
com.google.cloud.aiplatform.v1beta1.Study.parser(), extensionRegistry);
if (studiesBuilder_ == null) {
ensureStudiesIsMutable();
studies_.add(m);
} else {
studiesBuilder_.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.Study> studies_ =
java.util.Collections.emptyList();
private void ensureStudiesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
studies_ = new java.util.ArrayList<com.google.cloud.aiplatform.v1beta1.Study>(studies_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Study,
com.google.cloud.aiplatform.v1beta1.Study.Builder,
com.google.cloud.aiplatform.v1beta1.StudyOrBuilder>
studiesBuilder_;
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.Study> getStudiesList() {
if (studiesBuilder_ == null) {
return java.util.Collections.unmodifiableList(studies_);
} else {
return studiesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public int getStudiesCount() {
if (studiesBuilder_ == null) {
return studies_.size();
} else {
return studiesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Study getStudies(int index) {
if (studiesBuilder_ == null) {
return studies_.get(index);
} else {
return studiesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public Builder setStudies(int index, com.google.cloud.aiplatform.v1beta1.Study value) {
if (studiesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureStudiesIsMutable();
studies_.set(index, value);
onChanged();
} else {
studiesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public Builder setStudies(
int index, com.google.cloud.aiplatform.v1beta1.Study.Builder builderForValue) {
if (studiesBuilder_ == null) {
ensureStudiesIsMutable();
studies_.set(index, builderForValue.build());
onChanged();
} else {
studiesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public Builder addStudies(com.google.cloud.aiplatform.v1beta1.Study value) {
if (studiesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureStudiesIsMutable();
studies_.add(value);
onChanged();
} else {
studiesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public Builder addStudies(int index, com.google.cloud.aiplatform.v1beta1.Study value) {
if (studiesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureStudiesIsMutable();
studies_.add(index, value);
onChanged();
} else {
studiesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public Builder addStudies(com.google.cloud.aiplatform.v1beta1.Study.Builder builderForValue) {
if (studiesBuilder_ == null) {
ensureStudiesIsMutable();
studies_.add(builderForValue.build());
onChanged();
} else {
studiesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public Builder addStudies(
int index, com.google.cloud.aiplatform.v1beta1.Study.Builder builderForValue) {
if (studiesBuilder_ == null) {
ensureStudiesIsMutable();
studies_.add(index, builderForValue.build());
onChanged();
} else {
studiesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public Builder addAllStudies(
java.lang.Iterable<? extends com.google.cloud.aiplatform.v1beta1.Study> values) {
if (studiesBuilder_ == null) {
ensureStudiesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, studies_);
onChanged();
} else {
studiesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public Builder clearStudies() {
if (studiesBuilder_ == null) {
studies_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
studiesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public Builder removeStudies(int index) {
if (studiesBuilder_ == null) {
ensureStudiesIsMutable();
studies_.remove(index);
onChanged();
} else {
studiesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Study.Builder getStudiesBuilder(int index) {
return getStudiesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.StudyOrBuilder getStudiesOrBuilder(int index) {
if (studiesBuilder_ == null) {
return studies_.get(index);
} else {
return studiesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.StudyOrBuilder>
getStudiesOrBuilderList() {
if (studiesBuilder_ != null) {
return studiesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(studies_);
}
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Study.Builder addStudiesBuilder() {
return getStudiesFieldBuilder()
.addBuilder(com.google.cloud.aiplatform.v1beta1.Study.getDefaultInstance());
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Study.Builder addStudiesBuilder(int index) {
return getStudiesFieldBuilder()
.addBuilder(index, com.google.cloud.aiplatform.v1beta1.Study.getDefaultInstance());
}
/**
*
*
* <pre>
* The studies associated with the project.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Study studies = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.Study.Builder>
getStudiesBuilderList() {
return getStudiesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Study,
com.google.cloud.aiplatform.v1beta1.Study.Builder,
com.google.cloud.aiplatform.v1beta1.StudyOrBuilder>
getStudiesFieldBuilder() {
if (studiesBuilder_ == null) {
studiesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Study,
com.google.cloud.aiplatform.v1beta1.Study.Builder,
com.google.cloud.aiplatform.v1beta1.StudyOrBuilder>(
studies_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
studies_ = null;
}
return studiesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Passes this token as the `page_token` field of the request for a
* subsequent call.
* 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>
* Passes this token as the `page_token` field of the request for a
* subsequent call.
* 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>
* Passes this token as the `page_token` field of the request for a
* subsequent call.
* 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>
* Passes this token as the `page_token` field of the request for a
* subsequent call.
* 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>
* Passes this token as the `page_token` field of the request for a
* subsequent call.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.ListStudiesResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.ListStudiesResponse)
private static final com.google.cloud.aiplatform.v1beta1.ListStudiesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.ListStudiesResponse();
}
public static com.google.cloud.aiplatform.v1beta1.ListStudiesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListStudiesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListStudiesResponse>() {
@java.lang.Override
public ListStudiesResponse 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<ListStudiesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListStudiesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListStudiesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,472 | java-recommender/proto-google-cloud-recommender-v1/src/main/java/com/google/cloud/recommender/v1/UpdateRecommenderConfigRequest.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/recommender/v1/recommender_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.recommender.v1;
/**
*
*
* <pre>
* Request for the `UpdateRecommenderConfig` method.
* </pre>
*
* Protobuf type {@code google.cloud.recommender.v1.UpdateRecommenderConfigRequest}
*/
public final class UpdateRecommenderConfigRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.recommender.v1.UpdateRecommenderConfigRequest)
UpdateRecommenderConfigRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateRecommenderConfigRequest.newBuilder() to construct.
private UpdateRecommenderConfigRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateRecommenderConfigRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateRecommenderConfigRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.recommender.v1.RecommenderProto
.internal_static_google_cloud_recommender_v1_UpdateRecommenderConfigRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.recommender.v1.RecommenderProto
.internal_static_google_cloud_recommender_v1_UpdateRecommenderConfigRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest.class,
com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest.Builder.class);
}
private int bitField0_;
public static final int RECOMMENDER_CONFIG_FIELD_NUMBER = 1;
private com.google.cloud.recommender.v1.RecommenderConfig recommenderConfig_;
/**
*
*
* <pre>
* Required. The RecommenderConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.RecommenderConfig recommender_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the recommenderConfig field is set.
*/
@java.lang.Override
public boolean hasRecommenderConfig() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The RecommenderConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.RecommenderConfig recommender_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The recommenderConfig.
*/
@java.lang.Override
public com.google.cloud.recommender.v1.RecommenderConfig getRecommenderConfig() {
return recommenderConfig_ == null
? com.google.cloud.recommender.v1.RecommenderConfig.getDefaultInstance()
: recommenderConfig_;
}
/**
*
*
* <pre>
* Required. The RecommenderConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.RecommenderConfig recommender_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.recommender.v1.RecommenderConfigOrBuilder
getRecommenderConfigOrBuilder() {
return recommenderConfig_ == null
? com.google.cloud.recommender.v1.RecommenderConfig.getDefaultInstance()
: recommenderConfig_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
public static final int VALIDATE_ONLY_FIELD_NUMBER = 3;
private boolean validateOnly_ = false;
/**
*
*
* <pre>
* If true, validate the request and preview the change, but do not actually
* update it.
* </pre>
*
* <code>bool validate_only = 3;</code>
*
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getRecommenderConfig());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getUpdateMask());
}
if (validateOnly_ != false) {
output.writeBool(3, validateOnly_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getRecommenderConfig());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask());
}
if (validateOnly_ != false) {
size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, validateOnly_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest)) {
return super.equals(obj);
}
com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest other =
(com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest) obj;
if (hasRecommenderConfig() != other.hasRecommenderConfig()) return false;
if (hasRecommenderConfig()) {
if (!getRecommenderConfig().equals(other.getRecommenderConfig())) return false;
}
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask().equals(other.getUpdateMask())) return false;
}
if (getValidateOnly() != other.getValidateOnly()) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasRecommenderConfig()) {
hash = (37 * hash) + RECOMMENDER_CONFIG_FIELD_NUMBER;
hash = (53 * hash) + getRecommenderConfig().hashCode();
}
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getValidateOnly());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest 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.recommender.v1.UpdateRecommenderConfigRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest 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.recommender.v1.UpdateRecommenderConfigRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest 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.recommender.v1.UpdateRecommenderConfigRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest 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.recommender.v1.UpdateRecommenderConfigRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest 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.recommender.v1.UpdateRecommenderConfigRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request for the `UpdateRecommenderConfig` method.
* </pre>
*
* Protobuf type {@code google.cloud.recommender.v1.UpdateRecommenderConfigRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.recommender.v1.UpdateRecommenderConfigRequest)
com.google.cloud.recommender.v1.UpdateRecommenderConfigRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.recommender.v1.RecommenderProto
.internal_static_google_cloud_recommender_v1_UpdateRecommenderConfigRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.recommender.v1.RecommenderProto
.internal_static_google_cloud_recommender_v1_UpdateRecommenderConfigRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest.class,
com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest.Builder.class);
}
// Construct using com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getRecommenderConfigFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
recommenderConfig_ = null;
if (recommenderConfigBuilder_ != null) {
recommenderConfigBuilder_.dispose();
recommenderConfigBuilder_ = null;
}
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
validateOnly_ = false;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.recommender.v1.RecommenderProto
.internal_static_google_cloud_recommender_v1_UpdateRecommenderConfigRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest
getDefaultInstanceForType() {
return com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest build() {
com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest buildPartial() {
com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest result =
new com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.recommenderConfig_ =
recommenderConfigBuilder_ == null
? recommenderConfig_
: recommenderConfigBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build();
to_bitField0_ |= 0x00000002;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.validateOnly_ = validateOnly_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest) {
return mergeFrom((com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest other) {
if (other
== com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest.getDefaultInstance())
return this;
if (other.hasRecommenderConfig()) {
mergeRecommenderConfig(other.getRecommenderConfig());
}
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
if (other.getValidateOnly() != false) {
setValidateOnly(other.getValidateOnly());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(
getRecommenderConfigFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 24:
{
validateOnly_ = input.readBool();
bitField0_ |= 0x00000004;
break;
} // case 24
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.cloud.recommender.v1.RecommenderConfig recommenderConfig_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.recommender.v1.RecommenderConfig,
com.google.cloud.recommender.v1.RecommenderConfig.Builder,
com.google.cloud.recommender.v1.RecommenderConfigOrBuilder>
recommenderConfigBuilder_;
/**
*
*
* <pre>
* Required. The RecommenderConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.RecommenderConfig recommender_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the recommenderConfig field is set.
*/
public boolean hasRecommenderConfig() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The RecommenderConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.RecommenderConfig recommender_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The recommenderConfig.
*/
public com.google.cloud.recommender.v1.RecommenderConfig getRecommenderConfig() {
if (recommenderConfigBuilder_ == null) {
return recommenderConfig_ == null
? com.google.cloud.recommender.v1.RecommenderConfig.getDefaultInstance()
: recommenderConfig_;
} else {
return recommenderConfigBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The RecommenderConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.RecommenderConfig recommender_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setRecommenderConfig(com.google.cloud.recommender.v1.RecommenderConfig value) {
if (recommenderConfigBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
recommenderConfig_ = value;
} else {
recommenderConfigBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The RecommenderConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.RecommenderConfig recommender_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setRecommenderConfig(
com.google.cloud.recommender.v1.RecommenderConfig.Builder builderForValue) {
if (recommenderConfigBuilder_ == null) {
recommenderConfig_ = builderForValue.build();
} else {
recommenderConfigBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The RecommenderConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.RecommenderConfig recommender_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeRecommenderConfig(com.google.cloud.recommender.v1.RecommenderConfig value) {
if (recommenderConfigBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& recommenderConfig_ != null
&& recommenderConfig_
!= com.google.cloud.recommender.v1.RecommenderConfig.getDefaultInstance()) {
getRecommenderConfigBuilder().mergeFrom(value);
} else {
recommenderConfig_ = value;
}
} else {
recommenderConfigBuilder_.mergeFrom(value);
}
if (recommenderConfig_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The RecommenderConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.RecommenderConfig recommender_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearRecommenderConfig() {
bitField0_ = (bitField0_ & ~0x00000001);
recommenderConfig_ = null;
if (recommenderConfigBuilder_ != null) {
recommenderConfigBuilder_.dispose();
recommenderConfigBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The RecommenderConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.RecommenderConfig recommender_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.recommender.v1.RecommenderConfig.Builder getRecommenderConfigBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getRecommenderConfigFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The RecommenderConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.RecommenderConfig recommender_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.recommender.v1.RecommenderConfigOrBuilder
getRecommenderConfigOrBuilder() {
if (recommenderConfigBuilder_ != null) {
return recommenderConfigBuilder_.getMessageOrBuilder();
} else {
return recommenderConfig_ == null
? com.google.cloud.recommender.v1.RecommenderConfig.getDefaultInstance()
: recommenderConfig_;
}
}
/**
*
*
* <pre>
* Required. The RecommenderConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.RecommenderConfig recommender_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.recommender.v1.RecommenderConfig,
com.google.cloud.recommender.v1.RecommenderConfig.Builder,
com.google.cloud.recommender.v1.RecommenderConfigOrBuilder>
getRecommenderConfigFieldBuilder() {
if (recommenderConfigBuilder_ == null) {
recommenderConfigBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.recommender.v1.RecommenderConfig,
com.google.cloud.recommender.v1.RecommenderConfig.Builder,
com.google.cloud.recommender.v1.RecommenderConfigOrBuilder>(
getRecommenderConfig(), getParentForChildren(), isClean());
recommenderConfig_ = null;
}
return recommenderConfigBuilder_;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
updateMaskBuilder_;
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
} else {
updateMaskBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& updateMask_ != null
&& updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) {
getUpdateMaskBuilder().mergeFrom(value);
} else {
updateMask_ = value;
}
} else {
updateMaskBuilder_.mergeFrom(value);
}
if (updateMask_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000002);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
private boolean validateOnly_;
/**
*
*
* <pre>
* If true, validate the request and preview the change, but do not actually
* update it.
* </pre>
*
* <code>bool validate_only = 3;</code>
*
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
/**
*
*
* <pre>
* If true, validate the request and preview the change, but do not actually
* update it.
* </pre>
*
* <code>bool validate_only = 3;</code>
*
* @param value The validateOnly to set.
* @return This builder for chaining.
*/
public Builder setValidateOnly(boolean value) {
validateOnly_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* If true, validate the request and preview the change, but do not actually
* update it.
* </pre>
*
* <code>bool validate_only = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearValidateOnly() {
bitField0_ = (bitField0_ & ~0x00000004);
validateOnly_ = false;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.recommender.v1.UpdateRecommenderConfigRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.UpdateRecommenderConfigRequest)
private static final com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest();
}
public static com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateRecommenderConfigRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateRecommenderConfigRequest>() {
@java.lang.Override
public UpdateRecommenderConfigRequest 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<UpdateRecommenderConfigRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateRecommenderConfigRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.recommender.v1.UpdateRecommenderConfigRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/ofbiz-framework | 36,130 | framework/entity/src/main/java/org/apache/ofbiz/entity/test/EntityQueryTestSuite.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.entity.test;
import java.sql.Timestamp;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.ofbiz.base.util.UtilDateTime;
import org.apache.ofbiz.base.util.UtilMisc;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.GenericEntityException;
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.testtools.EntityTestCase;
import org.apache.ofbiz.entity.transaction.TransactionUtil;
import org.apache.ofbiz.entity.util.EntityFindOptions;
import org.apache.ofbiz.entity.util.EntityListIterator;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.entity.util.EntityUtil;
public class EntityQueryTestSuite extends EntityTestCase {
public EntityQueryTestSuite(String name) {
super(name);
}
/**
* queryCount(): This method returns number of records found for the particular query.
* assert: Compared count of number of records found by Entity Engine method with count of number of records found by EntityQuery method.
*/
public void testQueryCount() throws GenericEntityException {
Delegator delegator = getDelegator();
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "record-1", "description", "Record One"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "record-2", "description", "Record Two"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "record-3", "description", "Record Three"));
delegator.storeAll(testingTypes);
List<GenericValue> totalRecordsByEntityEngine = delegator.findList("TestingType", null, null, null, null, false);
int numberOfRecordsByEntityQuery = (int) EntityQuery.use(delegator).from("TestingType").queryCount();
assertEquals("queryCount(): Total Number of Records matched", totalRecordsByEntityEngine.size(), numberOfRecordsByEntityQuery);
}
/**
* where(): This method is used for setting condition of which records to fetch from entity.
* assert 1: Compared size of the list returned by Entity Engine method and by EntityQuery method.
* assert 2: Compared 'testingTypeId' field of first record fetched by Entity Engine method and by EntityQuery method.
* assert 3: Compared 'description' field of first record fetched by Entity Engine method and by EntityQuery method.
*/
public void testWhere() throws GenericEntityException {
Delegator delegator = getDelegator();
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "where-1", "description", "find me"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "where-2", "description", "find me not"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "where-3", "description", "find me"));
delegator.storeAll(testingTypes);
List<GenericValue> listByEntityEngine = delegator.findList("TestingType", EntityCondition.makeCondition("description",
EntityOperator.EQUALS, "find me"), null, UtilMisc.toList("description"), null, false);
List<GenericValue> listByEntityQuery = EntityQuery.use(delegator).from("TestingType").where("description", "find me")
.orderBy("description").queryList();
assertEquals("where(): Number of records fetched by Entity Engine and by EntityQuery matched", listByEntityEngine.size(),
listByEntityQuery.size());
assertEquals("where(): Record matched = testingTypeId", listByEntityEngine.get(0).getString("testingTypeId"),
listByEntityQuery.get(0).getString("testingTypeId"));
assertEquals("where(): Record matched = description", listByEntityEngine.get(0).getString("description"),
listByEntityQuery.get(0).getString("description"));
}
/**
* queryList(): Returns all records from the given entity.
* assert 1: Compared size of the list returned by Entity Engine method and by EntityQuery method.
* assert 2: Compared 'testingTypeId' field of first record fetched by Entity Engine method and by EntityQuery method.
* assert 3: Compared 'description' field of first record fetched by Entity Engine method and by EntityQuery method.
*/
public void testQueryList() throws GenericEntityException {
Delegator delegator = getDelegator();
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "queryList-1", "description", "queryList record one"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "queryList-2", "description", "queryList record two"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "queryList-3", "description", "queryList record three"));
delegator.storeAll(testingTypes);
List<GenericValue> listByEntityEngine = delegator.findList("TestingType", null, null, UtilMisc.toList("description"), null, false);
List<GenericValue> listByEntityQuery = EntityQuery.use(delegator).from("TestingType").orderBy("description").queryList();
assertEquals("queryList(): Number of records fetched by Entity Engine and by EntityQuery matched", listByEntityEngine.size(),
listByEntityQuery.size());
assertEquals("queryList(): Record matched = testingTypeId", listByEntityEngine.get(0).getString("testingTypeId"),
listByEntityQuery.get(0).getString("testingTypeId"));
assertEquals("queryList(): Record matched = description", listByEntityEngine.get(0).getString("description"),
listByEntityQuery.get(0).getString("description"));
}
/**
* queryFirst(): Returns first record from result of query.
* assert 1: Compared 'testingTypeId' field of record fetched by Entity Engine method and by EntityQuery method.
* assert 2: Compared 'description' field of first record fetched by Entity Engine method and by EntityQuery method.
*/
public void testQueryFirst() throws GenericEntityException {
Delegator delegator = getDelegator();
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "queryFirst-1", "description", "first record"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "queryFirst-2", "description", "second record"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "queryFirst-3", "description", "third record"));
delegator.storeAll(testingTypes);
GenericValue firstRecordByEntityEngine = EntityUtil.getFirst(delegator.findList("TestingType", null, null, null, null, false));
GenericValue firstRecordByEntityQuery = EntityQuery.use(delegator).from("TestingType").queryFirst();
assertEquals("queryFirst(): Record matched = testingTypeId", firstRecordByEntityEngine.getString("testingTypeId"),
firstRecordByEntityQuery.getString("testingTypeId"));
assertEquals("queryFirst(): Record matched = description", firstRecordByEntityEngine.getString("description"),
firstRecordByEntityQuery.getString("description"));
}
/**
* queryOne(): This method returns only one record based on the conditions given.
* assert 1: Compared 'testingTypeId' field of record fetched by Entity Engine method and by EntityQuery method.
* assert 2: Compared 'description' field of first record fetched by Entity Engine method and by EntityQuery method.
*/
public void testQueryOne() throws GenericEntityException {
Delegator delegator = getDelegator();
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "queryOne-1", "description", "query one"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "queryOne-2", "description", "query two"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "queryOne-3", "description", "query three"));
delegator.storeAll(testingTypes);
GenericValue findOneByEntityEngine = EntityQuery.use(delegator).from("TestingType").where("testingTypeId", "queryOne-2").queryOne();
GenericValue queryOneByEntityQuery = EntityQuery.use(delegator).from("TestingType").where("testingTypeId", "queryOne-2").queryOne();
assertEquals("queryOne(): Record matched = testingTypeId", findOneByEntityEngine.getString("testingTypeId"),
queryOneByEntityQuery.getString("testingTypeId"));
assertEquals("queryOne(): Record matched = description", findOneByEntityEngine.getString("description"),
queryOneByEntityQuery.getString("description"));
}
/**
* queryOne(): This method returns only one record based on the conditions given, resolve from a context Map.
* assert 1: Check the TestingType entity queryOneMap-2 has been resolve
* assert 2: Check the TestingType entity queryOneMap-3 has been resolve with the parameters map present in context
*/
public void testQueryOneWithContext() throws GenericEntityException {
Delegator delegator = getDelegator();
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "queryOneMap-1", "description", "query one by map"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "queryOneMap-2", "description", "query two by map"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "queryOneMap-3", "description", "query three by map"));
delegator.storeAll(testingTypes);
Map<String, Object> context = UtilMisc.toMap("testingTypeId", "queryOneMap-2", "description", "query two by map", "otherField", "otherValue");
GenericValue queryOneByEntityQueryAndContext = EntityQuery.use(delegator).from("TestingType").where(context).queryOne();
assertNotNull("queryOne() with context: Record found", queryOneByEntityQueryAndContext);
context = UtilMisc.toMap("description", "query two by map", "otherField", "otherValue",
"parameters", UtilMisc.toMap("testingTypeId", "queryOneMap-3", "description", "query three by map", "otherField", "otherValue"));
GenericValue queryOneByEntityQueryAndParameters = EntityQuery.use(delegator).from("TestingType").where(context).queryOne();
assertNotNull("queryOne() with parameters: Record found", queryOneByEntityQueryAndParameters);
assertEquals("queryOne() with parameters: Record is queryOneMap-3 ", "queryOneMap-3",
queryOneByEntityQueryAndParameters.getString("testingTypeId"));
}
/**
* select(): This method is used to select particular fields only from the entity.
* assert 1: Compared value of first record of selected 'description' field by both EntityEngine method and EntityQuery method.
* assert 2: Compared 'testingTypeId' field for null which is fetched by EntityQuery method.
*/
public void testSelect() throws GenericEntityException {
Delegator delegator = getDelegator();
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "select-1", "description", "description one"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "select-2", "description", "description two"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "select-3", "description", "description three"));
delegator.storeAll(testingTypes);
List<GenericValue> selectByEntityEngine = delegator.findList("TestingType", null, UtilMisc.toSet("description"),
UtilMisc.toList("description"), null, false);
List<GenericValue> selectByEntityQuery = EntityQuery.use(delegator).select("description").from("TestingType")
.orderBy("description").queryList();
assertEquals("select(): Record matched = description", selectByEntityEngine.get(0).getString("description"),
selectByEntityQuery.get(0).getString("description"));
assertNull(selectByEntityQuery.get(0).getString("testingTypeId"));
}
/**
* distinct(): This method is used to get distinct values of records from entity field.
* (Note: Distinct method is generally used with select method)
* assert 1: Compared size of the list returned by Entity Engine method and by EntityQuery method.
* assert 2: Compared value of first record of selected 'description' field by both EntityEngine method and EntityQuery method.
* assert 3: Compared 'testingTypeId' field for null which is fetched by EntityQuery method.
*/
public void testDistinctAndSelect() throws GenericEntityException {
Delegator delegator = getDelegator();
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "distinct-1", "description", "Distinct Record"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "distinct-2", "description", "Distinct Record"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "distinct-3", "description", "Not a Distinct Record"));
delegator.storeAll(testingTypes);
EntityFindOptions findOptions = new EntityFindOptions();
findOptions.setDistinct(true);
List<GenericValue> distinctByEntityEngine = delegator.findList("TestingType", null, UtilMisc.toSet("description"),
UtilMisc.toList("description"), findOptions, false);
List<GenericValue> distinctByEntityQuery = EntityQuery.use(delegator).select("description").from("TestingType")
.distinct().orderBy("description").queryList();
assertEquals("distinct(): Number of records found by EntityEngine method are matching with records found by EntityQuery distinct method",
distinctByEntityEngine.size(), distinctByEntityQuery.size());
assertEquals("distinct(): Record matched = description", distinctByEntityEngine.get(0).getString("description"),
distinctByEntityQuery.get(0).getString("description"));
assertNull(distinctByEntityQuery.get(0).getString("testingTypeId"));
}
/**
* orderBy(): This method sorts the records found according to the given field or combination of fields.
* assert 1: Compared number of records returned by Entity Engine method and by EntityQuery method.
* assert 2: Compared 'testingTypeId' field of first record fetched by Entity Engine method and by EntityQuery method.
* assert 3: Compared 'description' field of first record fetched by Entity Engine method and by EntityQuery method.
*/
public void testOrderBy() throws GenericEntityException {
Delegator delegator = getDelegator();
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "orderBy-1", "description", "B"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "orderBy-2", "description", "C"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "orderBy-3", "description", "A"));
delegator.storeAll(testingTypes);
List<GenericValue> orderedByEntityEngine = delegator.findList("TestingType", EntityCondition.makeCondition("testingTypeId",
EntityOperator.LIKE, "orderBy-%"), null, UtilMisc.toList("description"), null, false);
List<GenericValue> orderedByEntityQuery = EntityQuery.use(delegator).from("TestingType").where(EntityCondition.makeCondition("testingTypeId",
EntityOperator.LIKE, "orderBy-%")).orderBy("description").queryList();
assertEquals("orderBy(): Number of records found by both the methods matched", orderedByEntityEngine.size(), orderedByEntityQuery.size());
assertEquals("orderBy(): Record matched = testingTypeId", orderedByEntityEngine.get(0).getString("testingTypeId"),
orderedByEntityQuery.get(0).getString("testingTypeId"));
assertEquals("orderBy(): Record matched = description", orderedByEntityEngine.get(0).getString("description"),
orderedByEntityQuery.get(0).getString("description"));
}
/**
* filteByDate(): This method return only values that are currently active using from/thruDate fields.
* assert 1: Compared number of records returned by Entity Engine method and by EntityQuery method.
* assert 2: Compared 'testingNodeId' field of first record fetched by Entity Engine method and by EntityQuery method.
* assert 3: Compared 'testingId' field of first record fetched by Entity Engine method and by EntityQuery method.
* assert 4: Compared 'fromDate' field of first record fetched by Entity Engine method and by EntityQuery method.
* assert 5: Compared 'thruDate' field of first record fetched by Entity Engine method and by EntityQuery method.
*/
public void testFilterByDate() throws GenericEntityException {
Delegator delegator = getDelegator();
delegator.create("TestingType", "testingTypeId", "filterByDate-1", "description", "Filter BY Date");
delegator.create("Testing", "testingId", "testing-1", "testingTypeId", "filterByDate-1");
delegator.create("Testing", "testingId", "testing-2", "testingTypeId", "filterByDate-1");
delegator.create("Testing", "testingId", "testing-3", "testingTypeId", "filterByDate-1");
delegator.create("Testing", "testingId", "testing-4", "testingTypeId", "filterByDate-1");
delegator.create("TestingNode", "testingNodeId", "testingNode-1");
delegator.create("TestingNode", "testingNodeId", "testingNode-2");
delegator.create("TestingNode", "testingNodeId", "testingNode-3");
delegator.create("TestingNode", "testingNodeId", "testingNode-4");
delegator.create("TestingNodeMember", "testingNodeId", "testingNode-1", "testingId", "testing-1", "fromDate",
UtilDateTime.nowTimestamp(), "thruDate", UtilDateTime.getNextDayStart(UtilDateTime.nowTimestamp()));
delegator.create("TestingNodeMember", "testingNodeId", "testingNode-2", "testingId", "testing-2", "fromDate",
UtilDateTime.nowTimestamp(), "thruDate", UtilDateTime.getNextDayStart(UtilDateTime.nowTimestamp()));
delegator.create("TestingNodeMember", "testingNodeId", "testingNode-3", "testingId", "testing-3", "fromDate",
UtilDateTime.getNextDayStart(UtilDateTime.nowTimestamp()), "thruDate", UtilDateTime.getWeekEnd(UtilDateTime.nowTimestamp()));
delegator.create("TestingNodeMember", "testingNodeId", "testingNode-4", "testingId", "testing-4", "fromDate",
UtilDateTime.getMonthStart(UtilDateTime.nowTimestamp()), "thruDate", UtilDateTime.getMonthStart(UtilDateTime.nowTimestamp()));
List<GenericValue> filteredByEntityUtil = EntityUtil.filterByDate(delegator.findList("TestingNodeMember", null, null,
UtilMisc.toList("testingNodeId"), null, false));
List<GenericValue> filteredByEntityQuery = EntityQuery.use(delegator).from("TestingNodeMember").filterByDate()
.orderBy("testingNodeId").queryList();
assertEquals("filterByDate(): Number of records found by both the methods matched", filteredByEntityUtil.size(),
filteredByEntityQuery.size());
assertEquals("filterByDate(): Record matched = testingNodeId", filteredByEntityUtil.get(0).getString("testingNodeId"),
filteredByEntityQuery.get(0).getString("testingNodeId"));
assertEquals("filterByDate(): Record matched = testingId", filteredByEntityUtil.get(0).getString("testingId"),
filteredByEntityQuery.get(0).getString("testingId"));
assertEquals("filterByDate(): Record matched = fromDate", filteredByEntityUtil.get(0).getString("fromDate"),
filteredByEntityQuery.get(0).getString("fromDate"));
assertEquals("filterByDate(): Record matched = thruDate", filteredByEntityUtil.get(0).getString("thruDate"),
filteredByEntityQuery.get(0).getString("thruDate"));
}
/**
* maxRows(): This method sets the maximum number of records to be fetched by the query.
* assert 1: Compared number of records returned by Entity Engine method and by EntityQuery method.
* assert 2: Compared 'testingTypeId' field of first record fetched by Entity Engine method and by EntityQuery method.
* assert 3: Compared 'description' field of first record fetched by Entity Engine method and by EntityQuery method.
*/
public void testMaxRows() throws GenericEntityException {
Delegator delegator = getDelegator();
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "maxRows-1", "description", "Max Row One"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "maxRows-2", "description", "Max Row Two"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "maxRows-3", "description", "Max Row Three"));
delegator.storeAll(testingTypes);
EntityFindOptions findOptions = new EntityFindOptions();
findOptions.setMaxRows(2);
List<GenericValue> maxRowsByEntityEngine = delegator.findList("TestingType", null, null, UtilMisc.toList("description"), findOptions, false);
List<GenericValue> maxRowsByEntityQuery = EntityQuery.use(delegator).from("TestingType").maxRows(2).orderBy("description").queryList();
assertEquals("maxRows(): Number of records found by both the methods matched", maxRowsByEntityEngine.size(), maxRowsByEntityQuery.size());
assertEquals("maxRows(): Record matched = testingTypeId", maxRowsByEntityEngine.get(0).getString("testingTypeId"),
maxRowsByEntityQuery.get(0).getString("testingTypeId"));
assertEquals("maxRows(): Record matched = description", maxRowsByEntityEngine.get(0).getString("description"),
maxRowsByEntityQuery.get(0).getString("description"));
}
/**
* fetchSize(): This method sets the fetch size for the records to be fetched from the entity.
* assert 1: Compared number of records returned by Entity Engine method and by EntityQuery method.
* assert 2: Compared 'testingTypeId' field of first record fetched by Entity Engine method and by EntityQuery method.
* assert 3: Compared 'description' field of first record fetched by Entity Engine method and by EntityQuery method.
*/
public void testFetchSize() throws GenericEntityException {
Delegator delegator = getDelegator();
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "fetchSize-1", "description", "Fetch Size One"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "fetchSize-2", "description", "Fetch Size Two"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "fetchSize-3", "description", "Fetch Size Three"));
delegator.storeAll(testingTypes);
EntityFindOptions findOptions = new EntityFindOptions();
findOptions.setFetchSize(2);
List<GenericValue> fetchSizeByEntityEngine = delegator.findList("TestingType", null, null,
UtilMisc.toList("description"), findOptions, false);
List<GenericValue> fetchSizeByEntityQuery = EntityQuery.use(delegator).from("TestingType").fetchSize(2).orderBy("description").queryList();
assertEquals("fetchSize(): Number of records found by both the methods matched", fetchSizeByEntityEngine.size(),
fetchSizeByEntityQuery.size());
assertEquals("fetchSize(): Record matched = testingTypeId", fetchSizeByEntityEngine.get(0).getString("testingTypeId"),
fetchSizeByEntityQuery.get(0).getString("testingTypeId"));
assertEquals("fetchSize(): Record matched = description", fetchSizeByEntityEngine.get(0).getString("description"),
fetchSizeByEntityQuery.get(0).getString("description"));
}
/**
* queryIterator(): This method is used to get iterator object over the entity.
* assert: Compared first record of both the iterator.
*/
public void testQueryIterator() throws GenericEntityException {
Delegator delegator = getDelegator();
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "queryIterator-1", "description", "Value One"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "queryIterator-2", "description", "Value Two"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "queryIterator-3", "description", "Value Three"));
delegator.storeAll(testingTypes);
boolean transactionStarted = false;
try {
transactionStarted = TransactionUtil.begin();
EntityListIterator eliByEntityEngine = null;
EntityListIterator eliByEntityQuery = null;
eliByEntityEngine = delegator.find("TestingType", null, null, null, null, null);
eliByEntityQuery = EntityQuery.use(delegator).from("TestingType").queryIterator();
GenericValue recordByEntityEngine = eliByEntityEngine.next();
GenericValue recordByEntityQuery = eliByEntityQuery.next();
assertEquals("queryIterator(): Value of first record pointed by both iterators matched", recordByEntityEngine, recordByEntityQuery);
eliByEntityEngine.close();
eliByEntityQuery.close();
TransactionUtil.commit(transactionStarted);
} catch (GenericEntityException e) {
TransactionUtil.rollback(transactionStarted, "Transaction is Rolled Back", e);
}
}
/**
* cursorForwardOnly(): Indicate that the ResultSet object's cursor may move only forward
* assert: Compared first record found by both the iterator.
*/
public void testCursorForwardOnly() throws GenericEntityException {
Delegator delegator = getDelegator();
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "cursorForwardOnly-1", "description", "cursorForwardOnly One"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "cursorForwardOnly-2", "description", "cursorForwardOnly Two"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "cursorForwardOnly-3", "description", "cursorForwardOnly Three"));
delegator.storeAll(testingTypes);
boolean transactionStarted = false;
try {
transactionStarted = TransactionUtil.begin();
EntityListIterator eliByEntityEngine = null;
EntityListIterator eliByEntityQuery = null;
EntityFindOptions findOptions = new EntityFindOptions();
findOptions.setResultSetType(EntityFindOptions.TYPE_FORWARD_ONLY);
eliByEntityEngine = delegator.find("TestingType", null, null, null, null, findOptions);
eliByEntityQuery = EntityQuery.use(delegator).from("TestingType").cursorForwardOnly().queryIterator();
GenericValue nextRecordByEntityEngine = eliByEntityEngine.next();
GenericValue nextRecordByEntityQuery = eliByEntityQuery.next();
assertEquals("cursorForwardOnly(): Value of first record pointed by both iterators matched", nextRecordByEntityEngine,
nextRecordByEntityQuery);
eliByEntityEngine.close();
eliByEntityQuery.close();
TransactionUtil.commit(transactionStarted);
} catch (GenericEntityException e) {
TransactionUtil.rollback(transactionStarted, "Transaction is Rolled Back", e);
}
}
/**
* cursorScrollSensitive(): ResultSet object's cursor is scrollable but generally sensitive to changes to the data that underlies the ResultSet.
* assert: Compared first record found by both the iterators.
*/
public void testCursorScrollSensitive() throws GenericEntityException {
Delegator delegator = getDelegator();
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "scrollSensitive-1", "description", "cursorScrollSensitive One"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "scrollSensitive-2", "description", "cursorScrollSensitive Two"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "scrollSensitive-3", "description", "cursorScrollSensitive Three"));
delegator.storeAll(testingTypes);
boolean transactionStarted = false;
try {
transactionStarted = TransactionUtil.begin();
EntityListIterator eliByEntityEngine = null;
EntityListIterator eliByEntityQuery = null;
EntityFindOptions findOptions = new EntityFindOptions();
findOptions.setResultSetType(EntityFindOptions.TYPE_SCROLL_SENSITIVE);
eliByEntityEngine = delegator.find("TestingType", null, null, null, null, findOptions);
eliByEntityQuery = EntityQuery.use(delegator).from("TestingType").cursorScrollSensitive().queryIterator();
GenericValue nextRecordByDelegator = eliByEntityEngine.next();
GenericValue nextRecordByEntityQuery = eliByEntityQuery.next();
assertEquals("cursorScrollSensitive(): Records by delegator method and by EntityQuery method matched", nextRecordByDelegator,
nextRecordByEntityQuery);
eliByEntityEngine.close();
eliByEntityQuery.close();
TransactionUtil.commit(transactionStarted);
} catch (GenericEntityException e) {
TransactionUtil.rollback(transactionStarted, "Transaction is Rolled Back", e);
}
}
/**
* testCache(): When cache() is activated, the result of a query is set to cache for a given condition.
* assert: Ensure that a request with a select or a date filter stored in cache is not retrieved by a query
* without select nor date filter having the same condition.
*/
public void testCache() throws GenericEntityException {
Timestamp now = UtilDateTime.nowTimestamp();
Delegator delegator = getDelegator();
delegator.create("TestingType", "testingTypeId", "cacheWithSelect", "description", "cache with selection One");
delegator.create("TestingType", "testingTypeId", "cacheWithDate", "description", "cache with filterByDate One");
delegator.create("TestingNode", "testingNodeId", "testingCacheNode1");
delegator.create("TestingNode", "testingNodeId", "testingCacheNode2");
delegator.create("Testing", "testingId", "testingCache1", "testingTypeId", "cacheWithDate");
delegator.create("TestingNodeMember", "testingNodeId", "testingCacheNode1", "testingId", "testingCache1", "fromDate",
now, "thruDate", UtilDateTime.getNextDayStart(now));
delegator.create("TestingNodeMember", "testingNodeId", "testingCacheNode2", "testingId", "testingCache1", "fromDate",
now, "thruDate", now);
List<GenericValue> cachedResultWithFilterByDate = EntityQuery.use(delegator).from("TestingNodeMember").filterByDate()
.where("testingId", "testingCache1").cache().queryList();
assertEquals("testCache(): Number of records found match", 1, cachedResultWithFilterByDate.size());
List<GenericValue> cachedResultWithoutFilterByDate = EntityQuery.use(delegator).from("TestingNodeMember")
.where("testingId", "testingCache1").queryList();
assertEquals("testCache(): Number of records found match", 2, cachedResultWithoutFilterByDate.size());
GenericValue firstCachedResultWithSelect = EntityQuery.use(delegator).select("testingTypeId").from("TestingType").cache().queryFirst();
assertFalse(firstCachedResultWithSelect.containsKey("description"));
GenericValue secondCachedResultWithSelect = EntityQuery.use(delegator).from("TestingType").cache().queryFirst();
assertTrue(secondCachedResultWithSelect.containsKey("description"));
}
/**
* cursorScrollInSensitive(): ResultSet object's cursor is scrollable but generally not sensitive to changes to the data that
* underlies the ResultSet.
* assert: Compared first record found by both the iterators.
*/
public void testCursorScrollInSensitive() throws GenericEntityException {
Delegator delegator = getDelegator();
List<GenericValue> testingTypes = new LinkedList<>();
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "scrollInSensitive-1", "description", "cursorScrollInSensitive One"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "scrollInSensitive-2", "description", "cursorScrollInSensitive Two"));
testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "scrollInSensitive-3", "description", "cursorScrollInSensitive Three"));
delegator.storeAll(testingTypes);
boolean transactionStarted = false;
try {
transactionStarted = TransactionUtil.begin();
EntityListIterator eliByEntityEngine = null;
EntityListIterator eliByEntityQuery = null;
EntityFindOptions findOptions = new EntityFindOptions();
findOptions.setResultSetType(EntityFindOptions.TYPE_SCROLL_INSENSITIVE);
eliByEntityEngine = delegator.find("TestingType", null, null, null, null, findOptions);
eliByEntityQuery = EntityQuery.use(delegator).from("TestingType").cursorScrollInsensitive().queryIterator();
GenericValue nextRecordByDelegator = eliByEntityEngine.next();
GenericValue nextRecordByEntityQuery = eliByEntityQuery.next();
assertEquals("cursorScrollInSensitive(): Records by delegator method and by EntityQuery method matched",
nextRecordByDelegator, nextRecordByEntityQuery);
eliByEntityEngine.close();
eliByEntityQuery.close();
TransactionUtil.commit(transactionStarted);
} catch (GenericEntityException e) {
TransactionUtil.rollback(transactionStarted, "Transaction is Rolled Back", e);
}
}
}
|
googleads/google-ads-java | 36,605 | google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/resources/CampaignSearchTermInsight.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v21/resources/campaign_search_term_insight.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v21.resources;
/**
* <pre>
* This report provides a high-level view of search demand at the campaign
* level by grouping similar search terms into categories and showing their
* search volume.
* Historical data is available starting March 2023.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.resources.CampaignSearchTermInsight}
*/
public final class CampaignSearchTermInsight extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v21.resources.CampaignSearchTermInsight)
CampaignSearchTermInsightOrBuilder {
private static final long serialVersionUID = 0L;
// Use CampaignSearchTermInsight.newBuilder() to construct.
private CampaignSearchTermInsight(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CampaignSearchTermInsight() {
resourceName_ = "";
categoryLabel_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new CampaignSearchTermInsight();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.resources.CampaignSearchTermInsightProto.internal_static_google_ads_googleads_v21_resources_CampaignSearchTermInsight_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.resources.CampaignSearchTermInsightProto.internal_static_google_ads_googleads_v21_resources_CampaignSearchTermInsight_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.resources.CampaignSearchTermInsight.class, com.google.ads.googleads.v21.resources.CampaignSearchTermInsight.Builder.class);
}
private int bitField0_;
public static final int RESOURCE_NAME_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object resourceName_ = "";
/**
* <pre>
* Output only. The resource name of the campaign level search term insight.
* Campaign level search term insight resource names have the form:
*
* `customers/{customer_id}/campaignSearchTermInsights/{campaign_id}~{category_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code>
* @return The resourceName.
*/
@java.lang.Override
public java.lang.String getResourceName() {
java.lang.Object ref = resourceName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resourceName_ = s;
return s;
}
}
/**
* <pre>
* Output only. The resource name of the campaign level search term insight.
* Campaign level search term insight resource names have the form:
*
* `customers/{customer_id}/campaignSearchTermInsights/{campaign_id}~{category_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for resourceName.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getResourceNameBytes() {
java.lang.Object ref = resourceName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
resourceName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CATEGORY_LABEL_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object categoryLabel_ = "";
/**
* <pre>
* Output only. The label for the search category. An empty string denotes the
* catch-all category for search terms that didn't fit into another category.
* </pre>
*
* <code>optional string category_label = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return Whether the categoryLabel field is set.
*/
@java.lang.Override
public boolean hasCategoryLabel() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* Output only. The label for the search category. An empty string denotes the
* catch-all category for search terms that didn't fit into another category.
* </pre>
*
* <code>optional string category_label = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The categoryLabel.
*/
@java.lang.Override
public java.lang.String getCategoryLabel() {
java.lang.Object ref = categoryLabel_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
categoryLabel_ = s;
return s;
}
}
/**
* <pre>
* Output only. The label for the search category. An empty string denotes the
* catch-all category for search terms that didn't fit into another category.
* </pre>
*
* <code>optional string category_label = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The bytes for categoryLabel.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getCategoryLabelBytes() {
java.lang.Object ref = categoryLabel_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
categoryLabel_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ID_FIELD_NUMBER = 3;
private long id_ = 0L;
/**
* <pre>
* Output only. The ID of the insight.
* </pre>
*
* <code>optional int64 id = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return Whether the id field is set.
*/
@java.lang.Override
public boolean hasId() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* Output only. The ID of the insight.
* </pre>
*
* <code>optional int64 id = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The id.
*/
@java.lang.Override
public long getId() {
return id_;
}
public static final int CAMPAIGN_ID_FIELD_NUMBER = 4;
private long campaignId_ = 0L;
/**
* <pre>
* Output only. The ID of the campaign.
* </pre>
*
* <code>optional int64 campaign_id = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return Whether the campaignId field is set.
*/
@java.lang.Override
public boolean hasCampaignId() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
* <pre>
* Output only. The ID of the campaign.
* </pre>
*
* <code>optional int64 campaign_id = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The campaignId.
*/
@java.lang.Override
public long getCampaignId() {
return campaignId_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_);
}
if (((bitField0_ & 0x00000001) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, categoryLabel_);
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeInt64(3, id_);
}
if (((bitField0_ & 0x00000004) != 0)) {
output.writeInt64(4, campaignId_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, categoryLabel_);
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(3, id_);
}
if (((bitField0_ & 0x00000004) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(4, campaignId_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v21.resources.CampaignSearchTermInsight)) {
return super.equals(obj);
}
com.google.ads.googleads.v21.resources.CampaignSearchTermInsight other = (com.google.ads.googleads.v21.resources.CampaignSearchTermInsight) obj;
if (!getResourceName()
.equals(other.getResourceName())) return false;
if (hasCategoryLabel() != other.hasCategoryLabel()) return false;
if (hasCategoryLabel()) {
if (!getCategoryLabel()
.equals(other.getCategoryLabel())) return false;
}
if (hasId() != other.hasId()) return false;
if (hasId()) {
if (getId()
!= other.getId()) return false;
}
if (hasCampaignId() != other.hasCampaignId()) return false;
if (hasCampaignId()) {
if (getCampaignId()
!= other.getCampaignId()) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + RESOURCE_NAME_FIELD_NUMBER;
hash = (53 * hash) + getResourceName().hashCode();
if (hasCategoryLabel()) {
hash = (37 * hash) + CATEGORY_LABEL_FIELD_NUMBER;
hash = (53 * hash) + getCategoryLabel().hashCode();
}
if (hasId()) {
hash = (37 * hash) + ID_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getId());
}
if (hasCampaignId()) {
hash = (37 * hash) + CAMPAIGN_ID_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getCampaignId());
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v21.resources.CampaignSearchTermInsight parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.resources.CampaignSearchTermInsight parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.resources.CampaignSearchTermInsight parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.resources.CampaignSearchTermInsight parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.resources.CampaignSearchTermInsight parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.resources.CampaignSearchTermInsight parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.resources.CampaignSearchTermInsight parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.resources.CampaignSearchTermInsight parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v21.resources.CampaignSearchTermInsight parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.resources.CampaignSearchTermInsight parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v21.resources.CampaignSearchTermInsight parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.resources.CampaignSearchTermInsight parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v21.resources.CampaignSearchTermInsight 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>
* This report provides a high-level view of search demand at the campaign
* level by grouping similar search terms into categories and showing their
* search volume.
* Historical data is available starting March 2023.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.resources.CampaignSearchTermInsight}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.resources.CampaignSearchTermInsight)
com.google.ads.googleads.v21.resources.CampaignSearchTermInsightOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.resources.CampaignSearchTermInsightProto.internal_static_google_ads_googleads_v21_resources_CampaignSearchTermInsight_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.resources.CampaignSearchTermInsightProto.internal_static_google_ads_googleads_v21_resources_CampaignSearchTermInsight_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.resources.CampaignSearchTermInsight.class, com.google.ads.googleads.v21.resources.CampaignSearchTermInsight.Builder.class);
}
// Construct using com.google.ads.googleads.v21.resources.CampaignSearchTermInsight.newBuilder()
private Builder() {
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
resourceName_ = "";
categoryLabel_ = "";
id_ = 0L;
campaignId_ = 0L;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v21.resources.CampaignSearchTermInsightProto.internal_static_google_ads_googleads_v21_resources_CampaignSearchTermInsight_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v21.resources.CampaignSearchTermInsight getDefaultInstanceForType() {
return com.google.ads.googleads.v21.resources.CampaignSearchTermInsight.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v21.resources.CampaignSearchTermInsight build() {
com.google.ads.googleads.v21.resources.CampaignSearchTermInsight result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v21.resources.CampaignSearchTermInsight buildPartial() {
com.google.ads.googleads.v21.resources.CampaignSearchTermInsight result = new com.google.ads.googleads.v21.resources.CampaignSearchTermInsight(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v21.resources.CampaignSearchTermInsight result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.resourceName_ = resourceName_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.categoryLabel_ = categoryLabel_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.id_ = id_;
to_bitField0_ |= 0x00000002;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.campaignId_ = campaignId_;
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.ads.googleads.v21.resources.CampaignSearchTermInsight) {
return mergeFrom((com.google.ads.googleads.v21.resources.CampaignSearchTermInsight)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v21.resources.CampaignSearchTermInsight other) {
if (other == com.google.ads.googleads.v21.resources.CampaignSearchTermInsight.getDefaultInstance()) return this;
if (!other.getResourceName().isEmpty()) {
resourceName_ = other.resourceName_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasCategoryLabel()) {
categoryLabel_ = other.categoryLabel_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasId()) {
setId(other.getId());
}
if (other.hasCampaignId()) {
setCampaignId(other.getCampaignId());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
resourceName_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18: {
categoryLabel_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 24: {
id_ = input.readInt64();
bitField0_ |= 0x00000004;
break;
} // case 24
case 32: {
campaignId_ = input.readInt64();
bitField0_ |= 0x00000008;
break;
} // case 32
default: {
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object resourceName_ = "";
/**
* <pre>
* Output only. The resource name of the campaign level search term insight.
* Campaign level search term insight resource names have the form:
*
* `customers/{customer_id}/campaignSearchTermInsights/{campaign_id}~{category_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code>
* @return The resourceName.
*/
public java.lang.String getResourceName() {
java.lang.Object ref = resourceName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resourceName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Output only. The resource name of the campaign level search term insight.
* Campaign level search term insight resource names have the form:
*
* `customers/{customer_id}/campaignSearchTermInsights/{campaign_id}~{category_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for resourceName.
*/
public com.google.protobuf.ByteString
getResourceNameBytes() {
java.lang.Object ref = resourceName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
resourceName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Output only. The resource name of the campaign level search term insight.
* Campaign level search term insight resource names have the form:
*
* `customers/{customer_id}/campaignSearchTermInsights/{campaign_id}~{category_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code>
* @param value The resourceName to set.
* @return This builder for chaining.
*/
public Builder setResourceName(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
resourceName_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Output only. The resource name of the campaign level search term insight.
* Campaign level search term insight resource names have the form:
*
* `customers/{customer_id}/campaignSearchTermInsights/{campaign_id}~{category_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code>
* @return This builder for chaining.
*/
public Builder clearResourceName() {
resourceName_ = getDefaultInstance().getResourceName();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* Output only. The resource name of the campaign level search term insight.
* Campaign level search term insight resource names have the form:
*
* `customers/{customer_id}/campaignSearchTermInsights/{campaign_id}~{category_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code>
* @param value The bytes for resourceName to set.
* @return This builder for chaining.
*/
public Builder setResourceNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
resourceName_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object categoryLabel_ = "";
/**
* <pre>
* Output only. The label for the search category. An empty string denotes the
* catch-all category for search terms that didn't fit into another category.
* </pre>
*
* <code>optional string category_label = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return Whether the categoryLabel field is set.
*/
public boolean hasCategoryLabel() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* Output only. The label for the search category. An empty string denotes the
* catch-all category for search terms that didn't fit into another category.
* </pre>
*
* <code>optional string category_label = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The categoryLabel.
*/
public java.lang.String getCategoryLabel() {
java.lang.Object ref = categoryLabel_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
categoryLabel_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Output only. The label for the search category. An empty string denotes the
* catch-all category for search terms that didn't fit into another category.
* </pre>
*
* <code>optional string category_label = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The bytes for categoryLabel.
*/
public com.google.protobuf.ByteString
getCategoryLabelBytes() {
java.lang.Object ref = categoryLabel_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
categoryLabel_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Output only. The label for the search category. An empty string denotes the
* catch-all category for search terms that didn't fit into another category.
* </pre>
*
* <code>optional string category_label = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @param value The categoryLabel to set.
* @return This builder for chaining.
*/
public Builder setCategoryLabel(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
categoryLabel_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Output only. The label for the search category. An empty string denotes the
* catch-all category for search terms that didn't fit into another category.
* </pre>
*
* <code>optional string category_label = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return This builder for chaining.
*/
public Builder clearCategoryLabel() {
categoryLabel_ = getDefaultInstance().getCategoryLabel();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
* <pre>
* Output only. The label for the search category. An empty string denotes the
* catch-all category for search terms that didn't fit into another category.
* </pre>
*
* <code>optional string category_label = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @param value The bytes for categoryLabel to set.
* @return This builder for chaining.
*/
public Builder setCategoryLabelBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
categoryLabel_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private long id_ ;
/**
* <pre>
* Output only. The ID of the insight.
* </pre>
*
* <code>optional int64 id = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return Whether the id field is set.
*/
@java.lang.Override
public boolean hasId() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
* <pre>
* Output only. The ID of the insight.
* </pre>
*
* <code>optional int64 id = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The id.
*/
@java.lang.Override
public long getId() {
return id_;
}
/**
* <pre>
* Output only. The ID of the insight.
* </pre>
*
* <code>optional int64 id = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @param value The id to set.
* @return This builder for chaining.
*/
public Builder setId(long value) {
id_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* Output only. The ID of the insight.
* </pre>
*
* <code>optional int64 id = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return This builder for chaining.
*/
public Builder clearId() {
bitField0_ = (bitField0_ & ~0x00000004);
id_ = 0L;
onChanged();
return this;
}
private long campaignId_ ;
/**
* <pre>
* Output only. The ID of the campaign.
* </pre>
*
* <code>optional int64 campaign_id = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return Whether the campaignId field is set.
*/
@java.lang.Override
public boolean hasCampaignId() {
return ((bitField0_ & 0x00000008) != 0);
}
/**
* <pre>
* Output only. The ID of the campaign.
* </pre>
*
* <code>optional int64 campaign_id = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The campaignId.
*/
@java.lang.Override
public long getCampaignId() {
return campaignId_;
}
/**
* <pre>
* Output only. The ID of the campaign.
* </pre>
*
* <code>optional int64 campaign_id = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @param value The campaignId to set.
* @return This builder for chaining.
*/
public Builder setCampaignId(long value) {
campaignId_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
* <pre>
* Output only. The ID of the campaign.
* </pre>
*
* <code>optional int64 campaign_id = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return This builder for chaining.
*/
public Builder clearCampaignId() {
bitField0_ = (bitField0_ & ~0x00000008);
campaignId_ = 0L;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v21.resources.CampaignSearchTermInsight)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v21.resources.CampaignSearchTermInsight)
private static final com.google.ads.googleads.v21.resources.CampaignSearchTermInsight DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v21.resources.CampaignSearchTermInsight();
}
public static com.google.ads.googleads.v21.resources.CampaignSearchTermInsight getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CampaignSearchTermInsight>
PARSER = new com.google.protobuf.AbstractParser<CampaignSearchTermInsight>() {
@java.lang.Override
public CampaignSearchTermInsight 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<CampaignSearchTermInsight> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CampaignSearchTermInsight> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v21.resources.CampaignSearchTermInsight getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/phoenix-omid | 36,432 | hbase-coprocessor/src/test/java/org/apache/omid/transaction/TestSnapshotFilter.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.omid.transaction;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CompareOperator;
import org.apache.hadoop.hbase.Coprocessor;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.MiniHBaseCluster;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.CoprocessorDescriptorBuilder;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.filter.BinaryComparator;
import org.apache.hadoop.hbase.filter.FamilyFilter;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.filter.SubstringComparator;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.omid.TestUtils;
import org.apache.omid.committable.CommitTable;
import org.apache.omid.committable.hbase.HBaseCommitTableConfig;
import org.apache.omid.metrics.NullMetricsProvider;
import org.apache.omid.timestamp.storage.HBaseTimestampStorageConfig;
import org.apache.omid.tso.TSOServer;
import org.apache.omid.tso.TSOServerConfig;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.testng.Assert.fail;
import org.apache.phoenix.thirdparty.com.google.common.util.concurrent.ListenableFuture;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class TestSnapshotFilter {
private static final Logger LOG = LoggerFactory.getLogger(TestSnapshotFilter.class);
private static final String TEST_FAMILY = "test-fam";
private static final int MAX_VERSIONS = 3;
private AbstractTransactionManager tm;
private Injector injector;
private Admin admin;
private Configuration hbaseConf;
private HBaseTestingUtility hbaseTestUtil;
private MiniHBaseCluster hbaseCluster;
private TSOServer tso;
private CommitTable commitTable;
private PostCommitActions syncPostCommitter;
private Connection connection;
@BeforeClass
public void setupTestSnapshotFilter() throws Exception {
TSOServerConfig tsoConfig = new TSOServerConfig();
tsoConfig.setPort(5679);
tsoConfig.setConflictMapSize(1);
tsoConfig.setWaitStrategy("LOW_CPU");
injector = Guice.createInjector(new TSOForSnapshotFilterTestModule(tsoConfig));
hbaseConf = injector.getInstance(Configuration.class);
hbaseConf.setBoolean("omid.server.side.filter", true);
hbaseConf.setInt("hbase.hconnection.threads.core", 5);
hbaseConf.setInt("hbase.hconnection.threads.max", 10);
// Tunn down handler threads in regionserver
hbaseConf.setInt("hbase.regionserver.handler.count", 10);
// Set to random port
hbaseConf.setInt("hbase.master.port", 0);
hbaseConf.setInt("hbase.master.info.port", 0);
hbaseConf.setInt("hbase.regionserver.port", 0);
hbaseConf.setInt("hbase.regionserver.info.port", 0);
HBaseCommitTableConfig hBaseCommitTableConfig = injector.getInstance(HBaseCommitTableConfig.class);
HBaseTimestampStorageConfig hBaseTimestampStorageConfig = injector.getInstance(HBaseTimestampStorageConfig.class);
setupHBase();
connection = ConnectionFactory.createConnection(hbaseConf);
admin = connection.getAdmin();
createRequiredHBaseTables(hBaseTimestampStorageConfig, hBaseCommitTableConfig);
setupTSO();
commitTable = injector.getInstance(CommitTable.class);
}
private void setupHBase() throws Exception {
LOG.info("--------------------------------------------------------------------------------------------------");
LOG.info("Setting up HBase");
LOG.info("--------------------------------------------------------------------------------------------------");
hbaseTestUtil = new HBaseTestingUtility(hbaseConf);
LOG.info("--------------------------------------------------------------------------------------------------");
LOG.info("Creating HBase MiniCluster");
LOG.info("--------------------------------------------------------------------------------------------------");
hbaseCluster = hbaseTestUtil.startMiniCluster(1);
}
private void createRequiredHBaseTables(HBaseTimestampStorageConfig timestampStorageConfig,
HBaseCommitTableConfig hBaseCommitTableConfig) throws IOException {
createTableIfNotExists(timestampStorageConfig.getTableName(), timestampStorageConfig.getFamilyName().getBytes());
createTableIfNotExists(hBaseCommitTableConfig.getTableName(), hBaseCommitTableConfig.getCommitTableFamily(), hBaseCommitTableConfig.getLowWatermarkFamily());
}
private void createTableIfNotExists(String tableName, byte[]... families) throws IOException {
if (!admin.tableExists(TableName.valueOf(tableName))) {
LOG.info("Creating {} table...", tableName);
ArrayList<ColumnFamilyDescriptor> fams = new ArrayList<>();
for (byte[] family : families) {
fams.add(ColumnFamilyDescriptorBuilder
.newBuilder(family)
.setMaxVersions(MAX_VERSIONS)
.build());
}
int priority = Coprocessor.PRIORITY_HIGHEST;
TableDescriptor desc = TableDescriptorBuilder
.newBuilder(TableName.valueOf(tableName))
.setColumnFamilies(fams)
.setCoprocessor(CoprocessorDescriptorBuilder
.newBuilder(OmidSnapshotFilter.class.getName())
.setPriority(++priority).build())
.setCoprocessor(CoprocessorDescriptorBuilder
.newBuilder("org.apache.hadoop.hbase.coprocessor.AggregateImplementation")
.setPriority(++priority).build())
.build();
admin.createTable(desc);
try {
hbaseTestUtil.waitTableAvailable(TableName.valueOf(tableName),5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void setupTSO() throws IOException, InterruptedException {
tso = injector.getInstance(TSOServer.class);
tso.startAsync();
tso.awaitRunning();
TestUtils.waitForSocketListening("localhost", 5679, 100);
Thread.currentThread().setName("UnitTest(s) thread");
}
@AfterClass
public void cleanupTestSnapshotFilter() throws Exception {
teardownTSO();
hbaseCluster.shutdown();
}
private void teardownTSO() throws IOException, InterruptedException {
tso.stopAsync();
tso.awaitTerminated();
TestUtils.waitForSocketNotListening("localhost", 5679, 1000);
}
@BeforeMethod
public void setupTestSnapshotFilterIndividualTest() throws Exception {
tm = spy((AbstractTransactionManager) newTransactionManager());
}
private TransactionManager newTransactionManager() throws Exception {
HBaseOmidClientConfiguration hbaseOmidClientConf = new HBaseOmidClientConfiguration();
hbaseOmidClientConf.setConnectionString("localhost:5679");
hbaseOmidClientConf.setHBaseConfiguration(hbaseConf);
CommitTable.Client commitTableClient = commitTable.getClient();
syncPostCommitter =
spy(new HBaseSyncPostCommitter(new NullMetricsProvider(),commitTableClient, connection));
return HBaseTransactionManager.builder(hbaseOmidClientConf)
.postCommitter(syncPostCommitter)
.commitTableClient(commitTableClient)
.build();
}
@Test(timeOut = 60_000)
public void testGetFirstResult() throws Throwable {
byte[] rowName1 = Bytes.toBytes("row1");
byte[] famName1 = Bytes.toBytes(TEST_FAMILY);
byte[] colName1 = Bytes.toBytes("col1");
byte[] dataValue1 = Bytes.toBytes("testWrite-1");
String TEST_TABLE = "testGetFirstResult";
createTableIfNotExists(TEST_TABLE, Bytes.toBytes(TEST_FAMILY));
TTable tt = new TTable(connection, TEST_TABLE);
Transaction tx1 = tm.begin();
Put row1 = new Put(rowName1);
row1.addColumn(famName1, colName1, dataValue1);
tt.put(tx1, row1);
tm.commit(tx1);
Transaction tx2 = tm.begin();
Get get = new Get(rowName1);
Result result = tt.get(tx2, get);
assertTrue(!result.isEmpty(), "Result should not be empty!");
long tsRow = result.rawCells()[0].getTimestamp();
assertEquals(tsRow, tx1.getTransactionId(), "Reading differnt version");
tm.commit(tx2);
Transaction tx3 = tm.begin();
Put put3 = new Put(rowName1);
put3.addColumn(famName1, colName1, dataValue1);
tt.put(tx3, put3);
tm.commit(tx3);
Transaction tx4 = tm.begin();
Get get2 = new Get(rowName1);
Result result2 = tt.get(tx4, get2);
assertTrue(!result2.isEmpty(), "Result should not be empty!");
long tsRow2 = result2.rawCells()[0].getTimestamp();
assertEquals(tsRow2, tx3.getTransactionId(), "Reading differnt version");
tm.commit(tx4);
tt.close();
}
// This test will fail if filtering is done before snapshot filtering
@Test(timeOut = 60_000)
public void testServerSideSnapshotFiltering() throws Throwable {
byte[] rowName1 = Bytes.toBytes("row1");
byte[] famName1 = Bytes.toBytes(TEST_FAMILY);
byte[] colName1 = Bytes.toBytes("col1");
byte[] dataValue1 = Bytes.toBytes("testWrite-1");
byte[] dataValue2 = Bytes.toBytes("testWrite-2");
String TEST_TABLE = "testServerSideSnapshotFiltering";
createTableIfNotExists(TEST_TABLE, Bytes.toBytes(TEST_FAMILY));
TTable tt = new TTable(connection, TEST_TABLE);
Transaction tx1 = tm.begin();
Put put1 = new Put(rowName1);
put1.addColumn(famName1, colName1, dataValue1);
tt.put(tx1, put1);
tm.commit(tx1);
Transaction tx2 = tm.begin();
Put put2 = new Put(rowName1);
put2.addColumn(famName1, colName1, dataValue2);
tt.put(tx2, put2);
Transaction tx3 = tm.begin();
Get get = new Get(rowName1);
// If snapshot filtering is not done in the server then the first value is
// "testWrite-2" and the whole row will be filtered out.
SingleColumnValueFilter filter = new SingleColumnValueFilter(
famName1,
colName1,
CompareOperator.EQUAL,
new SubstringComparator("testWrite-1"));
get.setFilter(filter);
Result results = tt.get(tx3, get);
assertTrue(results.size() == 1);
}
// This test will fail if filtering is done before snapshot filtering
@Test(timeOut = 60_000)
public void testServerSideSnapshotScannerFiltering() throws Throwable {
byte[] rowName1 = Bytes.toBytes("row1");
byte[] famName1 = Bytes.toBytes(TEST_FAMILY);
byte[] colName1 = Bytes.toBytes("col1");
byte[] dataValue1 = Bytes.toBytes("testWrite-1");
byte[] dataValue2 = Bytes.toBytes("testWrite-2");
String TEST_TABLE = "testServerSideSnapshotFiltering";
createTableIfNotExists(TEST_TABLE, Bytes.toBytes(TEST_FAMILY));
TTable tt = new TTable(connection, TEST_TABLE);
Transaction tx1 = tm.begin();
Put put1 = new Put(rowName1);
put1.addColumn(famName1, colName1, dataValue1);
tt.put(tx1, put1);
tm.commit(tx1);
Transaction tx2 = tm.begin();
Put put2 = new Put(rowName1);
put2.addColumn(famName1, colName1, dataValue2);
// tt.put(tx2, put2);
Transaction tx3 = tm.begin();
// If snapshot filtering is not done in the server then the first value is
// "testWrite-2" and the whole row will be filtered out.
SingleColumnValueFilter filter = new SingleColumnValueFilter(
famName1,
colName1,
CompareOperator.EQUAL,
new SubstringComparator("testWrite-1"));
Scan scan = new Scan();
scan.setFilter(filter);
ResultScanner iterableRS = tt.getScanner(tx3, scan);
Result result = iterableRS.next();
assertTrue(result.size() == 1);
}
@Test(timeOut = 60_000)
public void testGetWithFamilyDelete() throws Throwable {
byte[] rowName1 = Bytes.toBytes("row1");
byte[] famName1 = Bytes.toBytes(TEST_FAMILY);
byte[] famName2 = Bytes.toBytes("test-fam2");
byte[] colName1 = Bytes.toBytes("col1");
byte[] colName2 = Bytes.toBytes("col2");
byte[] dataValue1 = Bytes.toBytes("testWrite-1");
String TEST_TABLE = "testGetWithFamilyDelete";
createTableIfNotExists(TEST_TABLE, Bytes.toBytes(TEST_FAMILY), famName2);
TTable tt = new TTable(connection, TEST_TABLE);
Transaction tx1 = tm.begin();
Put put1 = new Put(rowName1);
put1.addColumn(famName1, colName1, dataValue1);
tt.put(tx1, put1);
tm.commit(tx1);
Transaction tx2 = tm.begin();
Put put2 = new Put(rowName1);
put2.addColumn(famName2, colName2, dataValue1);
tt.put(tx2, put2);
tm.commit(tx2);
Transaction tx3 = tm.begin();
Delete d = new Delete(rowName1);
d.addFamily(famName2);
tt.delete(tx3, d);
Transaction tx4 = tm.begin();
Get get = new Get(rowName1);
Filter filter1 = new FilterList(FilterList.Operator.MUST_PASS_ONE,
new FamilyFilter(CompareOperator.EQUAL, new BinaryComparator(Bytes.toBytes(TEST_FAMILY))),
new FamilyFilter(CompareOperator.EQUAL, new BinaryComparator(famName2)));
get.setFilter(filter1);
Result result = tt.get(tx4, get);
assertTrue(result.size() == 2, "Result should be 2");
try {
tm.commit(tx3);
} catch (RollbackException e) {
if (!tm.isLowLatency())
fail();
}
Transaction tx5 = tm.begin();
result = tt.get(tx5, get);
if (!tm.isLowLatency())
assertTrue(result.size() == 1, "Result should be 1");
tt.close();
}
@Test(timeOut = 60_000)
public void testReadFromCommitTable() throws Exception {
final byte[] rowName1 = Bytes.toBytes("row1");
byte[] famName1 = Bytes.toBytes(TEST_FAMILY);
byte[] colName1 = Bytes.toBytes("col1");
byte[] dataValue1 = Bytes.toBytes("testWrite-1");
final String TEST_TABLE = "testReadFromCommitTable";
final byte[] famName2 = Bytes.toBytes("test-fam2");
final CountDownLatch readAfterCommit = new CountDownLatch(1);
final CountDownLatch postCommitBegin = new CountDownLatch(1);
final AtomicBoolean readFailed = new AtomicBoolean(false);
final AbstractTransactionManager tm = (AbstractTransactionManager) newTransactionManager();
createTableIfNotExists(TEST_TABLE, Bytes.toBytes(TEST_FAMILY), famName2);
doAnswer(new Answer<ListenableFuture<Void>>() {
@Override
public ListenableFuture<Void> answer(InvocationOnMock invocation) throws Throwable {
LOG.info("Releasing readAfterCommit barrier");
readAfterCommit.countDown();
LOG.info("Waiting postCommitBegin barrier");
postCommitBegin.await();
ListenableFuture<Void> result = (ListenableFuture<Void>) invocation.callRealMethod();
return result;
}
}).when(syncPostCommitter).updateShadowCells(any(HBaseTransaction.class));
Thread readThread = new Thread("Read Thread") {
@Override
public void run() {
try {
LOG.info("Waiting readAfterCommit barrier");
readAfterCommit.await();
Transaction tx4 = tm.begin();
TTable tt = new TTable(connection, TEST_TABLE);
Get get = new Get(rowName1);
Filter filter1 = new FilterList(FilterList.Operator.MUST_PASS_ONE,
new FamilyFilter(CompareOperator.EQUAL, new BinaryComparator(Bytes.toBytes(TEST_FAMILY))),
new FamilyFilter(CompareOperator.EQUAL, new BinaryComparator(famName2)));
get.setFilter(filter1);
Result result = tt.get(tx4, get);
if (result.size() == 2) {
readFailed.set(false);
}
else {
readFailed.set(false);
}
postCommitBegin.countDown();
} catch (Throwable e) {
readFailed.set(false);
LOG.error("Error whilst reading", e);
}
}
};
readThread.start();
TTable table = new TTable(connection, TEST_TABLE);
final HBaseTransaction t1 = (HBaseTransaction) tm.begin();
Put put1 = new Put(rowName1);
put1.addColumn(famName1, colName1, dataValue1);
table.put(t1, put1);
tm.commit(t1);
readThread.join();
assertFalse(readFailed.get(), "Read should have succeeded");
}
@Test(timeOut = 60_000)
public void testGetWithFilter() throws Throwable {
byte[] rowName1 = Bytes.toBytes("row1");
byte[] famName1 = Bytes.toBytes(TEST_FAMILY);
byte[] famName2 = Bytes.toBytes("test-fam2");
byte[] colName1 = Bytes.toBytes("col1");
byte[] colName2 = Bytes.toBytes("col2");
byte[] dataValue1 = Bytes.toBytes("testWrite-1");
String TEST_TABLE = "testGetWithFilter";
createTableIfNotExists(TEST_TABLE, Bytes.toBytes(TEST_FAMILY), famName2);
TTable tt = new TTable(connection, TEST_TABLE);
Transaction tx1 = tm.begin();
Put put1 = new Put(rowName1);
put1.addColumn(famName1, colName1, dataValue1);
tt.put(tx1, put1);
tm.commit(tx1);
Transaction tx2 = tm.begin();
Put put2 = new Put(rowName1);
put2.addColumn(famName2, colName2, dataValue1);
tt.put(tx2, put2);
tm.commit(tx2);
Transaction tx3 = tm.begin();
Get get = new Get(rowName1);
Filter filter1 = new FilterList(FilterList.Operator.MUST_PASS_ONE,
new FamilyFilter(CompareOperator.EQUAL, new BinaryComparator(Bytes.toBytes(TEST_FAMILY))),
new FamilyFilter(CompareOperator.EQUAL, new BinaryComparator(famName2)));
get.setFilter(filter1);
Result result = tt.get(tx3, get);
assertTrue(result.size() == 2, "Result should be 2");
Filter filter2 = new FilterList(FilterList.Operator.MUST_PASS_ONE,
new FamilyFilter(CompareOperator.EQUAL, new BinaryComparator(Bytes.toBytes(TEST_FAMILY))));
get.setFilter(filter2);
result = tt.get(tx3, get);
assertTrue(result.size() == 1, "Result should be 2");
tm.commit(tx3);
tt.close();
}
@Test(timeOut = 60_000)
public void testGetSecondResult() throws Throwable {
byte[] rowName1 = Bytes.toBytes("row1");
byte[] famName1 = Bytes.toBytes(TEST_FAMILY);
byte[] colName1 = Bytes.toBytes("col1");
byte[] dataValue1 = Bytes.toBytes("testWrite-1");
String TEST_TABLE = "testGetSecondResult";
createTableIfNotExists(TEST_TABLE, Bytes.toBytes(TEST_FAMILY));
TTable tt = new TTable(connection, TEST_TABLE);
Transaction tx1 = tm.begin();
Put put1 = new Put(rowName1);
put1.addColumn(famName1, colName1, dataValue1);
tt.put(tx1, put1);
tm.commit(tx1);
Transaction tx2 = tm.begin();
Put put2 = new Put(rowName1);
put2.addColumn(famName1, colName1, dataValue1);
tt.put(tx2, put2);
Transaction tx3 = tm.begin();
Get get = new Get(rowName1);
Result result = tt.get(tx3, get);
assertTrue(!result.isEmpty(), "Result should not be empty!");
long tsRow = result.rawCells()[0].getTimestamp();
assertEquals(tsRow, tx1.getTransactionId(), "Reading differnt version");
tm.commit(tx3);
tt.close();
}
@Test(timeOut = 60_000)
public void testScanFirstResult() throws Throwable {
byte[] rowName1 = Bytes.toBytes("row1");
byte[] famName1 = Bytes.toBytes(TEST_FAMILY);
byte[] colName1 = Bytes.toBytes("col1");
byte[] dataValue1 = Bytes.toBytes("testWrite-1");
String TEST_TABLE = "testScanFirstResult";
createTableIfNotExists(TEST_TABLE, Bytes.toBytes(TEST_FAMILY));
TTable tt = new TTable(connection, TEST_TABLE);
Transaction tx1 = tm.begin();
Put row1 = new Put(rowName1);
row1.addColumn(famName1, colName1, dataValue1);
tt.put(tx1, row1);
tm.commit(tx1);
Transaction tx2 = tm.begin();
ResultScanner iterableRS = tt.getScanner(tx2, new Scan().withStartRow(rowName1).withStopRow(rowName1, true));
Result result = iterableRS.next();
long tsRow = result.rawCells()[0].getTimestamp();
assertEquals(tsRow, tx1.getTransactionId(), "Reading differnt version");
assertFalse(iterableRS.next() != null);
tm.commit(tx2);
Transaction tx3 = tm.begin();
Put put3 = new Put(rowName1);
put3.addColumn(famName1, colName1, dataValue1);
tt.put(tx3, put3);
tm.commit(tx3);
Transaction tx4 = tm.begin();
ResultScanner iterableRS2 = tt.getScanner(tx4, new Scan().withStartRow(rowName1).withStopRow(rowName1, true));
Result result2 = iterableRS2.next();
long tsRow2 = result2.rawCells()[0].getTimestamp();
assertEquals(tsRow2, tx3.getTransactionId(), "Reading differnt version");
assertFalse(iterableRS2.next() != null);
tm.commit(tx4);
tt.close();
}
@Test(timeOut = 60_000)
public void testScanWithFilter() throws Throwable {
byte[] rowName1 = Bytes.toBytes("row1");
byte[] famName1 = Bytes.toBytes(TEST_FAMILY);
byte[] famName2 = Bytes.toBytes("test-fam2");
byte[] colName1 = Bytes.toBytes("col1");
byte[] colName2 = Bytes.toBytes("col2");
byte[] dataValue1 = Bytes.toBytes("testWrite-1");
String TEST_TABLE = "testScanWithFilter";
createTableIfNotExists(TEST_TABLE, famName1, famName2);
TTable tt = new TTable(connection, TEST_TABLE);
Transaction tx1 = tm.begin();
Put put1 = new Put(rowName1);
put1.addColumn(famName1, colName1, dataValue1);
tt.put(tx1, put1);
tm.commit(tx1);
Transaction tx2 = tm.begin();
Put put2 = new Put(rowName1);
put2.addColumn(famName2, colName2, dataValue1);
tt.put(tx2, put2);
tm.commit(tx2);
Transaction tx3 = tm.begin();
Scan scan = new Scan();
scan.setFilter(new FilterList(FilterList.Operator.MUST_PASS_ONE,
new FamilyFilter(CompareOperator.EQUAL, new BinaryComparator(Bytes.toBytes(TEST_FAMILY)))));
scan.withStartRow(rowName1).withStopRow(rowName1, true);
ResultScanner iterableRS = tt.getScanner(tx3, scan);
Result result = iterableRS.next();
assertTrue(result.containsColumn(famName1, colName1));
assertFalse(result.containsColumn(famName2, colName2));
scan.setFilter(new FilterList(FilterList.Operator.MUST_PASS_ONE,
new FamilyFilter(CompareOperator.EQUAL, new BinaryComparator(Bytes.toBytes(TEST_FAMILY))),
new FamilyFilter(CompareOperator.EQUAL, new BinaryComparator(famName2))));
iterableRS = tt.getScanner(tx3, scan);
result = iterableRS.next();
assertTrue(result.containsColumn(famName1, colName1));
assertTrue(result.containsColumn(famName2, colName2));
tm.commit(tx3);
tt.close();
}
@Test(timeOut = 60_000)
public void testScanSecondResult() throws Throwable {
byte[] rowName1 = Bytes.toBytes("row1");
byte[] famName1 = Bytes.toBytes(TEST_FAMILY);
byte[] colName1 = Bytes.toBytes("col1");
byte[] dataValue1 = Bytes.toBytes("testWrite-1");
String TEST_TABLE = "testScanSecondResult";
createTableIfNotExists(TEST_TABLE, Bytes.toBytes(TEST_FAMILY));
TTable tt = new TTable(connection, TEST_TABLE);
Transaction tx1 = tm.begin();
Put put1 = new Put(rowName1);
put1.addColumn(famName1, colName1, dataValue1);
tt.put(tx1, put1);
tm.commit(tx1);
Transaction tx2 = tm.begin();
Put put2 = new Put(rowName1);
put2.addColumn(famName1, colName1, dataValue1);
tt.put(tx2, put2);
Transaction tx3 = tm.begin();
ResultScanner iterableRS = tt.getScanner(tx3, new Scan().withStartRow(rowName1).withStopRow(rowName1, true));
Result result = iterableRS.next();
long tsRow = result.rawCells()[0].getTimestamp();
assertEquals(tsRow, tx1.getTransactionId(), "Reading differnt version");
assertFalse(iterableRS.next() != null);
tm.commit(tx3);
tt.close();
}
@Test (timeOut = 60_000)
public void testScanFewResults() throws Throwable {
byte[] rowName1 = Bytes.toBytes("row1");
byte[] rowName2 = Bytes.toBytes("row2");
byte[] rowName3 = Bytes.toBytes("row3");
byte[] famName = Bytes.toBytes(TEST_FAMILY);
byte[] colName1 = Bytes.toBytes("col1");
byte[] colName2 = Bytes.toBytes("col2");
byte[] dataValue1 = Bytes.toBytes("testWrite-1");
byte[] dataValue2 = Bytes.toBytes("testWrite-2");
String TEST_TABLE = "testScanFewResults";
createTableIfNotExists(TEST_TABLE, Bytes.toBytes(TEST_FAMILY));
TTable tt = new TTable(connection, TEST_TABLE);
Transaction tx1 = tm.begin();
Put put1 = new Put(rowName1);
put1.addColumn(famName, colName1, dataValue1);
tt.put(tx1, put1);
tm.commit(tx1);
Transaction tx2 = tm.begin();
Put put2 = new Put(rowName2);
put2.addColumn(famName, colName2, dataValue2);
tt.put(tx2, put2);
tm.commit(tx2);
Transaction tx3 = tm.begin();
ResultScanner iterableRS = tt.getScanner(tx3, new Scan().withStartRow(rowName1).withStopRow(rowName3));
Result result = iterableRS.next();
long tsRow = result.rawCells()[0].getTimestamp();
assertEquals(tsRow, tx1.getTransactionId(), "Reading differnt version");
result = iterableRS.next();
tsRow = result.rawCells()[0].getTimestamp();
assertEquals(tsRow, tx2.getTransactionId(), "Reading differnt version");
assertFalse(iterableRS.next() != null);
tm.commit(tx3);
tt.close();
}
@Test (timeOut = 60_000)
public void testScanFewResultsDifferentTransaction() throws Throwable {
byte[] rowName1 = Bytes.toBytes("row1");
byte[] rowName2 = Bytes.toBytes("row2");
byte[] rowName3 = Bytes.toBytes("row3");
byte[] famName = Bytes.toBytes(TEST_FAMILY);
byte[] colName1 = Bytes.toBytes("col1");
byte[] colName2 = Bytes.toBytes("col2");
byte[] dataValue1 = Bytes.toBytes("testWrite-1");
byte[] dataValue2 = Bytes.toBytes("testWrite-2");
String TEST_TABLE = "testScanFewResultsDifferentTransaction";
createTableIfNotExists(TEST_TABLE, Bytes.toBytes(TEST_FAMILY));
TTable tt = new TTable(connection, TEST_TABLE);
Transaction tx1 = tm.begin();
Put put1 = new Put(rowName1);
put1.addColumn(famName, colName1, dataValue1);
tt.put(tx1, put1);
Put put2 = new Put(rowName2);
put2.addColumn(famName, colName2, dataValue2);
tt.put(tx1, put2);
tm.commit(tx1);
Transaction tx2 = tm.begin();
put2 = new Put(rowName2);
put2.addColumn(famName, colName2, dataValue2);
tt.put(tx2, put2);
tm.commit(tx2);
Transaction tx3 = tm.begin();
ResultScanner iterableRS = tt.getScanner(tx3, new Scan().withStartRow(rowName1).withStopRow(rowName3));
Result result = iterableRS.next();
long tsRow = result.rawCells()[0].getTimestamp();
assertEquals(tsRow, tx1.getTransactionId(), "Reading differnt version");
result = iterableRS.next();
tsRow = result.rawCells()[0].getTimestamp();
assertEquals(tsRow, tx2.getTransactionId(), "Reading differnt version");
assertFalse(iterableRS.next() != null);
tm.commit(tx3);
tt.close();
}
@Test (timeOut = 60_000)
public void testScanFewResultsSameTransaction() throws Throwable {
byte[] rowName1 = Bytes.toBytes("row1");
byte[] rowName2 = Bytes.toBytes("row2");
byte[] rowName3 = Bytes.toBytes("row3");
byte[] famName = Bytes.toBytes(TEST_FAMILY);
byte[] colName1 = Bytes.toBytes("col1");
byte[] colName2 = Bytes.toBytes("col2");
byte[] dataValue1 = Bytes.toBytes("testWrite-1");
byte[] dataValue2 = Bytes.toBytes("testWrite-2");
String TEST_TABLE = "testScanFewResultsSameTransaction";
createTableIfNotExists(TEST_TABLE, Bytes.toBytes(TEST_FAMILY));
TTable tt = new TTable(connection, TEST_TABLE);
Transaction tx1 = tm.begin();
Put put1 = new Put(rowName1);
put1.addColumn(famName, colName1, dataValue1);
tt.put(tx1, put1);
Put put2 = new Put(rowName2);
put2.addColumn(famName, colName2, dataValue2);
tt.put(tx1, put2);
tm.commit(tx1);
Transaction tx2 = tm.begin();
put2 = new Put(rowName2);
put2.addColumn(famName, colName2, dataValue2);
tt.put(tx2, put2);
Transaction tx3 = tm.begin();
ResultScanner iterableRS = tt.getScanner(tx3, new Scan().withStartRow(rowName1).withStopRow(rowName3));
Result result = iterableRS.next();
long tsRow = result.rawCells()[0].getTimestamp();
assertEquals(tsRow, tx1.getTransactionId(), "Reading differnt version");
result = iterableRS.next();
tsRow = result.rawCells()[0].getTimestamp();
assertEquals(tsRow, tx1.getTransactionId(), "Reading differnt version");
assertFalse(iterableRS.next() != null);
tm.commit(tx3);
tt.close();
}
@Test (timeOut = 60_000)
public void testFilterCommitCacheInSnapshot() throws Throwable {
String TEST_TABLE = "testFilterCommitCacheInSnapshot";
byte[] rowName = Bytes.toBytes("row1");
byte[] famName = Bytes.toBytes(TEST_FAMILY);
createTableIfNotExists(TEST_TABLE, famName);
TTable tt = new TTable(connection, TEST_TABLE);
Transaction tx1 = tm.begin();
Put put = new Put(rowName);
for (int i = 0; i < 200; ++i) {
byte[] dataValue1 = Bytes.toBytes("some data");
byte[] colName = Bytes.toBytes("col" + i);
put.addColumn(famName, colName, dataValue1);
}
tt.put(tx1, put);
tm.commit(tx1);
Transaction tx3 = tm.begin();
Table htable = connection.getTable(TableName.valueOf(TEST_TABLE));
SnapshotFilterImpl snapshotFilter = spy(new SnapshotFilterImpl(new HTableAccessWrapper(htable, htable),
tm.getCommitTableClient()));
Filter newFilter = TransactionFilters.getVisibilityFilter(null,
snapshotFilter, (HBaseTransaction) tx3);
Table rawTable = connection.getTable(TableName.valueOf(TEST_TABLE));
Scan scan = new Scan();
ResultScanner scanner = rawTable.getScanner(scan);
for(Result row: scanner) {
for(Cell cell: row.rawCells()) {
newFilter.filterCell(cell);
}
}
verify(snapshotFilter, Mockito.times(0))
.getTSIfInSnapshot(any(Cell.class),any(HBaseTransaction.class), any(Map.class));
tm.commit(tx3);
tt.close();
}
@Test (timeOut = 60_000)
public void testFilterCommitCacheNotInSnapshot() throws Throwable {
String TEST_TABLE = "testFilterCommitCacheNotInSnapshot";
byte[] rowName = Bytes.toBytes("row1");
byte[] famName = Bytes.toBytes(TEST_FAMILY);
createTableIfNotExists(TEST_TABLE, famName);
TTable tt = new TTable(connection, TEST_TABLE);
//add some uncommitted values
Transaction tx1 = tm.begin();
Put put = new Put(rowName);
for (int i = 0; i < 200; ++i) {
byte[] dataValue1 = Bytes.toBytes("some data");
byte[] colName = Bytes.toBytes("col" + i);
put.addColumn(famName, colName, dataValue1);
}
tt.put(tx1, put);
//try to scan from tx
Transaction tx = tm.begin();
Table htable = connection.getTable(TableName.valueOf(TEST_TABLE));
SnapshotFilterImpl snapshotFilter = spy(new SnapshotFilterImpl(new HTableAccessWrapper(htable, htable),
tm.getCommitTableClient()));
Filter newFilter = TransactionFilters.getVisibilityFilter(null,
snapshotFilter, (HBaseTransaction) tx);
Table rawTable = connection.getTable(TableName.valueOf(TEST_TABLE));
Scan scan = new Scan();
ResultScanner scanner = rawTable.getScanner(scan);
for(Result row: scanner) {
for(Cell cell: row.rawCells()) {
newFilter.filterCell(cell);
}
}
verify(snapshotFilter, Mockito.times(1))
.getTSIfInSnapshot(any(Cell.class),any(HBaseTransaction.class), any(Map.class));
tt.close();
}
}
|
openjdk/jdk8 | 36,603 | jdk/src/share/classes/javax/swing/text/html/FormView.java | /*
* Copyright (c) 1998, 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.text.html;
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
/**
* Component decorator that implements the view interface
* for form elements, <input>, <textarea>,
* and <select>. The model for the component is stored
* as an attribute of the the element (using StyleConstants.ModelAttribute),
* and is used to build the component of the view. The type
* of the model is assumed to of the type that would be set by
* <code>HTMLDocument.HTMLReader.FormAction</code>. If there are
* multiple views mapped over the document, they will share the
* embedded component models.
* <p>
* The following table shows what components get built
* by this view.
* <table summary="shows what components get built by this view">
* <tr>
* <th>Element Type</th>
* <th>Component built</th>
* </tr>
* <tr>
* <td>input, type button</td>
* <td>JButton</td>
* </tr>
* <tr>
* <td>input, type checkbox</td>
* <td>JCheckBox</td>
* </tr>
* <tr>
* <td>input, type image</td>
* <td>JButton</td>
* </tr>
* <tr>
* <td>input, type password</td>
* <td>JPasswordField</td>
* </tr>
* <tr>
* <td>input, type radio</td>
* <td>JRadioButton</td>
* </tr>
* <tr>
* <td>input, type reset</td>
* <td>JButton</td>
* </tr>
* <tr>
* <td>input, type submit</td>
* <td>JButton</td>
* </tr>
* <tr>
* <td>input, type text</td>
* <td>JTextField</td>
* </tr>
* <tr>
* <td>select, size > 1 or multiple attribute defined</td>
* <td>JList in a JScrollPane</td>
* </tr>
* <tr>
* <td>select, size unspecified or 1</td>
* <td>JComboBox</td>
* </tr>
* <tr>
* <td>textarea</td>
* <td>JTextArea in a JScrollPane</td>
* </tr>
* <tr>
* <td>input, type file</td>
* <td>JTextField</td>
* </tr>
* </table>
*
* @author Timothy Prinzing
* @author Sunita Mani
*/
public class FormView extends ComponentView implements ActionListener {
/**
* If a value attribute is not specified for a FORM input element
* of type "submit", then this default string is used.
*
* @deprecated As of 1.3, value now comes from UIManager property
* FormView.submitButtonText
*/
@Deprecated
public static final String SUBMIT = new String("Submit Query");
/**
* If a value attribute is not specified for a FORM input element
* of type "reset", then this default string is used.
*
* @deprecated As of 1.3, value comes from UIManager UIManager property
* FormView.resetButtonText
*/
@Deprecated
public static final String RESET = new String("Reset");
/**
* Document attribute name for storing POST data. JEditorPane.getPostData()
* uses the same name, should be kept in sync.
*/
final static String PostDataProperty = "javax.swing.JEditorPane.postdata";
/**
* Used to indicate if the maximum span should be the same as the
* preferred span. This is used so that the Component's size doesn't
* change if there is extra room on a line. The first bit is used for
* the X direction, and the second for the y direction.
*/
private short maxIsPreferred;
/**
* Creates a new FormView object.
*
* @param elem the element to decorate
*/
public FormView(Element elem) {
super(elem);
}
/**
* Create the component. This is basically a
* big switch statement based upon the tag type
* and html attributes of the associated element.
*/
protected Component createComponent() {
AttributeSet attr = getElement().getAttributes();
HTML.Tag t = (HTML.Tag)
attr.getAttribute(StyleConstants.NameAttribute);
JComponent c = null;
Object model = attr.getAttribute(StyleConstants.ModelAttribute);
// Remove listeners previously registered in shared model
// when a new UI component is replaced. See bug 7189299.
removeStaleListenerForModel(model);
if (t == HTML.Tag.INPUT) {
c = createInputComponent(attr, model);
} else if (t == HTML.Tag.SELECT) {
if (model instanceof OptionListModel) {
JList list = new JList((ListModel) model);
int size = HTML.getIntegerAttributeValue(attr,
HTML.Attribute.SIZE,
1);
list.setVisibleRowCount(size);
list.setSelectionModel((ListSelectionModel)model);
c = new JScrollPane(list);
} else {
c = new JComboBox((ComboBoxModel) model);
maxIsPreferred = 3;
}
} else if (t == HTML.Tag.TEXTAREA) {
JTextArea area = new JTextArea((Document) model);
int rows = HTML.getIntegerAttributeValue(attr,
HTML.Attribute.ROWS,
1);
area.setRows(rows);
int cols = HTML.getIntegerAttributeValue(attr,
HTML.Attribute.COLS,
20);
maxIsPreferred = 3;
area.setColumns(cols);
c = new JScrollPane(area,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
}
if (c != null) {
c.setAlignmentY(1.0f);
}
return c;
}
/**
* Creates a component for an <INPUT> element based on the
* value of the "type" attribute.
*
* @param set of attributes associated with the <INPUT> element.
* @param model the value of the StyleConstants.ModelAttribute
* @return the component.
*/
private JComponent createInputComponent(AttributeSet attr, Object model) {
JComponent c = null;
String type = (String) attr.getAttribute(HTML.Attribute.TYPE);
if (type.equals("submit") || type.equals("reset")) {
String value = (String)
attr.getAttribute(HTML.Attribute.VALUE);
if (value == null) {
if (type.equals("submit")) {
value = UIManager.getString("FormView.submitButtonText");
} else {
value = UIManager.getString("FormView.resetButtonText");
}
}
JButton button = new JButton(value);
if (model != null) {
button.setModel((ButtonModel)model);
button.addActionListener(this);
}
c = button;
maxIsPreferred = 3;
} else if (type.equals("image")) {
String srcAtt = (String) attr.getAttribute(HTML.Attribute.SRC);
JButton button;
try {
URL base = ((HTMLDocument)getElement().getDocument()).getBase();
URL srcURL = new URL(base, srcAtt);
Icon icon = new ImageIcon(srcURL);
button = new JButton(icon);
} catch (MalformedURLException e) {
button = new JButton(srcAtt);
}
if (model != null) {
button.setModel((ButtonModel)model);
button.addMouseListener(new MouseEventListener());
}
c = button;
maxIsPreferred = 3;
} else if (type.equals("checkbox")) {
c = new JCheckBox();
if (model != null) {
((JCheckBox)c).setModel((JToggleButton.ToggleButtonModel) model);
}
maxIsPreferred = 3;
} else if (type.equals("radio")) {
c = new JRadioButton();
if (model != null) {
((JRadioButton)c).setModel((JToggleButton.ToggleButtonModel)model);
}
maxIsPreferred = 3;
} else if (type.equals("text")) {
int size = HTML.getIntegerAttributeValue(attr,
HTML.Attribute.SIZE,
-1);
JTextField field;
if (size > 0) {
field = new JTextField();
field.setColumns(size);
}
else {
field = new JTextField();
field.setColumns(20);
}
c = field;
if (model != null) {
field.setDocument((Document) model);
}
field.addActionListener(this);
maxIsPreferred = 3;
} else if (type.equals("password")) {
JPasswordField field = new JPasswordField();
c = field;
if (model != null) {
field.setDocument((Document) model);
}
int size = HTML.getIntegerAttributeValue(attr,
HTML.Attribute.SIZE,
-1);
field.setColumns((size > 0) ? size : 20);
field.addActionListener(this);
maxIsPreferred = 3;
} else if (type.equals("file")) {
JTextField field = new JTextField();
if (model != null) {
field.setDocument((Document)model);
}
int size = HTML.getIntegerAttributeValue(attr, HTML.Attribute.SIZE,
-1);
field.setColumns((size > 0) ? size : 20);
JButton browseButton = new JButton(UIManager.getString
("FormView.browseFileButtonText"));
Box box = Box.createHorizontalBox();
box.add(field);
box.add(Box.createHorizontalStrut(5));
box.add(browseButton);
browseButton.addActionListener(new BrowseFileAction(
attr, (Document)model));
c = box;
maxIsPreferred = 3;
}
return c;
}
private void removeStaleListenerForModel(Object model) {
if (model instanceof DefaultButtonModel) {
// case of JButton whose model is DefaultButtonModel
// Need to remove stale ActionListener, ChangeListener and
// ItemListener that are instance of AbstractButton$Handler.
DefaultButtonModel buttonModel = (DefaultButtonModel) model;
String listenerClass = "javax.swing.AbstractButton$Handler";
for (ActionListener listener : buttonModel.getActionListeners()) {
if (listenerClass.equals(listener.getClass().getName())) {
buttonModel.removeActionListener(listener);
}
}
for (ChangeListener listener : buttonModel.getChangeListeners()) {
if (listenerClass.equals(listener.getClass().getName())) {
buttonModel.removeChangeListener(listener);
}
}
for (ItemListener listener : buttonModel.getItemListeners()) {
if (listenerClass.equals(listener.getClass().getName())) {
buttonModel.removeItemListener(listener);
}
}
} else if (model instanceof AbstractListModel) {
// case of JComboBox and JList
// For JList, the stale ListDataListener is instance
// BasicListUI$Handler.
// For JComboBox, there are 2 stale ListDataListeners, which are
// BasicListUI$Handler and BasicComboBoxUI$Handler.
AbstractListModel listModel = (AbstractListModel) model;
String listenerClass1 =
"javax.swing.plaf.basic.BasicListUI$Handler";
String listenerClass2 =
"javax.swing.plaf.basic.BasicComboBoxUI$Handler";
for (ListDataListener listener : listModel.getListDataListeners()) {
if (listenerClass1.equals(listener.getClass().getName())
|| listenerClass2.equals(listener.getClass().getName()))
{
listModel.removeListDataListener(listener);
}
}
} else if (model instanceof AbstractDocument) {
// case of JPasswordField, JTextField and JTextArea
// All have 2 stale DocumentListeners.
String listenerClass1 =
"javax.swing.plaf.basic.BasicTextUI$UpdateHandler";
String listenerClass2 =
"javax.swing.text.DefaultCaret$Handler";
AbstractDocument docModel = (AbstractDocument) model;
for (DocumentListener listener : docModel.getDocumentListeners()) {
if (listenerClass1.equals(listener.getClass().getName())
|| listenerClass2.equals(listener.getClass().getName()))
{
docModel.removeDocumentListener(listener);
}
}
}
}
/**
* Determines the maximum span for this view along an
* axis. For certain components, the maximum and preferred span are the
* same. For others this will return the value
* returned by Component.getMaximumSize along the
* axis of interest.
*
* @param axis may be either View.X_AXIS or View.Y_AXIS
* @return the span the view would like to be rendered into >= 0.
* Typically the view is told to render into the span
* that is returned, although there is no guarantee.
* The parent may choose to resize or break the view.
* @exception IllegalArgumentException for an invalid axis
*/
public float getMaximumSpan(int axis) {
switch (axis) {
case View.X_AXIS:
if ((maxIsPreferred & 1) == 1) {
super.getMaximumSpan(axis);
return getPreferredSpan(axis);
}
return super.getMaximumSpan(axis);
case View.Y_AXIS:
if ((maxIsPreferred & 2) == 2) {
super.getMaximumSpan(axis);
return getPreferredSpan(axis);
}
return super.getMaximumSpan(axis);
default:
break;
}
return super.getMaximumSpan(axis);
}
/**
* Responsible for processing the ActionEvent.
* If the element associated with the FormView,
* has a type of "submit", "reset", "text" or "password"
* then the action is processed. In the case of a "submit"
* the form is submitted. In the case of a "reset"
* the form is reset to its original state.
* In the case of "text" or "password", if the
* element is the last one of type "text" or "password",
* the form is submitted. Otherwise, focus is transferred
* to the next component in the form.
*
* @param evt the ActionEvent.
*/
public void actionPerformed(ActionEvent evt) {
Element element = getElement();
StringBuilder dataBuffer = new StringBuilder();
HTMLDocument doc = (HTMLDocument)getDocument();
AttributeSet attr = element.getAttributes();
String type = (String) attr.getAttribute(HTML.Attribute.TYPE);
if (type.equals("submit")) {
getFormData(dataBuffer);
submitData(dataBuffer.toString());
} else if (type.equals("reset")) {
resetForm();
} else if (type.equals("text") || type.equals("password")) {
if (isLastTextOrPasswordField()) {
getFormData(dataBuffer);
submitData(dataBuffer.toString());
} else {
getComponent().transferFocus();
}
}
}
/**
* This method is responsible for submitting the form data.
* A thread is forked to undertake the submission.
*/
protected void submitData(String data) {
Element form = getFormElement();
AttributeSet attrs = form.getAttributes();
HTMLDocument doc = (HTMLDocument) form.getDocument();
URL base = doc.getBase();
String target = (String) attrs.getAttribute(HTML.Attribute.TARGET);
if (target == null) {
target = "_self";
}
String method = (String) attrs.getAttribute(HTML.Attribute.METHOD);
if (method == null) {
method = "GET";
}
method = method.toLowerCase();
boolean isPostMethod = method.equals("post");
if (isPostMethod) {
storePostData(doc, target, data);
}
String action = (String) attrs.getAttribute(HTML.Attribute.ACTION);
URL actionURL;
try {
actionURL = (action == null)
? new URL(base.getProtocol(), base.getHost(),
base.getPort(), base.getFile())
: new URL(base, action);
if (!isPostMethod) {
String query = data.toString();
actionURL = new URL(actionURL + "?" + query);
}
} catch (MalformedURLException e) {
actionURL = null;
}
final JEditorPane c = (JEditorPane) getContainer();
HTMLEditorKit kit = (HTMLEditorKit) c.getEditorKit();
FormSubmitEvent formEvent = null;
if (!kit.isAutoFormSubmission() || doc.isFrameDocument()) {
FormSubmitEvent.MethodType methodType = isPostMethod
? FormSubmitEvent.MethodType.POST
: FormSubmitEvent.MethodType.GET;
formEvent = new FormSubmitEvent(
FormView.this, HyperlinkEvent.EventType.ACTIVATED,
actionURL, form, target, methodType, data);
}
// setPage() may take significant time so schedule it to run later.
final FormSubmitEvent fse = formEvent;
final URL url = actionURL;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (fse != null) {
c.fireHyperlinkUpdate(fse);
} else {
try {
c.setPage(url);
} catch (IOException e) {
UIManager.getLookAndFeel().provideErrorFeedback(c);
}
}
}
});
}
private void storePostData(HTMLDocument doc, String target, String data) {
/* POST data is stored into the document property named by constant
* PostDataProperty from where it is later retrieved by method
* JEditorPane.getPostData(). If the current document is in a frame,
* the data is initially put into the toplevel (frameset) document
* property (named <PostDataProperty>.<Target frame name>). It is the
* responsibility of FrameView which updates the target frame
* to move data from the frameset document property into the frame
* document property.
*/
Document propDoc = doc;
String propName = PostDataProperty;
if (doc.isFrameDocument()) {
// find the top-most JEditorPane holding the frameset view.
FrameView.FrameEditorPane p =
(FrameView.FrameEditorPane) getContainer();
FrameView v = p.getFrameView();
JEditorPane c = v.getOutermostJEditorPane();
if (c != null) {
propDoc = c.getDocument();
propName += ("." + target);
}
}
propDoc.putProperty(propName, data);
}
/**
* MouseEventListener class to handle form submissions when
* an input with type equal to image is clicked on.
* A MouseListener is necessary since along with the image
* data the coordinates associated with the mouse click
* need to be submitted.
*/
protected class MouseEventListener extends MouseAdapter {
public void mouseReleased(MouseEvent evt) {
String imageData = getImageData(evt.getPoint());
imageSubmit(imageData);
}
}
/**
* This method is called to submit a form in response
* to a click on an image -- an <INPUT> form
* element of type "image".
*
* @param imageData the mouse click coordinates.
*/
protected void imageSubmit(String imageData) {
StringBuilder dataBuffer = new StringBuilder();
Element elem = getElement();
HTMLDocument hdoc = (HTMLDocument)elem.getDocument();
getFormData(dataBuffer);
if (dataBuffer.length() > 0) {
dataBuffer.append('&');
}
dataBuffer.append(imageData);
submitData(dataBuffer.toString());
return;
}
/**
* Extracts the value of the name attribute
* associated with the input element of type
* image. If name is defined it is encoded using
* the URLEncoder.encode() method and the
* image data is returned in the following format:
* name + ".x" +"="+ x +"&"+ name +".y"+"="+ y
* otherwise,
* "x="+ x +"&y="+ y
*
* @param point associated with the mouse click.
* @return the image data.
*/
private String getImageData(Point point) {
String mouseCoords = point.x + ":" + point.y;
int sep = mouseCoords.indexOf(':');
String x = mouseCoords.substring(0, sep);
String y = mouseCoords.substring(++sep);
String name = (String) getElement().getAttributes().getAttribute(HTML.Attribute.NAME);
String data;
if (name == null || name.equals("")) {
data = "x="+ x +"&y="+ y;
} else {
name = URLEncoder.encode(name);
data = name + ".x" +"="+ x +"&"+ name +".y"+"="+ y;
}
return data;
}
/**
* The following methods provide functionality required to
* iterate over a the elements of the form and in the case
* of a form submission, extract the data from each model
* that is associated with each form element, and in the
* case of reset, reinitialize the each model to its
* initial state.
*/
/**
* Returns the Element representing the <code>FORM</code>.
*/
private Element getFormElement() {
Element elem = getElement();
while (elem != null) {
if (elem.getAttributes().getAttribute
(StyleConstants.NameAttribute) == HTML.Tag.FORM) {
return elem;
}
elem = elem.getParentElement();
}
return null;
}
/**
* Iterates over the
* element hierarchy, extracting data from the
* models associated with the relevant form elements.
* "Relevant" means the form elements that are part
* of the same form whose element triggered the submit
* action.
*
* @param buffer the buffer that contains that data to submit
* @param targetElement the element that triggered the
* form submission
*/
private void getFormData(StringBuilder buffer) {
Element formE = getFormElement();
if (formE != null) {
ElementIterator it = new ElementIterator(formE);
Element next;
while ((next = it.next()) != null) {
if (isControl(next)) {
String type = (String)next.getAttributes().getAttribute
(HTML.Attribute.TYPE);
if (type != null && type.equals("submit") &&
next != getElement()) {
// do nothing - this submit is not the trigger
} else if (type == null || !type.equals("image")) {
// images only result in data if they triggered
// the submit and they require that the mouse click
// coords be appended to the data. Hence its
// processing is handled by the view.
loadElementDataIntoBuffer(next, buffer);
}
}
}
}
}
/**
* Loads the data
* associated with the element into the buffer.
* The format in which data is appended depends
* on the type of the form element. Essentially
* data is loaded in name/value pairs.
*
*/
private void loadElementDataIntoBuffer(Element elem, StringBuilder buffer) {
AttributeSet attr = elem.getAttributes();
String name = (String)attr.getAttribute(HTML.Attribute.NAME);
if (name == null) {
return;
}
String value = null;
HTML.Tag tag = (HTML.Tag)elem.getAttributes().getAttribute
(StyleConstants.NameAttribute);
if (tag == HTML.Tag.INPUT) {
value = getInputElementData(attr);
} else if (tag == HTML.Tag.TEXTAREA) {
value = getTextAreaData(attr);
} else if (tag == HTML.Tag.SELECT) {
loadSelectData(attr, buffer);
}
if (name != null && value != null) {
appendBuffer(buffer, name, value);
}
}
/**
* Returns the data associated with an <INPUT> form
* element. The value of "type" attributes is
* used to determine the type of the model associated
* with the element and then the relevant data is
* extracted.
*/
private String getInputElementData(AttributeSet attr) {
Object model = attr.getAttribute(StyleConstants.ModelAttribute);
String type = (String) attr.getAttribute(HTML.Attribute.TYPE);
String value = null;
if (type.equals("text") || type.equals("password")) {
Document doc = (Document)model;
try {
value = doc.getText(0, doc.getLength());
} catch (BadLocationException e) {
value = null;
}
} else if (type.equals("submit") || type.equals("hidden")) {
value = (String) attr.getAttribute(HTML.Attribute.VALUE);
if (value == null) {
value = "";
}
} else if (type.equals("radio") || type.equals("checkbox")) {
ButtonModel m = (ButtonModel)model;
if (m.isSelected()) {
value = (String) attr.getAttribute(HTML.Attribute.VALUE);
if (value == null) {
value = "on";
}
}
} else if (type.equals("file")) {
Document doc = (Document)model;
String path;
try {
path = doc.getText(0, doc.getLength());
} catch (BadLocationException e) {
path = null;
}
if (path != null && path.length() > 0) {
value = path;
}
}
return value;
}
/**
* Returns the data associated with the <TEXTAREA> form
* element. This is done by getting the text stored in the
* Document model.
*/
private String getTextAreaData(AttributeSet attr) {
Document doc = (Document)attr.getAttribute(StyleConstants.ModelAttribute);
try {
return doc.getText(0, doc.getLength());
} catch (BadLocationException e) {
return null;
}
}
/**
* Loads the buffer with the data associated with the Select
* form element. Basically, only items that are selected
* and have their name attribute set are added to the buffer.
*/
private void loadSelectData(AttributeSet attr, StringBuilder buffer) {
String name = (String)attr.getAttribute(HTML.Attribute.NAME);
if (name == null) {
return;
}
Object m = attr.getAttribute(StyleConstants.ModelAttribute);
if (m instanceof OptionListModel) {
OptionListModel<Option> model = (OptionListModel<Option>) m;
for (int i = 0; i < model.getSize(); i++) {
if (model.isSelectedIndex(i)) {
Option option = model.getElementAt(i);
appendBuffer(buffer, name, option.getValue());
}
}
} else if (m instanceof ComboBoxModel) {
ComboBoxModel model = (ComboBoxModel)m;
Option option = (Option)model.getSelectedItem();
if (option != null) {
appendBuffer(buffer, name, option.getValue());
}
}
}
/**
* Appends name / value pairs into the
* buffer. Both names and values are encoded using the
* URLEncoder.encode() method before being added to the
* buffer.
*/
private void appendBuffer(StringBuilder buffer, String name, String value) {
if (buffer.length() > 0) {
buffer.append('&');
}
String encodedName = URLEncoder.encode(name);
buffer.append(encodedName);
buffer.append('=');
String encodedValue = URLEncoder.encode(value);
buffer.append(encodedValue);
}
/**
* Returns true if the Element <code>elem</code> represents a control.
*/
private boolean isControl(Element elem) {
return elem.isLeaf();
}
/**
* Iterates over the element hierarchy to determine if
* the element parameter, which is assumed to be an
* <INPUT> element of type password or text, is the last
* one of either kind, in the form to which it belongs.
*/
boolean isLastTextOrPasswordField() {
Element parent = getFormElement();
Element elem = getElement();
if (parent != null) {
ElementIterator it = new ElementIterator(parent);
Element next;
boolean found = false;
while ((next = it.next()) != null) {
if (next == elem) {
found = true;
}
else if (found && isControl(next)) {
AttributeSet elemAttr = next.getAttributes();
if (HTMLDocument.matchNameAttribute
(elemAttr, HTML.Tag.INPUT)) {
String type = (String)elemAttr.getAttribute
(HTML.Attribute.TYPE);
if ("text".equals(type) || "password".equals(type)) {
return false;
}
}
}
}
}
return true;
}
/**
* Resets the form
* to its initial state by reinitializing the models
* associated with each form element to their initial
* values.
*
* param elem the element that triggered the reset
*/
void resetForm() {
Element parent = getFormElement();
if (parent != null) {
ElementIterator it = new ElementIterator(parent);
Element next;
while((next = it.next()) != null) {
if (isControl(next)) {
AttributeSet elemAttr = next.getAttributes();
Object m = elemAttr.getAttribute(StyleConstants.
ModelAttribute);
if (m instanceof TextAreaDocument) {
TextAreaDocument doc = (TextAreaDocument)m;
doc.reset();
} else if (m instanceof PlainDocument) {
try {
PlainDocument doc = (PlainDocument)m;
doc.remove(0, doc.getLength());
if (HTMLDocument.matchNameAttribute
(elemAttr, HTML.Tag.INPUT)) {
String value = (String)elemAttr.
getAttribute(HTML.Attribute.VALUE);
if (value != null) {
doc.insertString(0, value, null);
}
}
} catch (BadLocationException e) {
}
} else if (m instanceof OptionListModel) {
OptionListModel model = (OptionListModel) m;
int size = model.getSize();
for (int i = 0; i < size; i++) {
model.removeIndexInterval(i, i);
}
BitSet selectionRange = model.getInitialSelection();
for (int i = 0; i < selectionRange.size(); i++) {
if (selectionRange.get(i)) {
model.addSelectionInterval(i, i);
}
}
} else if (m instanceof OptionComboBoxModel) {
OptionComboBoxModel model = (OptionComboBoxModel) m;
Option option = model.getInitialSelection();
if (option != null) {
model.setSelectedItem(option);
}
} else if (m instanceof JToggleButton.ToggleButtonModel) {
boolean checked = ((String)elemAttr.getAttribute
(HTML.Attribute.CHECKED) != null);
JToggleButton.ToggleButtonModel model =
(JToggleButton.ToggleButtonModel)m;
model.setSelected(checked);
}
}
}
}
}
/**
* BrowseFileAction is used for input type == file. When the user
* clicks the button a JFileChooser is brought up allowing the user
* to select a file in the file system. The resulting path to the selected
* file is set in the text field (actually an instance of Document).
*/
private class BrowseFileAction implements ActionListener {
private AttributeSet attrs;
private Document model;
BrowseFileAction(AttributeSet attrs, Document model) {
this.attrs = attrs;
this.model = model;
}
public void actionPerformed(ActionEvent ae) {
// PENDING: When mime support is added to JFileChooser use the
// accept value of attrs.
JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(false);
if (fc.showOpenDialog(getContainer()) ==
JFileChooser.APPROVE_OPTION) {
File selected = fc.getSelectedFile();
if (selected != null) {
try {
if (model.getLength() > 0) {
model.remove(0, model.getLength());
}
model.insertString(0, selected.getPath(), null);
} catch (BadLocationException ble) {}
}
}
}
}
}
|
openjdk/jdk8 | 36,791 | jdk/src/share/classes/sun/awt/AppContext.java | /*
* Copyright (c) 1998, 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 sun.awt;
import java.awt.EventQueue;
import java.awt.Window;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.Toolkit;
import java.awt.GraphicsEnvironment;
import java.awt.event.InvocationEvent;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyChangeListener;
import sun.util.logging.PlatformLogger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.atomic.AtomicInteger;
/**
* The AppContext is a table referenced by ThreadGroup which stores
* application service instances. (If you are not writing an application
* service, or don't know what one is, please do not use this class.)
* The AppContext allows applet access to what would otherwise be
* potentially dangerous services, such as the ability to peek at
* EventQueues or change the look-and-feel of a Swing application.<p>
*
* Most application services use a singleton object to provide their
* services, either as a default (such as getSystemEventQueue or
* getDefaultToolkit) or as static methods with class data (System).
* The AppContext works with the former method by extending the concept
* of "default" to be ThreadGroup-specific. Application services
* lookup their singleton in the AppContext.<p>
*
* For example, here we have a Foo service, with its pre-AppContext
* code:<p>
* <code><pre>
* public class Foo {
* private static Foo defaultFoo = new Foo();
*
* public static Foo getDefaultFoo() {
* return defaultFoo;
* }
*
* ... Foo service methods
* }</pre></code><p>
*
* The problem with the above is that the Foo service is global in scope,
* so that applets and other untrusted code can execute methods on the
* single, shared Foo instance. The Foo service therefore either needs
* to block its use by untrusted code using a SecurityManager test, or
* restrict its capabilities so that it doesn't matter if untrusted code
* executes it.<p>
*
* Here's the Foo class written to use the AppContext:<p>
* <code><pre>
* public class Foo {
* public static Foo getDefaultFoo() {
* Foo foo = (Foo)AppContext.getAppContext().get(Foo.class);
* if (foo == null) {
* foo = new Foo();
* getAppContext().put(Foo.class, foo);
* }
* return foo;
* }
*
* ... Foo service methods
* }</pre></code><p>
*
* Since a separate AppContext can exist for each ThreadGroup, trusted
* and untrusted code have access to different Foo instances. This allows
* untrusted code access to "system-wide" services -- the service remains
* within the AppContext "sandbox". For example, say a malicious applet
* wants to peek all of the key events on the EventQueue to listen for
* passwords; if separate EventQueues are used for each ThreadGroup
* using AppContexts, the only key events that applet will be able to
* listen to are its own. A more reasonable applet request would be to
* change the Swing default look-and-feel; with that default stored in
* an AppContext, the applet's look-and-feel will change without
* disrupting other applets or potentially the browser itself.<p>
*
* Because the AppContext is a facility for safely extending application
* service support to applets, none of its methods may be blocked by a
* a SecurityManager check in a valid Java implementation. Applets may
* therefore safely invoke any of its methods without worry of being
* blocked.
*
* Note: If a SecurityManager is installed which derives from
* sun.awt.AWTSecurityManager, it may override the
* AWTSecurityManager.getAppContext() method to return the proper
* AppContext based on the execution context, in the case where
* the default ThreadGroup-based AppContext indexing would return
* the main "system" AppContext. For example, in an applet situation,
* if a system thread calls into an applet, rather than returning the
* main "system" AppContext (the one corresponding to the system thread),
* an installed AWTSecurityManager may return the applet's AppContext
* based on the execution context.
*
* @author Thomas Ball
* @author Fred Ecks
*/
public final class AppContext {
private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.AppContext");
/* Since the contents of an AppContext are unique to each Java
* session, this class should never be serialized. */
/*
* The key to put()/get() the Java EventQueue into/from the AppContext.
*/
public static final Object EVENT_QUEUE_KEY = new StringBuffer("EventQueue");
/*
* The keys to store EventQueue push/pop lock and condition.
*/
public final static Object EVENT_QUEUE_LOCK_KEY = new StringBuilder("EventQueue.Lock");
public final static Object EVENT_QUEUE_COND_KEY = new StringBuilder("EventQueue.Condition");
/* A map of AppContexts, referenced by ThreadGroup.
*/
private static final Map<ThreadGroup, AppContext> threadGroup2appContext =
Collections.synchronizedMap(new IdentityHashMap<ThreadGroup, AppContext>());
/**
* Returns a set containing all <code>AppContext</code>s.
*/
public static Set<AppContext> getAppContexts() {
synchronized (threadGroup2appContext) {
return new HashSet<AppContext>(threadGroup2appContext.values());
}
}
/* The main "system" AppContext, used by everything not otherwise
contained in another AppContext. It is implicitly created for
standalone apps only (i.e. not applets)
*/
private static volatile AppContext mainAppContext = null;
private static class GetAppContextLock {};
private final static Object getAppContextLock = new GetAppContextLock();
/*
* The hash map associated with this AppContext. A private delegate
* is used instead of subclassing HashMap so as to avoid all of
* HashMap's potentially risky methods, such as clear(), elements(),
* putAll(), etc.
*/
private final Map<Object, Object> table = new HashMap<>();
private final ThreadGroup threadGroup;
/**
* If any <code>PropertyChangeListeners</code> have been registered,
* the <code>changeSupport</code> field describes them.
*
* @see #addPropertyChangeListener
* @see #removePropertyChangeListener
* @see #firePropertyChange
*/
private PropertyChangeSupport changeSupport = null;
public static final String DISPOSED_PROPERTY_NAME = "disposed";
public static final String GUI_DISPOSED = "guidisposed";
private enum State {
VALID,
BEING_DISPOSED,
DISPOSED
};
private volatile State state = State.VALID;
public boolean isDisposed() {
return state == State.DISPOSED;
}
/*
* The total number of AppContexts, system-wide. This number is
* incremented at the beginning of the constructor, and decremented
* at the end of dispose(). getAppContext() checks to see if this
* number is 1. If so, it returns the sole AppContext without
* checking Thread.currentThread().
*/
private static final AtomicInteger numAppContexts = new AtomicInteger(0);
/*
* The context ClassLoader that was used to create this AppContext.
*/
private final ClassLoader contextClassLoader;
/**
* Constructor for AppContext. This method is <i>not</i> public,
* nor should it ever be used as such. The proper way to construct
* an AppContext is through the use of SunToolkit.createNewAppContext.
* A ThreadGroup is created for the new AppContext, a Thread is
* created within that ThreadGroup, and that Thread calls
* SunToolkit.createNewAppContext before calling anything else.
* That creates both the new AppContext and its EventQueue.
*
* @param threadGroup The ThreadGroup for the new AppContext
* @see sun.awt.SunToolkit
* @since 1.2
*/
AppContext(ThreadGroup threadGroup) {
numAppContexts.incrementAndGet();
this.threadGroup = threadGroup;
threadGroup2appContext.put(threadGroup, this);
this.contextClassLoader =
AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return Thread.currentThread().getContextClassLoader();
}
});
// Initialize push/pop lock and its condition to be used by all the
// EventQueues within this AppContext
Lock eventQueuePushPopLock = new ReentrantLock();
put(EVENT_QUEUE_LOCK_KEY, eventQueuePushPopLock);
Condition eventQueuePushPopCond = eventQueuePushPopLock.newCondition();
put(EVENT_QUEUE_COND_KEY, eventQueuePushPopCond);
}
private static final ThreadLocal<AppContext> threadAppContext =
new ThreadLocal<AppContext>();
private final static void initMainAppContext() {
// On the main Thread, we get the ThreadGroup, make a corresponding
// AppContext, and instantiate the Java EventQueue. This way, legacy
// code is unaffected by the move to multiple AppContext ability.
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
ThreadGroup currentThreadGroup =
Thread.currentThread().getThreadGroup();
ThreadGroup parentThreadGroup = currentThreadGroup.getParent();
while (parentThreadGroup != null) {
// Find the root ThreadGroup to construct our main AppContext
currentThreadGroup = parentThreadGroup;
parentThreadGroup = currentThreadGroup.getParent();
}
mainAppContext = SunToolkit.createNewAppContext(currentThreadGroup);
return null;
}
});
}
/**
* Returns the appropriate AppContext for the caller,
* as determined by its ThreadGroup. If the main "system" AppContext
* would be returned and there's an AWTSecurityManager installed, it
* is called to get the proper AppContext based on the execution
* context.
*
* @return the AppContext for the caller.
* @see java.lang.ThreadGroup
* @since 1.2
*/
public final static AppContext getAppContext() {
// we are standalone app, return the main app context
if (numAppContexts.get() == 1 && mainAppContext != null) {
return mainAppContext;
}
AppContext appContext = threadAppContext.get();
if (null == appContext) {
appContext = AccessController.doPrivileged(new PrivilegedAction<AppContext>()
{
public AppContext run() {
// Get the current ThreadGroup, and look for it and its
// parents in the hash from ThreadGroup to AppContext --
// it should be found, because we use createNewContext()
// when new AppContext objects are created.
ThreadGroup currentThreadGroup = Thread.currentThread().getThreadGroup();
ThreadGroup threadGroup = currentThreadGroup;
// Special case: we implicitly create the main app context
// if no contexts have been created yet. This covers standalone apps
// and excludes applets because by the time applet starts
// a number of contexts have already been created by the plugin.
synchronized (getAppContextLock) {
if (numAppContexts.get() == 0) {
if (System.getProperty("javaplugin.version") == null &&
System.getProperty("javawebstart.version") == null) {
initMainAppContext();
} else if (System.getProperty("javafx.version") != null &&
threadGroup.getParent() != null) {
// Swing inside JavaFX case
SunToolkit.createNewAppContext();
}
}
}
AppContext context = threadGroup2appContext.get(threadGroup);
while (context == null) {
threadGroup = threadGroup.getParent();
if (threadGroup == null) {
return null;
}
context = threadGroup2appContext.get(threadGroup);
}
// In case we did anything in the above while loop, we add
// all the intermediate ThreadGroups to threadGroup2appContext
// so we won't spin again.
for (ThreadGroup tg = currentThreadGroup; tg != threadGroup; tg = tg.getParent()) {
threadGroup2appContext.put(tg, context);
}
// Now we're done, so we cache the latest key/value pair.
threadAppContext.set(context);
return context;
}
});
}
return appContext;
}
/**
* Returns true if the specified AppContext is the main AppContext.
*
* @param ctx the context to compare with the main context
* @return true if the specified AppContext is the main AppContext.
* @since 1.8
*/
public final static boolean isMainContext(AppContext ctx) {
return (ctx != null && ctx == mainAppContext);
}
private final static AppContext getExecutionAppContext() {
SecurityManager securityManager = System.getSecurityManager();
if ((securityManager != null) &&
(securityManager instanceof AWTSecurityManager))
{
AWTSecurityManager awtSecMgr = (AWTSecurityManager) securityManager;
AppContext secAppContext = awtSecMgr.getAppContext();
return secAppContext; // Return what we're told
}
return null;
}
private long DISPOSAL_TIMEOUT = 5000; // Default to 5-second timeout
// for disposal of all Frames
// (we wait for this time twice,
// once for dispose(), and once
// to clear the EventQueue).
private long THREAD_INTERRUPT_TIMEOUT = 1000;
// Default to 1-second timeout for all
// interrupted Threads to exit, and another
// 1 second for all stopped Threads to die.
/**
* Disposes of this AppContext, all of its top-level Frames, and
* all Threads and ThreadGroups contained within it.
*
* This method must be called from a Thread which is not contained
* within this AppContext.
*
* @exception IllegalThreadStateException if the current thread is
* contained within this AppContext
* @since 1.2
*/
public void dispose() throws IllegalThreadStateException {
// Check to be sure that the current Thread isn't in this AppContext
if (this.threadGroup.parentOf(Thread.currentThread().getThreadGroup())) {
throw new IllegalThreadStateException(
"Current Thread is contained within AppContext to be disposed."
);
}
synchronized(this) {
if (this.state != State.VALID) {
return; // If already disposed or being disposed, bail.
}
this.state = State.BEING_DISPOSED;
}
final PropertyChangeSupport changeSupport = this.changeSupport;
if (changeSupport != null) {
changeSupport.firePropertyChange(DISPOSED_PROPERTY_NAME, false, true);
}
// First, we post an InvocationEvent to be run on the
// EventDispatchThread which disposes of all top-level Frames and TrayIcons
final Object notificationLock = new Object();
Runnable runnable = new Runnable() {
public void run() {
Window[] windowsToDispose = Window.getOwnerlessWindows();
for (Window w : windowsToDispose) {
try {
w.dispose();
} catch (Throwable t) {
log.finer("exception occurred while disposing app context", t);
}
}
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
if (!GraphicsEnvironment.isHeadless() && SystemTray.isSupported())
{
SystemTray systemTray = SystemTray.getSystemTray();
TrayIcon[] trayIconsToDispose = systemTray.getTrayIcons();
for (TrayIcon ti : trayIconsToDispose) {
systemTray.remove(ti);
}
}
return null;
}
});
// Alert PropertyChangeListeners that the GUI has been disposed.
if (changeSupport != null) {
changeSupport.firePropertyChange(GUI_DISPOSED, false, true);
}
synchronized(notificationLock) {
notificationLock.notifyAll(); // Notify caller that we're done
}
}
};
synchronized(notificationLock) {
SunToolkit.postEvent(this,
new InvocationEvent(Toolkit.getDefaultToolkit(), runnable));
try {
notificationLock.wait(DISPOSAL_TIMEOUT);
} catch (InterruptedException e) { }
}
// Next, we post another InvocationEvent to the end of the
// EventQueue. When it's executed, we know we've executed all
// events in the queue.
runnable = new Runnable() { public void run() {
synchronized(notificationLock) {
notificationLock.notifyAll(); // Notify caller that we're done
}
} };
synchronized(notificationLock) {
SunToolkit.postEvent(this,
new InvocationEvent(Toolkit.getDefaultToolkit(), runnable));
try {
notificationLock.wait(DISPOSAL_TIMEOUT);
} catch (InterruptedException e) { }
}
// We are done with posting events, so change the state to disposed
synchronized(this) {
this.state = State.DISPOSED;
}
// Next, we interrupt all Threads in the ThreadGroup
this.threadGroup.interrupt();
// Note, the EventDispatchThread we've interrupted may dump an
// InterruptedException to the console here. This needs to be
// fixed in the EventDispatchThread, not here.
// Next, we sleep 10ms at a time, waiting for all of the active
// Threads in the ThreadGroup to exit.
long startTime = System.currentTimeMillis();
long endTime = startTime + THREAD_INTERRUPT_TIMEOUT;
while ((this.threadGroup.activeCount() > 0) &&
(System.currentTimeMillis() < endTime)) {
try {
Thread.sleep(10);
} catch (InterruptedException e) { }
}
// Then, we stop any remaining Threads
this.threadGroup.stop();
// Next, we sleep 10ms at a time, waiting for all of the active
// Threads in the ThreadGroup to die.
startTime = System.currentTimeMillis();
endTime = startTime + THREAD_INTERRUPT_TIMEOUT;
while ((this.threadGroup.activeCount() > 0) &&
(System.currentTimeMillis() < endTime)) {
try {
Thread.sleep(10);
} catch (InterruptedException e) { }
}
// Next, we remove this and all subThreadGroups from threadGroup2appContext
int numSubGroups = this.threadGroup.activeGroupCount();
if (numSubGroups > 0) {
ThreadGroup [] subGroups = new ThreadGroup[numSubGroups];
numSubGroups = this.threadGroup.enumerate(subGroups);
for (int subGroup = 0; subGroup < numSubGroups; subGroup++) {
threadGroup2appContext.remove(subGroups[subGroup]);
}
}
threadGroup2appContext.remove(this.threadGroup);
threadAppContext.set(null);
// Finally, we destroy the ThreadGroup entirely.
try {
this.threadGroup.destroy();
} catch (IllegalThreadStateException e) {
// Fired if not all the Threads died, ignore it and proceed
}
synchronized (table) {
this.table.clear(); // Clear out the Hashtable to ease garbage collection
}
numAppContexts.decrementAndGet();
mostRecentKeyValue = null;
}
static final class PostShutdownEventRunnable implements Runnable {
private final AppContext appContext;
public PostShutdownEventRunnable(AppContext ac) {
appContext = ac;
}
public void run() {
final EventQueue eq = (EventQueue)appContext.get(EVENT_QUEUE_KEY);
if (eq != null) {
eq.postEvent(AWTAutoShutdown.getShutdownEvent());
}
}
}
static final class CreateThreadAction implements PrivilegedAction<Thread> {
private final AppContext appContext;
private final Runnable runnable;
public CreateThreadAction(AppContext ac, Runnable r) {
appContext = ac;
runnable = r;
}
public Thread run() {
Thread t = new Thread(appContext.getThreadGroup(), runnable);
t.setContextClassLoader(appContext.getContextClassLoader());
t.setPriority(Thread.NORM_PRIORITY + 1);
t.setDaemon(true);
return t;
}
}
static void stopEventDispatchThreads() {
for (AppContext appContext: getAppContexts()) {
if (appContext.isDisposed()) {
continue;
}
Runnable r = new PostShutdownEventRunnable(appContext);
// For security reasons EventQueue.postEvent should only be called
// on a thread that belongs to the corresponding thread group.
if (appContext != AppContext.getAppContext()) {
// Create a thread that belongs to the thread group associated
// with the AppContext and invokes EventQueue.postEvent.
PrivilegedAction<Thread> action = new CreateThreadAction(appContext, r);
Thread thread = AccessController.doPrivileged(action);
thread.start();
} else {
r.run();
}
}
}
private MostRecentKeyValue mostRecentKeyValue = null;
private MostRecentKeyValue shadowMostRecentKeyValue = null;
/**
* Returns the value to which the specified key is mapped in this context.
*
* @param key a key in the AppContext.
* @return the value to which the key is mapped in this AppContext;
* <code>null</code> if the key is not mapped to any value.
* @see #put(Object, Object)
* @since 1.2
*/
public Object get(Object key) {
/*
* The most recent reference should be updated inside a synchronized
* block to avoid a race when put() and get() are executed in
* parallel on different threads.
*/
synchronized (table) {
// Note: this most recent key/value caching is thread-hot.
// A simple test using SwingSet found that 72% of lookups
// were matched using the most recent key/value. By instantiating
// a simple MostRecentKeyValue object on cache misses, the
// cache hits can be processed without synchronization.
MostRecentKeyValue recent = mostRecentKeyValue;
if ((recent != null) && (recent.key == key)) {
return recent.value;
}
Object value = table.get(key);
if(mostRecentKeyValue == null) {
mostRecentKeyValue = new MostRecentKeyValue(key, value);
shadowMostRecentKeyValue = new MostRecentKeyValue(key, value);
} else {
MostRecentKeyValue auxKeyValue = mostRecentKeyValue;
shadowMostRecentKeyValue.setPair(key, value);
mostRecentKeyValue = shadowMostRecentKeyValue;
shadowMostRecentKeyValue = auxKeyValue;
}
return value;
}
}
/**
* Maps the specified <code>key</code> to the specified
* <code>value</code> in this AppContext. Neither the key nor the
* value can be <code>null</code>.
* <p>
* The value can be retrieved by calling the <code>get</code> method
* with a key that is equal to the original key.
*
* @param key the AppContext key.
* @param value the value.
* @return the previous value of the specified key in this
* AppContext, or <code>null</code> if it did not have one.
* @exception NullPointerException if the key or value is
* <code>null</code>.
* @see #get(Object)
* @since 1.2
*/
public Object put(Object key, Object value) {
synchronized (table) {
MostRecentKeyValue recent = mostRecentKeyValue;
if ((recent != null) && (recent.key == key))
recent.value = value;
return table.put(key, value);
}
}
/**
* Removes the key (and its corresponding value) from this
* AppContext. This method does nothing if the key is not in the
* AppContext.
*
* @param key the key that needs to be removed.
* @return the value to which the key had been mapped in this AppContext,
* or <code>null</code> if the key did not have a mapping.
* @since 1.2
*/
public Object remove(Object key) {
synchronized (table) {
MostRecentKeyValue recent = mostRecentKeyValue;
if ((recent != null) && (recent.key == key))
recent.value = null;
return table.remove(key);
}
}
/**
* Returns the root ThreadGroup for all Threads contained within
* this AppContext.
* @since 1.2
*/
public ThreadGroup getThreadGroup() {
return threadGroup;
}
/**
* Returns the context ClassLoader that was used to create this
* AppContext.
*
* @see java.lang.Thread#getContextClassLoader
*/
public ClassLoader getContextClassLoader() {
return contextClassLoader;
}
/**
* Returns a string representation of this AppContext.
* @since 1.2
*/
@Override
public String toString() {
return getClass().getName() + "[threadGroup=" + threadGroup.getName() + "]";
}
/**
* Returns an array of all the property change listeners
* registered on this component.
*
* @return all of this component's <code>PropertyChangeListener</code>s
* or an empty array if no property change
* listeners are currently registered
*
* @see #addPropertyChangeListener
* @see #removePropertyChangeListener
* @see #getPropertyChangeListeners(java.lang.String)
* @see java.beans.PropertyChangeSupport#getPropertyChangeListeners
* @since 1.4
*/
public synchronized PropertyChangeListener[] getPropertyChangeListeners() {
if (changeSupport == null) {
return new PropertyChangeListener[0];
}
return changeSupport.getPropertyChangeListeners();
}
/**
* Adds a PropertyChangeListener to the listener list for a specific
* property. The specified property may be one of the following:
* <ul>
* <li>if this AppContext is disposed ("disposed")</li>
* </ul>
* <ul>
* <li>if this AppContext's unowned Windows have been disposed
* ("guidisposed"). Code to cleanup after the GUI is disposed
* (such as LookAndFeel.uninitialize()) should execute in response to
* this property being fired. Notifications for the "guidisposed"
* property are sent on the event dispatch thread.</li>
* </ul>
* <p>
* If listener is null, no exception is thrown and no action is performed.
*
* @param propertyName one of the property names listed above
* @param listener the PropertyChangeListener to be added
*
* @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
* @see #getPropertyChangeListeners(java.lang.String)
* @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
*/
public synchronized void addPropertyChangeListener(
String propertyName,
PropertyChangeListener listener) {
if (listener == null) {
return;
}
if (changeSupport == null) {
changeSupport = new PropertyChangeSupport(this);
}
changeSupport.addPropertyChangeListener(propertyName, listener);
}
/**
* Removes a PropertyChangeListener from the listener list for a specific
* property. This method should be used to remove PropertyChangeListeners
* that were registered for a specific bound property.
* <p>
* If listener is null, no exception is thrown and no action is performed.
*
* @param propertyName a valid property name
* @param listener the PropertyChangeListener to be removed
*
* @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
* @see #getPropertyChangeListeners(java.lang.String)
* @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
*/
public synchronized void removePropertyChangeListener(
String propertyName,
PropertyChangeListener listener) {
if (listener == null || changeSupport == null) {
return;
}
changeSupport.removePropertyChangeListener(propertyName, listener);
}
/**
* Returns an array of all the listeners which have been associated
* with the named property.
*
* @return all of the <code>PropertyChangeListeners</code> associated with
* the named property or an empty array if no listeners have
* been added
*
* @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
* @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
* @see #getPropertyChangeListeners
* @since 1.4
*/
public synchronized PropertyChangeListener[] getPropertyChangeListeners(
String propertyName) {
if (changeSupport == null) {
return new PropertyChangeListener[0];
}
return changeSupport.getPropertyChangeListeners(propertyName);
}
// Set up JavaAWTAccess in SharedSecrets
static {
sun.misc.SharedSecrets.setJavaAWTAccess(new sun.misc.JavaAWTAccess() {
private boolean hasRootThreadGroup(final AppContext ecx) {
return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return ecx.threadGroup.getParent() == null;
}
});
}
/**
* Returns the AppContext used for applet logging isolation, or null if
* the default global context can be used.
* If there's no applet, or if the caller is a stand alone application,
* or running in the main app context, returns null.
* Otherwise, returns the AppContext of the calling applet.
* @return null if the global default context can be used,
* an AppContext otherwise.
**/
public Object getAppletContext() {
// There's no AppContext: return null.
// No need to call getAppContext() if numAppContext == 0:
// it means that no AppContext has been created yet, and
// we don't want to trigger the creation of a main app
// context since we don't need it.
if (numAppContexts.get() == 0) return null;
// Get the context from the security manager
AppContext ecx = getExecutionAppContext();
// Not sure we really need to re-check numAppContexts here.
// If all applets have gone away then we could have a
// numAppContexts coming back to 0. So we recheck
// it here because we don't want to trigger the
// creation of a main AppContext in that case.
// This is probably not 100% MT-safe but should reduce
// the window of opportunity in which that issue could
// happen.
if (numAppContexts.get() > 0) {
// Defaults to thread group caching.
// This is probably not required as we only really need
// isolation in a deployed applet environment, in which
// case ecx will not be null when we reach here
// However it helps emulate the deployed environment,
// in tests for instance.
ecx = ecx != null ? ecx : getAppContext();
}
// getAppletContext() may be called when initializing the main
// app context - in which case mainAppContext will still be
// null. To work around this issue we simply use
// AppContext.threadGroup.getParent() == null instead, since
// mainAppContext is the only AppContext which should have
// the root TG as its thread group.
// See: JDK-8023258
final boolean isMainAppContext = ecx == null
|| mainAppContext == ecx
|| mainAppContext == null && hasRootThreadGroup(ecx);
return isMainAppContext ? null : ecx;
}
});
}
}
final class MostRecentKeyValue {
Object key;
Object value;
MostRecentKeyValue(Object k, Object v) {
key = k;
value = v;
}
void setPair(Object k, Object v) {
key = k;
value = v;
}
}
|
apache/harmony | 36,550 | classlib/modules/swing/src/test/api/java.injected/javax/swing/text/UtilitiesTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Evgeniya G. Maenkova
*/
package javax.swing.text;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.text.BreakIterator;
import java.text.CharacterIterator;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingTestCase;
import javax.swing.plaf.basic.BasicTextUI;
public class UtilitiesTest extends SwingTestCase {
JTextComponent textComponent;
TabExp te = new TabExp();
JFrame jf;
//not implemented
//JEditorPane jtp;
//not implemented
//JTextPane jtp;
JTextArea jta;
JTextField jtf;
Document doc_jta;
Document doc_jtp;
Document doc_jtf;
String sLTR = "aaaa";
String sRTL = "\u05dc" + "\u05dc" + "\u05dc" + "\u05dc";
boolean bWasException;
String message;
class TabExp implements TabExpander {
public float nextTabStop(final float f, final int i) {
//System.out.println(" " + f + " " + i);
return f + i;
}
}
@Override
protected void setUp() throws Exception {
super.setUp();
timeoutDelay = 10 * DEFAULT_TIMEOUT_DELAY;
bWasException = false;
message = null;
String content = sRTL + "\t" + sLTR + "\t" + sRTL + "\t\t" + sLTR + "\n" + sLTR + "\t "
+ sLTR + " \t " + sLTR + sRTL + sRTL + sRTL + sRTL + "\n" + sRTL + " " + sRTL
+ " " + sRTL + "\n" + sRTL + " " + sRTL + "; " + sRTL + "\n" + sRTL + ";"
+ sLTR + " \t" + sRTL + "\t" + sRTL + " " + sRTL + ",";
jf = new JFrame();
jta = new JTextArea(content);
jtf = new JTextField(content);
//jtp = new JTextPane();
//jtp.setText(content);
doc_jta = jta.getDocument();
//doc_jtp = jtp.getDocument();
doc_jtf = jtf.getDocument();
//setContent();
jf.getContentPane().setLayout(new GridLayout(2, 2));
jf.getContentPane().add(jta);
jf.getContentPane().add(jtf);
//jf.getContentPane().add(jtp);
jf.setSize(400, 500);
jf.pack();
}
protected void setContent() {
String str[] = { "Draws the given text, expanding any tabs",
"that are contained using the given tab expansion technique",
"Determines the width of the given segment of text taking",
"Draws the given text, expanding any tabs", };
SimpleAttributeSet[] attrs = new SimpleAttributeSet[4];
attrs[0] = new SimpleAttributeSet();
StyleConstants.setFontFamily(attrs[0], "SansSerif");
StyleConstants.setFontSize(attrs[0], 16);
attrs[1] = new SimpleAttributeSet(attrs[0]);
StyleConstants.setBold(attrs[1], true);
attrs[2] = new SimpleAttributeSet(attrs[0]);
StyleConstants.setItalic(attrs[2], true);
attrs[3] = new SimpleAttributeSet(attrs[0]);
StyleConstants.setFontSize(attrs[3], 20);
try {
for (int i = 0; i < str.length; i++) {
doc_jtp.insertString(doc_jtp.getLength(), str[i] + "\n", attrs[i]);
}
} catch (BadLocationException ble) {
System.err.println("Error");
}
}
@Override
protected void tearDown() throws Exception {
jf.dispose();
super.tearDown();
}
void checkWasException() {
assertTrue(bWasException);
assertEquals("No more words", message);
bWasException = false;
message = null;
}
void checkWasException(final String s) {
assertTrue(bWasException);
assertEquals(s, message);
bWasException = false;
message = null;
}
int getTabbedTextOffset(final Segment s, final FontMetrics fm, final int start,
final int end, final TabExpander t, final int pos) {
int res = start;
boolean lastTab = true;
int ret = 0;
int tmp1 = 0;
//TODO end < start
for (char c = s.first(); c != CharacterIterator.DONE; c = s.next()) {
if (c == '\t' && t == null) {
c = ' ';
}
if (c == '\t') {
tmp1 = res;
res = (int) t.nextTabStop(res, s.getIndex() + pos - s.getBeginIndex());// + s.getIndex());
lastTab = true;
} else {
res += fm.charWidth(c);
lastTab = false;
}
int diff = (lastTab) ? (res - tmp1) : (fm.charWidth(c));
int tail = (diff / 2) + 1;
if (res < end + tail) {
ret++;
} else {
return ret;
}
}
return ret;
}
int getTabbedTextWidth(final Segment s, final FontMetrics fm, final int x,
final TabExpander t, final int pos) {
return getTabbedTextEnd(s, fm, x, t, pos) - x;
}
int getTabbedTextEnd(final Segment s, final FontMetrics fm, final int x,
final TabExpander t, final int pos) {
int res = x;
String str = "";
boolean isNullTabExpander = (t == null);
int segmentOffset = pos - s.getBeginIndex();
boolean isTab = false;
for (char c = s.first(); c != CharacterIterator.DONE; c = s.next()) {
isTab = (c == '\t');
if (isTab && !isNullTabExpander) {
res = (int) t.nextTabStop(fm.stringWidth(str) + res, s.getIndex()
+ segmentOffset);
str = "";
} else {
str += (isTab) ? ' ' : c;
isTab = false;
}
}
return isTab ? res : (res + fm.stringWidth(str));
}
void drawTabbedTextTest(final JTextComponent c) {
//According to my experiments this is only for one line
Document doc = c.getDocument();
Graphics g = c.getGraphics();
Element root = doc.getDefaultRootElement();
Segment seg = new Segment();
for (int i = 0; i < root.getElementCount(); i++) {
Element currentElem = root.getElement(i);
int start = currentElem.getStartOffset();
int end = currentElem.getEndOffset();
for (int j = start; j < end; j++) {
try {
doc.getText(start, (end - start), seg);
} catch (BadLocationException e) {
assertTrue("Unexpected Exception: " + e.getMessage(), false);
}
FontMetrics fm = g.getFontMetrics();
assertEquals(Utilities.drawTabbedText(seg, 23, 24, g, te, j), getTabbedTextEnd(
seg, fm, 23, te, j));
assertEquals(Utilities.drawTabbedText(seg, 23, 24, g, null, j),
getTabbedTextEnd(seg, fm, 23, null, j));
assertEquals(Utilities.drawTabbedText(seg, 23, 24, g, te, 100),
getTabbedTextEnd(seg, fm, 23, te, 100));
assertEquals(Utilities.drawTabbedText(seg, 23, 24, g, null, 100),
getTabbedTextEnd(seg, fm, 23, null, 100));
}
}
}
public void testDrawTabbedText() {
drawTabbedTextTest(jta);
drawTabbedTextTest(jtf);
//drawTabbedTextTest(jtp);
}
public void getTabbedTextWidthTest(final JTextComponent c) {
//According to my experiments this is only for one line
Document doc = c.getDocument();
Graphics g = c.getGraphics();
Element root = doc.getDefaultRootElement();
Segment seg = new Segment();
FontMetrics fm = g.getFontMetrics();
for (int i = 0; i < root.getElementCount(); i++) {
Element currentElem = root.getElement(i);
int start = currentElem.getStartOffset();
int end = currentElem.getEndOffset();
for (int j = start; j < end; j++) {
try {
doc.getText(start, end - start, seg);
} catch (BadLocationException e) {
assertTrue("Unexpected Exception: " + e.getMessage(), false);
}
assertEquals(Utilities.getTabbedTextWidth(seg, fm, 23, te, j),
getTabbedTextWidth(seg, fm, 23, te, j));
assertEquals(Utilities.getTabbedTextWidth(seg, fm, 23, null, j),
getTabbedTextWidth(seg, fm, 23, null, j));
assertEquals(Utilities.getTabbedTextWidth(seg, fm, 23, te, 100),
getTabbedTextWidth(seg, fm, 23, te, 100));
assertEquals(Utilities.getTabbedTextWidth(seg, fm, 23, null, 100),
getTabbedTextWidth(seg, fm, 23, null, 100));
}
}
}
public void testGetTabbedTextWidth() {
getTabbedTextWidthTest(jta);
getTabbedTextWidthTest(jtf);
//getTabbedTextWidthTest(jtp);
}
int getTabbedTextOffsetRound(final Segment s, final FontMetrics fm, final int start,
final int end, final TabExpander t, final int pos, final boolean round) {
String str = "";
int segmentOffset = pos - s.getBeginIndex();
boolean isTab = false;
boolean isNullTabExpander = (t == null);
int currentEnd = start;
int currentIndex = 0;
int prevEnd = start;
int tabEnd = start;
for (char c = s.first(); c != CharacterIterator.DONE; c = s.next()) {
isTab = (c == '\t');
if (isTab && !isNullTabExpander) {
tabEnd = (int) t.nextTabStop(currentEnd, s.getIndex() + segmentOffset);
str = "";
} else {
str += (isTab) ? ' ' : c;
isTab = false;
}
currentEnd = isTab ? tabEnd : (tabEnd + fm.stringWidth(str));
int delta = (round) ? (currentEnd - prevEnd) / 2 : 0;
if (currentEnd > end + delta) {
break;
}
currentIndex++;
prevEnd = currentEnd;
}
return currentIndex;
}
void getTabbedTextOffsetRoundTest_BoundaryCases(final JTextComponent c) {
Document doc = c.getDocument();
Graphics g = c.getGraphics();
assertNotNull(g);
Element root = doc.getDefaultRootElement();
Segment seg = new Segment();
for (int i = 0; i < root.getElementCount(); i++) {
Element currentElem = root.getElement(i);
int start = currentElem.getStartOffset();
int end = currentElem.getEndOffset();
try {
doc.getText(start, (end - start), seg);
} catch (BadLocationException e) {
assertTrue("Unexpected Exception: " + e.getMessage(), false);
}
int textOffset = start + 9;
FontMetrics fm = getFontMetrics(c.getFont(), 10);
int textWidth = getTabbedTextWidth(seg, fm, 23, te, textOffset);
for (int k = -3; k < textWidth + 4; k = (k == 0) ? k = textWidth + 1 : k + 1) {
int target = 23 + k;
int offset = (k <= 0) ? 0 : seg.count;
assertEquals(offset, Utilities.getTabbedTextOffset(seg, fm, 23, target, te,
textOffset, false));
assertEquals(offset, Utilities.getTabbedTextOffset(seg, fm, 23, target, te,
textOffset, true));
assertEquals(offset, Utilities.getTabbedTextOffset(seg, fm, 23, target, null,
textOffset, false));
assertEquals(offset, Utilities.getTabbedTextOffset(seg, fm, 23, target, null,
textOffset, true));
}
}
}
public void testGetTabbedTextOffsetRound_BoundaryCases() {
getTabbedTextOffsetRoundTest_BoundaryCases(jta);
getTabbedTextOffsetRoundTest_BoundaryCases(jtf);
//getTabbedTextOffsetRoundTest(jtp);
}
void getTabbedTextOffsetRoundTest(final JTextComponent c) {
Document doc = c.getDocument();
Graphics g = c.getGraphics();
Element root = doc.getDefaultRootElement();
Segment seg = new Segment();
FontMetrics fm = g.getFontMetrics();
for (int i = 0; i < root.getElementCount(); i++) {
Element currentElem = root.getElement(i);
int start = currentElem.getStartOffset();
int end = currentElem.getEndOffset();
try {
doc.getText(start, (end - start), seg);
} catch (BadLocationException e) {
assertTrue("Unexpected Exception: " + e.getMessage(), false);
}
int offset = start + 8;
int textWidth = Utilities.getTabbedTextWidth(seg, fm, 23, te, offset);
for (int k = 0; k < textWidth; k++) {
int target = 23 + k;
assertEquals(getTabbedTextOffsetRound(seg, fm, 23, target, te, offset, false),
Utilities.getTabbedTextOffset(seg, fm, 23, target, te, offset, false));
assertEquals(getTabbedTextOffsetRound(seg, fm, 23, target, te, offset, true),
Utilities.getTabbedTextOffset(seg, fm, 23, target, te, offset, true));
}
}
}
public void testGetTabbedTextOffsetRound() {
getTabbedTextOffsetRoundTest(jta);
getTabbedTextOffsetRoundTest(jtf);
//getTabbedTextOffsetRoundTest(jtp);
}
void getTabbedTextOffsetRoundTest_NoTabExpander(final JTextComponent c) {
Document doc = c.getDocument();
Graphics g = c.getGraphics();
FontMetrics fm = g.getFontMetrics();
Element root = doc.getDefaultRootElement();
Segment seg = new Segment();
for (int i = 0; i < root.getElementCount(); i++) {
Element currentElem = root.getElement(i);
int start = currentElem.getStartOffset();
int end = currentElem.getEndOffset();
int offset = start + 50;
try {
doc.getText(start, (end - start), seg);
} catch (BadLocationException e) {
assertTrue("Unexpected Exception: " + e.getMessage(), false);
}
int textWidth = Utilities.getTabbedTextWidth(seg, fm, 23, te, offset);
for (int k = 0; k < textWidth; k += 100) {
int target = 23 + k;
assertEquals(
getTabbedTextOffsetRound(seg, fm, 23, target, null, offset, false),
Utilities.getTabbedTextOffset(seg, fm, 23, target, null, offset, false));
assertEquals(getTabbedTextOffsetRound(seg, fm, 23, target, null, offset, true),
Utilities.getTabbedTextOffset(seg, fm, 23, target, null, offset, true));
}
}
}
public void testGetTabbedTextOffsetRound_NoTabExpander() {
getTabbedTextOffsetRoundTest_NoTabExpander(jta);
getTabbedTextOffsetRoundTest_NoTabExpander(jtf);
//getTabbedTextOffsetRoundTest_NoTabExpander(jtp);
}
void getTabbedTextOffsetTest(final JTextComponent c) {
Document doc = c.getDocument();
Graphics g = c.getGraphics();
Element root = doc.getDefaultRootElement();
Segment seg = new Segment();
FontMetrics fm = g.getFontMetrics();
for (int i = 0; i < root.getElementCount(); i++) {
Element currentElem = root.getElement(i);
int start = currentElem.getStartOffset();
int end = currentElem.getEndOffset();
try {
doc.getText(start, (end - start), seg);
} catch (BadLocationException e) {
assertTrue("Unexpected Exception: " + e.getMessage(), false);
}
int offset = start + 6;
int textWidth = Utilities.getTabbedTextWidth(seg, fm, 23, te, offset);
for (int k = -3; k < textWidth + 4; k++) {
int target = 23 + k;
assertEquals(getTabbedTextOffsetRound(seg, fm, 23, target, te, offset, true),
Utilities.getTabbedTextOffset(seg, fm, 23, target, te, offset));
assertEquals(getTabbedTextOffsetRound(seg, fm, 23, target, null, offset, true),
Utilities.getTabbedTextOffset(seg, fm, 23, target, null, offset));
}
}
}
public void testGetTabbedTextOffset() {
getTabbedTextOffsetTest(jta);
getTabbedTextOffsetTest(jtf);
//getTabbedTextOffsetTest(jtp);
}
int getBreakLocation(final Segment s, final FontMetrics fm, final int start, final int end,
final TabExpander t, final int pos) {
int offset = s.offset;
int index = Utilities.getTabbedTextOffset(s, fm, start, end, t, pos, false);
int fullIndex = offset + index;
BreakIterator bi = BreakIterator.getWordInstance();
bi.setText(s);
if (bi.last() <= fullIndex) {
return bi.last() - offset;
}
if (bi.isBoundary(fullIndex)) {
return Character.isWhitespace(s.array[fullIndex]) ? index + 1 : index;
}
int prev = bi.preceding(fullIndex);
if (prev == bi.first()) {
return index;
}
return prev - offset;
}
void getBreakLocationTest(final JTextComponent c) {
Document doc = c.getDocument();
Graphics g = c.getGraphics();
FontMetrics fm = g.getFontMetrics();
Element root = doc.getDefaultRootElement();
Segment seg = new Segment();
for (int i = 0; i < root.getElementCount(); i++) {
Element currentElem = root.getElement(i);
int start = currentElem.getStartOffset();
int end = currentElem.getEndOffset();
for (int j = start; j < Math.min(start + 10, end); j++) {
try {
doc.getText(start, (end - start), seg);
} catch (BadLocationException e) {
assertTrue("Unexpected Exception: " + e.getMessage(), false);
}
int textWidth = Utilities.getTabbedTextWidth(seg, fm, 23, te, j);
for (int k = 0; k < textWidth; k++) {
int target = 23 + k;
//TODO This test have to fail
assertEquals(Utilities.getBreakLocation(seg, fm, 23, target, te, j),
getBreakLocation(seg, fm, 23, target, te, j));
assertEquals(Utilities.getBreakLocation(seg, fm, 23, target, null, j),
getBreakLocation(seg, fm, 23, target, null, j));
}
}
}
}
public void testGetBreakLocation() {
if (isHarmony()) {
getBreakLocationTest(jta);
}
}
private void getParagraphElementTest(final JTextComponent c) {
AbstractDocument ad = (AbstractDocument) c.getDocument();
if (ad instanceof PlainDocument) {
assertNull(Utilities.getParagraphElement(c, 5000));
assertNull(Utilities.getParagraphElement(c, -5000));
} else {
assertEquals(ad.getParagraphElement(5000), Utilities.getParagraphElement(c, 5000));
assertEquals(ad.getParagraphElement(-5000), Utilities.getParagraphElement(c, -5000));
}
Element rootElement = ad.getDefaultRootElement();
for (int i = 0; i < rootElement.getElementCount(); i++) {
Element elem = rootElement.getElement(i);
int start = elem.getStartOffset();
int end = elem.getEndOffset();
for (int j = start; j < end; j++) {
assertEquals(elem, Utilities.getParagraphElement(c, j));
assertEquals(elem, ad.getParagraphElement(j));
}
}
}
public void testGetParagraphElement() {
getParagraphElementTest(jta);
//getParagraphElementTest(jtp);
getParagraphElementTest(jtf);
}
int getPositionAbove(final JTextComponent c, final int p, final int x)
throws BadLocationException {
int p0 = Utilities.getRowStart(c, p);
if (p0 == 0) {
return -1;
}
int end = p0 - 1;
int diff = Integer.MAX_VALUE;
int offset = 0;
int start = Utilities.getRowStart(c, end);
for (int i = start; i <= end; i++) {
Rectangle rect = c.modelToView(i);
assertNotNull(rect);
int locDiff = Math.abs(rect.x - x);
if (locDiff <= diff) {
diff = locDiff;
offset = i;
}
}
return offset;
}
int getPositionBelow(final JTextComponent c, final int p, final int x)
throws BadLocationException {
int p0 = Utilities.getRowEnd(c, p);
int length = c.getDocument().getLength();
if (p0 == length) {
return p;
}
int start = p0 + 1;
int diff = Integer.MAX_VALUE;
int offset = 0;
int end = Utilities.getRowEnd(c, start);
for (int i = start; i <= end; i++) {
Rectangle rect = c.modelToView(i);
assertNotNull(rect);
int locDiff = Math.abs(rect.x - x);
if (locDiff < diff) {
diff = locDiff;
offset = i;
}
}
return offset;
}
void getPositionAboveBelowTest(final JTextComponent c) {
BasicTextUI ui = (BasicTextUI) c.getUI();
Document doc = c.getDocument();
int length = doc.getLength();
for (int i = 0; i < length; i++) {
int utilAbove = 0;
int utilAbove1 = 0;
int utilBelow = 0;
int utilBelow1 = 0;
int utilAboveT = 0;
int utilAbove1T = 0;
int utilBelowT = 0;
int utilBelow1T = 0;
int appendix = 23;
Rectangle rect = null;
try {
rect = ui.modelToView(c, i);
} catch (BadLocationException e) {
}
assertNotNull(rect);
try {
utilBelow = Utilities.getPositionBelow(c, i, rect.x);
utilBelowT = getPositionBelow(c, i, rect.x);
utilBelow1 = Utilities.getPositionBelow(c, i, rect.x + appendix);
utilBelow1T = Utilities.getPositionBelow(c, i, rect.x + appendix);
} catch (BadLocationException e) {
assertFalse("Unexpected exception: " + e.getMessage(), true);
}
assertEquals(utilAboveT, utilAbove);
assertEquals(utilAbove1T, utilAbove1);
assertEquals(utilBelow1, utilBelow1T);
assertEquals(utilBelow, utilBelowT);
}
try {
Utilities.getPositionAbove(c, -10, 100);
} catch (BadLocationException e) {
message = e.getMessage();
bWasException = true;
}
checkWasException("Position not represented by view");
try {
Utilities.getPositionAbove(c, 5000, 100);
} catch (BadLocationException e) {
message = e.getMessage();
bWasException = true;
}
checkWasException("Position not represented by view");
try {
Utilities.getPositionBelow(c, -10, 100);
} catch (BadLocationException e) {
message = e.getMessage();
bWasException = true;
}
checkWasException("Position not represented by view");
try {
Utilities.getPositionBelow(c, 5000, 100);
} catch (BadLocationException e) {
message = e.getMessage();
bWasException = true;
}
checkWasException("Position not represented by view");
}
public void testGetPositionAboveBelow() {
getPositionAboveBelowTest(jta);
//getPositionAboveBelowTest(jtp);
getPositionAboveBelowTest(jtf);
}
// HARMONY-2745
public void testGetPositionAbove() throws BadLocationException {
jta = new JTextArea();
assertEquals(-1, Utilities.getPositionAbove(jta, 1, 0));
}
// HARMONY-2745
public void testGetPositionBelow() throws BadLocationException {
jta = new JTextArea();
assertEquals(-1, Utilities.getPositionBelow(jta, 1, 0));
}
void getWordStartTest(final JTextComponent c) {
AbstractDocument ad = (AbstractDocument) c.getDocument();
BreakIterator bi = BreakIterator.getWordInstance();
int length = ad.getLength();
try {
bi.setText(ad.getText(0, ad.getLength()));
} catch (BadLocationException e) {
}
int iteratorWordStart = 0;
bi.first();
for (int i = 0; i < length; i++) {
int utilitiesWordStart = 0;
if (i < length - 1) {
iteratorWordStart = bi.preceding(i + 1);
} else {
bi.last();
iteratorWordStart = bi.previous();
}
try {
utilitiesWordStart = Utilities.getWordStart(c, i);
} catch (BadLocationException e) {
}
assertEquals(iteratorWordStart, utilitiesWordStart);
}
/* According to spec */
try {
Utilities.getWordStart(c, length + 10);
} catch (BadLocationException e) {
message = e.getMessage();
bWasException = true;
}
checkWasException("No word at " + (length + 10));
try {
Utilities.getWordStart(c, -1);
} catch (BadLocationException e) {
message = e.getMessage();
bWasException = true;
}
checkWasException("No word at -1");
/**/
}
public void testGetWordStart() {
getWordStartTest(jta);
//getWordStartTest(jtp);
getWordStartTest(jtf);
}
void getWordEndTest(final JTextComponent c) {
AbstractDocument ad = (AbstractDocument) c.getDocument();
BreakIterator bi = BreakIterator.getWordInstance();
int length = ad.getLength();
try {
bi.setText(ad.getText(0, length));
} catch (BadLocationException e) {
}
bi.first();
for (int i = 0; i < length; i++) {
int utilitiesWordEnd = 0;
int iteratorWordEnd = bi.following(i);
try {
utilitiesWordEnd = Utilities.getWordEnd(c, i);
} catch (BadLocationException e) {
}
assertEquals(iteratorWordEnd, utilitiesWordEnd);
}
/* According to spec */
try {
Utilities.getWordEnd(c, length + 10);
} catch (BadLocationException e) {
message = e.getMessage();
bWasException = true;
}
checkWasException("No word at " + (length + 10));
try {
Utilities.getWordEnd(c, -1);
} catch (BadLocationException e) {
message = e.getMessage();
bWasException = true;
}
checkWasException("No word at -1");
/**/
}
public void testGetWordEnd() {
getWordEndTest(jta);
//getWordEndTest(jtp);
getWordEndTest(jtf);
}
// may be in future...
int getRowStart(final JTextComponent c, final int pos) throws BadLocationException {
Rectangle r = null;
r = c.modelToView(pos);
for (int i = pos; i >= 0; i--) {
Rectangle tmp = null;
tmp = c.modelToView(i);
if (tmp.y < r.y) {
return i + 1;
}
}
return 0;
}
int getRowEnd(final JTextComponent c, final int pos) throws BadLocationException {
int length = c.getDocument().getLength();
if (c instanceof JTextField) {
return length;
}
Rectangle r = null;
r = c.modelToView(pos);
for (int i = pos; i <= length; i++) {
Rectangle tmp = null;
tmp = c.modelToView(i);
if (tmp.y > r.y) {
return i - 1;
}
}
return length;
}
void getRowStartEndTest(final JTextComponent c) throws Exception {
Document doc = c.getDocument();
View root = c.getUI().getRootView(c).getView(0);
assertNotNull(root);
int length = doc.getLength();
for (int i = 0; i < length; i++) {
/*
* int index1 = root.getViewIndex(i, Position.Bias.Forward); View
* view1 = root.getView(index1); int index2 = view1.getViewIndex(i,
* Position.Bias.Forward); View view2 = view1.getView(index2); View
* view = (c instanceof JTextField) ? view1 : view2;
*
* int start = view.getStartOffset(); int end = view.getEndOffset() -
* 1;
*/
int utilitiesRowStart = 0;
int utilitiesRowEnd = 0;
try {
utilitiesRowStart = Utilities.getRowStart(c, i);
utilitiesRowEnd = Utilities.getRowEnd(c, i);
} catch (BadLocationException e) {
}
assertEquals(getRowEnd(c, i), utilitiesRowEnd);
assertEquals(getRowStart(c, i), utilitiesRowStart);
}
try {
Utilities.getRowStart(c, 5000);
} catch (BadLocationException e) {
bWasException = true;
message = e.getMessage();
}
checkWasException("Position not represented by view");
try {
Utilities.getRowEnd(c, 5000);
} catch (BadLocationException e) {
bWasException = true;
message = e.getMessage();
}
;
checkWasException("Position not represented by view");
try {
Utilities.getRowStart(c, -10);
} catch (BadLocationException e) {
bWasException = true;
message = e.getMessage();
}
;
checkWasException("Position not represented by view");
try {
Utilities.getRowEnd(c, -10);
} catch (BadLocationException e) {
bWasException = true;
message = e.getMessage();
}
;
checkWasException("Position not represented by view");
textComponent = c;
textComponent.setSize(0, 0);
assertEquals(-1, Utilities.getRowStart(c, -20));
assertEquals(-1, Utilities.getRowEnd(c, 5000));
assertEquals(-1, Utilities.getRowStart(c, 5));
assertEquals(-1, Utilities.getRowEnd(c, 6));
}
public void testGetRowStartEnd() throws Exception {
getRowStartEndTest(jta);
//getRowStartEndTest(jtp);
getRowStartEndTest(jtf);
}
void getPreviousWordTest(final JTextComponent c) {
AbstractDocument ad = (AbstractDocument) c.getDocument();
BreakIterator bi = BreakIterator.getWordInstance();
int length = ad.getLength();
String content = null;
try {
content = ad.getText(0, ad.getLength());
bi.setText(content);
} catch (BadLocationException e) {
}
assertNotNull(content);
bi.first();
for (int i = 0; i < length; i++) {
int utilitiesPrevWord = 0;
int iteratorPrevWord = bi.preceding(i);
while (iteratorPrevWord > 0
&& ((content.charAt(iteratorPrevWord) == ' ' || content
.charAt(iteratorPrevWord) == '\n') || content
.charAt(iteratorPrevWord) == '\t')) {
iteratorPrevWord = bi.preceding(iteratorPrevWord);
}
try {
utilitiesPrevWord = Utilities.getPreviousWord(c, i);
} catch (BadLocationException e) {
}
if (iteratorPrevWord == -1) {
iteratorPrevWord = 0;
}
assertEquals(iteratorPrevWord, utilitiesPrevWord);
}
try {
Utilities.getPreviousWord(c, -1);
} catch (BadLocationException e) {
bWasException = true;
message = e.getMessage();
}
checkWasException();
try {
Utilities.getPreviousWord(c, 5000);
} catch (BadLocationException e) {
bWasException = true;
message = e.getMessage();
}
checkWasException();
}
public void testGetPreviousWord() {
getPreviousWordTest(jta);
//getPreviousWordTest(jtp);
getPreviousWordTest(jtf);
}
void getNextWordTest(final JTextComponent c) {
AbstractDocument ad = (AbstractDocument) c.getDocument();
BreakIterator bi = BreakIterator.getWordInstance();
int length = ad.getLength();
String content = null;
try {
content = ad.getText(0, ad.getLength());
bi.setText(content);
} catch (BadLocationException e) {
}
assertNotNull(content);
bi.first();
for (int i = 0; i < length; i++) {
int utilitiesNextWord = 0;
int iteratorNextWord = bi.following(i);
while (iteratorNextWord < length
&& ((content.charAt(iteratorNextWord) == ' ' || content
.charAt(iteratorNextWord) == '\n') || content
.charAt(iteratorNextWord) == '\t')) {
iteratorNextWord = bi.following(iteratorNextWord);
}
try {
utilitiesNextWord = Utilities.getNextWord(c, i);
} catch (BadLocationException e) {
}
if (iteratorNextWord == length) {
iteratorNextWord = 0;
}
assertEquals(iteratorNextWord, utilitiesNextWord);
}
try {
Utilities.getNextWord(c, length + 10);
} catch (BadLocationException e) {
message = e.getMessage();
bWasException = true;
}
checkWasException();
bWasException = false;
message = null;
try {
Utilities.getNextWord(c, -1);
} catch (BadLocationException e) {
message = e.getMessage();
bWasException = true;
}
checkWasException();
}
public void testGetNextWord() {
getNextWordTest(jta);
getNextWordTest(jtf);
//getNextWordTest(jtp);
}
// HARMONY-2744
public void testGetNextWord02() {
jta = new JTextArea("");
try {
Utilities.getNextWord(jta, 0);
fail("BadLocationException expected");
} catch (BadLocationException e) {
// "No more words"
}
}
// HARMONY-2744
public void testGetNextWord03() {
jta = new JTextArea("a");
try {
Utilities.getNextWord(jta, 0);
fail("BadLocationException expected");
} catch (BadLocationException e) {
// "No more words"
}
try {
Utilities.getNextWord(jta, 1);
fail("BadLocationException expected");
} catch (BadLocationException e) {
// "No more words"
}
}
// HARMONY-2744
public void testGetNextWord04() throws Exception {
jta = new JTextArea("a b");
assertEquals(2, Utilities.getNextWord(jta, 0));
assertEquals(2, Utilities.getNextWord(jta, 1));
try {
Utilities.getNextWord(jta, 2);
fail("BadLocationException expected");
} catch (BadLocationException e) {
// "No more words"
}
}
} |
apache/hive | 36,499 | standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/DropPartitionRequest.java | /**
* Autogenerated by Thrift Compiler (0.16.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.apache.hadoop.hive.metastore.api;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.16.0)")
@org.apache.hadoop.classification.InterfaceAudience.Public @org.apache.hadoop.classification.InterfaceStability.Stable public class DropPartitionRequest implements org.apache.thrift.TBase<DropPartitionRequest, DropPartitionRequest._Fields>, java.io.Serializable, Cloneable, Comparable<DropPartitionRequest> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("DropPartitionRequest");
private static final org.apache.thrift.protocol.TField CAT_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("catName", org.apache.thrift.protocol.TType.STRING, (short)1);
private static final org.apache.thrift.protocol.TField DB_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("dbName", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.protocol.TField TBL_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("tblName", org.apache.thrift.protocol.TType.STRING, (short)3);
private static final org.apache.thrift.protocol.TField PART_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("partName", org.apache.thrift.protocol.TType.STRING, (short)4);
private static final org.apache.thrift.protocol.TField PART_VALS_FIELD_DESC = new org.apache.thrift.protocol.TField("partVals", org.apache.thrift.protocol.TType.LIST, (short)5);
private static final org.apache.thrift.protocol.TField DELETE_DATA_FIELD_DESC = new org.apache.thrift.protocol.TField("deleteData", org.apache.thrift.protocol.TType.BOOL, (short)6);
private static final org.apache.thrift.protocol.TField ENVIRONMENT_CONTEXT_FIELD_DESC = new org.apache.thrift.protocol.TField("environmentContext", org.apache.thrift.protocol.TType.STRUCT, (short)7);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new DropPartitionRequestStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new DropPartitionRequestTupleSchemeFactory();
private @org.apache.thrift.annotation.Nullable java.lang.String catName; // optional
private @org.apache.thrift.annotation.Nullable java.lang.String dbName; // required
private @org.apache.thrift.annotation.Nullable java.lang.String tblName; // required
private @org.apache.thrift.annotation.Nullable java.lang.String partName; // optional
private @org.apache.thrift.annotation.Nullable java.util.List<java.lang.String> partVals; // optional
private boolean deleteData; // optional
private @org.apache.thrift.annotation.Nullable EnvironmentContext environmentContext; // 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 {
CAT_NAME((short)1, "catName"),
DB_NAME((short)2, "dbName"),
TBL_NAME((short)3, "tblName"),
PART_NAME((short)4, "partName"),
PART_VALS((short)5, "partVals"),
DELETE_DATA((short)6, "deleteData"),
ENVIRONMENT_CONTEXT((short)7, "environmentContext");
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: // CAT_NAME
return CAT_NAME;
case 2: // DB_NAME
return DB_NAME;
case 3: // TBL_NAME
return TBL_NAME;
case 4: // PART_NAME
return PART_NAME;
case 5: // PART_VALS
return PART_VALS;
case 6: // DELETE_DATA
return DELETE_DATA;
case 7: // ENVIRONMENT_CONTEXT
return ENVIRONMENT_CONTEXT;
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 __DELETEDATA_ISSET_ID = 0;
private byte __isset_bitfield = 0;
private static final _Fields optionals[] = {_Fields.CAT_NAME,_Fields.PART_NAME,_Fields.PART_VALS,_Fields.DELETE_DATA,_Fields.ENVIRONMENT_CONTEXT};
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.CAT_NAME, new org.apache.thrift.meta_data.FieldMetaData("catName", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.DB_NAME, new org.apache.thrift.meta_data.FieldMetaData("dbName", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.TBL_NAME, new org.apache.thrift.meta_data.FieldMetaData("tblName", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.PART_NAME, new org.apache.thrift.meta_data.FieldMetaData("partName", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.PART_VALS, new org.apache.thrift.meta_data.FieldMetaData("partVals", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))));
tmpMap.put(_Fields.DELETE_DATA, new org.apache.thrift.meta_data.FieldMetaData("deleteData", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));
tmpMap.put(_Fields.ENVIRONMENT_CONTEXT, new org.apache.thrift.meta_data.FieldMetaData("environmentContext", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, EnvironmentContext.class)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(DropPartitionRequest.class, metaDataMap);
}
public DropPartitionRequest() {
}
public DropPartitionRequest(
java.lang.String dbName,
java.lang.String tblName)
{
this();
this.dbName = dbName;
this.tblName = tblName;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public DropPartitionRequest(DropPartitionRequest other) {
__isset_bitfield = other.__isset_bitfield;
if (other.isSetCatName()) {
this.catName = other.catName;
}
if (other.isSetDbName()) {
this.dbName = other.dbName;
}
if (other.isSetTblName()) {
this.tblName = other.tblName;
}
if (other.isSetPartName()) {
this.partName = other.partName;
}
if (other.isSetPartVals()) {
java.util.List<java.lang.String> __this__partVals = new java.util.ArrayList<java.lang.String>(other.partVals);
this.partVals = __this__partVals;
}
this.deleteData = other.deleteData;
if (other.isSetEnvironmentContext()) {
this.environmentContext = new EnvironmentContext(other.environmentContext);
}
}
public DropPartitionRequest deepCopy() {
return new DropPartitionRequest(this);
}
@Override
public void clear() {
this.catName = null;
this.dbName = null;
this.tblName = null;
this.partName = null;
this.partVals = null;
setDeleteDataIsSet(false);
this.deleteData = false;
this.environmentContext = null;
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getCatName() {
return this.catName;
}
public void setCatName(@org.apache.thrift.annotation.Nullable java.lang.String catName) {
this.catName = catName;
}
public void unsetCatName() {
this.catName = null;
}
/** Returns true if field catName is set (has been assigned a value) and false otherwise */
public boolean isSetCatName() {
return this.catName != null;
}
public void setCatNameIsSet(boolean value) {
if (!value) {
this.catName = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getDbName() {
return this.dbName;
}
public void setDbName(@org.apache.thrift.annotation.Nullable java.lang.String dbName) {
this.dbName = dbName;
}
public void unsetDbName() {
this.dbName = null;
}
/** Returns true if field dbName is set (has been assigned a value) and false otherwise */
public boolean isSetDbName() {
return this.dbName != null;
}
public void setDbNameIsSet(boolean value) {
if (!value) {
this.dbName = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getTblName() {
return this.tblName;
}
public void setTblName(@org.apache.thrift.annotation.Nullable java.lang.String tblName) {
this.tblName = tblName;
}
public void unsetTblName() {
this.tblName = null;
}
/** Returns true if field tblName is set (has been assigned a value) and false otherwise */
public boolean isSetTblName() {
return this.tblName != null;
}
public void setTblNameIsSet(boolean value) {
if (!value) {
this.tblName = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getPartName() {
return this.partName;
}
public void setPartName(@org.apache.thrift.annotation.Nullable java.lang.String partName) {
this.partName = partName;
}
public void unsetPartName() {
this.partName = null;
}
/** Returns true if field partName is set (has been assigned a value) and false otherwise */
public boolean isSetPartName() {
return this.partName != null;
}
public void setPartNameIsSet(boolean value) {
if (!value) {
this.partName = null;
}
}
public int getPartValsSize() {
return (this.partVals == null) ? 0 : this.partVals.size();
}
@org.apache.thrift.annotation.Nullable
public java.util.Iterator<java.lang.String> getPartValsIterator() {
return (this.partVals == null) ? null : this.partVals.iterator();
}
public void addToPartVals(java.lang.String elem) {
if (this.partVals == null) {
this.partVals = new java.util.ArrayList<java.lang.String>();
}
this.partVals.add(elem);
}
@org.apache.thrift.annotation.Nullable
public java.util.List<java.lang.String> getPartVals() {
return this.partVals;
}
public void setPartVals(@org.apache.thrift.annotation.Nullable java.util.List<java.lang.String> partVals) {
this.partVals = partVals;
}
public void unsetPartVals() {
this.partVals = null;
}
/** Returns true if field partVals is set (has been assigned a value) and false otherwise */
public boolean isSetPartVals() {
return this.partVals != null;
}
public void setPartValsIsSet(boolean value) {
if (!value) {
this.partVals = null;
}
}
public boolean isDeleteData() {
return this.deleteData;
}
public void setDeleteData(boolean deleteData) {
this.deleteData = deleteData;
setDeleteDataIsSet(true);
}
public void unsetDeleteData() {
__isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __DELETEDATA_ISSET_ID);
}
/** Returns true if field deleteData is set (has been assigned a value) and false otherwise */
public boolean isSetDeleteData() {
return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __DELETEDATA_ISSET_ID);
}
public void setDeleteDataIsSet(boolean value) {
__isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __DELETEDATA_ISSET_ID, value);
}
@org.apache.thrift.annotation.Nullable
public EnvironmentContext getEnvironmentContext() {
return this.environmentContext;
}
public void setEnvironmentContext(@org.apache.thrift.annotation.Nullable EnvironmentContext environmentContext) {
this.environmentContext = environmentContext;
}
public void unsetEnvironmentContext() {
this.environmentContext = null;
}
/** Returns true if field environmentContext is set (has been assigned a value) and false otherwise */
public boolean isSetEnvironmentContext() {
return this.environmentContext != null;
}
public void setEnvironmentContextIsSet(boolean value) {
if (!value) {
this.environmentContext = null;
}
}
public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
switch (field) {
case CAT_NAME:
if (value == null) {
unsetCatName();
} else {
setCatName((java.lang.String)value);
}
break;
case DB_NAME:
if (value == null) {
unsetDbName();
} else {
setDbName((java.lang.String)value);
}
break;
case TBL_NAME:
if (value == null) {
unsetTblName();
} else {
setTblName((java.lang.String)value);
}
break;
case PART_NAME:
if (value == null) {
unsetPartName();
} else {
setPartName((java.lang.String)value);
}
break;
case PART_VALS:
if (value == null) {
unsetPartVals();
} else {
setPartVals((java.util.List<java.lang.String>)value);
}
break;
case DELETE_DATA:
if (value == null) {
unsetDeleteData();
} else {
setDeleteData((java.lang.Boolean)value);
}
break;
case ENVIRONMENT_CONTEXT:
if (value == null) {
unsetEnvironmentContext();
} else {
setEnvironmentContext((EnvironmentContext)value);
}
break;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case CAT_NAME:
return getCatName();
case DB_NAME:
return getDbName();
case TBL_NAME:
return getTblName();
case PART_NAME:
return getPartName();
case PART_VALS:
return getPartVals();
case DELETE_DATA:
return isDeleteData();
case ENVIRONMENT_CONTEXT:
return getEnvironmentContext();
}
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 CAT_NAME:
return isSetCatName();
case DB_NAME:
return isSetDbName();
case TBL_NAME:
return isSetTblName();
case PART_NAME:
return isSetPartName();
case PART_VALS:
return isSetPartVals();
case DELETE_DATA:
return isSetDeleteData();
case ENVIRONMENT_CONTEXT:
return isSetEnvironmentContext();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that instanceof DropPartitionRequest)
return this.equals((DropPartitionRequest)that);
return false;
}
public boolean equals(DropPartitionRequest that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_catName = true && this.isSetCatName();
boolean that_present_catName = true && that.isSetCatName();
if (this_present_catName || that_present_catName) {
if (!(this_present_catName && that_present_catName))
return false;
if (!this.catName.equals(that.catName))
return false;
}
boolean this_present_dbName = true && this.isSetDbName();
boolean that_present_dbName = true && that.isSetDbName();
if (this_present_dbName || that_present_dbName) {
if (!(this_present_dbName && that_present_dbName))
return false;
if (!this.dbName.equals(that.dbName))
return false;
}
boolean this_present_tblName = true && this.isSetTblName();
boolean that_present_tblName = true && that.isSetTblName();
if (this_present_tblName || that_present_tblName) {
if (!(this_present_tblName && that_present_tblName))
return false;
if (!this.tblName.equals(that.tblName))
return false;
}
boolean this_present_partName = true && this.isSetPartName();
boolean that_present_partName = true && that.isSetPartName();
if (this_present_partName || that_present_partName) {
if (!(this_present_partName && that_present_partName))
return false;
if (!this.partName.equals(that.partName))
return false;
}
boolean this_present_partVals = true && this.isSetPartVals();
boolean that_present_partVals = true && that.isSetPartVals();
if (this_present_partVals || that_present_partVals) {
if (!(this_present_partVals && that_present_partVals))
return false;
if (!this.partVals.equals(that.partVals))
return false;
}
boolean this_present_deleteData = true && this.isSetDeleteData();
boolean that_present_deleteData = true && that.isSetDeleteData();
if (this_present_deleteData || that_present_deleteData) {
if (!(this_present_deleteData && that_present_deleteData))
return false;
if (this.deleteData != that.deleteData)
return false;
}
boolean this_present_environmentContext = true && this.isSetEnvironmentContext();
boolean that_present_environmentContext = true && that.isSetEnvironmentContext();
if (this_present_environmentContext || that_present_environmentContext) {
if (!(this_present_environmentContext && that_present_environmentContext))
return false;
if (!this.environmentContext.equals(that.environmentContext))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((isSetCatName()) ? 131071 : 524287);
if (isSetCatName())
hashCode = hashCode * 8191 + catName.hashCode();
hashCode = hashCode * 8191 + ((isSetDbName()) ? 131071 : 524287);
if (isSetDbName())
hashCode = hashCode * 8191 + dbName.hashCode();
hashCode = hashCode * 8191 + ((isSetTblName()) ? 131071 : 524287);
if (isSetTblName())
hashCode = hashCode * 8191 + tblName.hashCode();
hashCode = hashCode * 8191 + ((isSetPartName()) ? 131071 : 524287);
if (isSetPartName())
hashCode = hashCode * 8191 + partName.hashCode();
hashCode = hashCode * 8191 + ((isSetPartVals()) ? 131071 : 524287);
if (isSetPartVals())
hashCode = hashCode * 8191 + partVals.hashCode();
hashCode = hashCode * 8191 + ((isSetDeleteData()) ? 131071 : 524287);
if (isSetDeleteData())
hashCode = hashCode * 8191 + ((deleteData) ? 131071 : 524287);
hashCode = hashCode * 8191 + ((isSetEnvironmentContext()) ? 131071 : 524287);
if (isSetEnvironmentContext())
hashCode = hashCode * 8191 + environmentContext.hashCode();
return hashCode;
}
@Override
public int compareTo(DropPartitionRequest other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.compare(isSetCatName(), other.isSetCatName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetCatName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.catName, other.catName);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetDbName(), other.isSetDbName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetDbName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.dbName, other.dbName);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetTblName(), other.isSetTblName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTblName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.tblName, other.tblName);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetPartName(), other.isSetPartName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetPartName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.partName, other.partName);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetPartVals(), other.isSetPartVals());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetPartVals()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.partVals, other.partVals);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetDeleteData(), other.isSetDeleteData());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetDeleteData()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.deleteData, other.deleteData);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetEnvironmentContext(), other.isSetEnvironmentContext());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetEnvironmentContext()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.environmentContext, other.environmentContext);
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("DropPartitionRequest(");
boolean first = true;
if (isSetCatName()) {
sb.append("catName:");
if (this.catName == null) {
sb.append("null");
} else {
sb.append(this.catName);
}
first = false;
}
if (!first) sb.append(", ");
sb.append("dbName:");
if (this.dbName == null) {
sb.append("null");
} else {
sb.append(this.dbName);
}
first = false;
if (!first) sb.append(", ");
sb.append("tblName:");
if (this.tblName == null) {
sb.append("null");
} else {
sb.append(this.tblName);
}
first = false;
if (isSetPartName()) {
if (!first) sb.append(", ");
sb.append("partName:");
if (this.partName == null) {
sb.append("null");
} else {
sb.append(this.partName);
}
first = false;
}
if (isSetPartVals()) {
if (!first) sb.append(", ");
sb.append("partVals:");
if (this.partVals == null) {
sb.append("null");
} else {
sb.append(this.partVals);
}
first = false;
}
if (isSetDeleteData()) {
if (!first) sb.append(", ");
sb.append("deleteData:");
sb.append(this.deleteData);
first = false;
}
if (isSetEnvironmentContext()) {
if (!first) sb.append(", ");
sb.append("environmentContext:");
if (this.environmentContext == null) {
sb.append("null");
} else {
sb.append(this.environmentContext);
}
first = false;
}
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
if (!isSetDbName()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'dbName' is unset! Struct:" + toString());
}
if (!isSetTblName()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'tblName' is unset! Struct:" + toString());
}
// check for sub-struct validity
if (environmentContext != null) {
environmentContext.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 DropPartitionRequestStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public DropPartitionRequestStandardScheme getScheme() {
return new DropPartitionRequestStandardScheme();
}
}
private static class DropPartitionRequestStandardScheme extends org.apache.thrift.scheme.StandardScheme<DropPartitionRequest> {
public void read(org.apache.thrift.protocol.TProtocol iprot, DropPartitionRequest 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: // CAT_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.catName = iprot.readString();
struct.setCatNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // DB_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.dbName = iprot.readString();
struct.setDbNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // TBL_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.tblName = iprot.readString();
struct.setTblNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 4: // PART_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.partName = iprot.readString();
struct.setPartNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 5: // PART_VALS
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list698 = iprot.readListBegin();
struct.partVals = new java.util.ArrayList<java.lang.String>(_list698.size);
@org.apache.thrift.annotation.Nullable java.lang.String _elem699;
for (int _i700 = 0; _i700 < _list698.size; ++_i700)
{
_elem699 = iprot.readString();
struct.partVals.add(_elem699);
}
iprot.readListEnd();
}
struct.setPartValsIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 6: // DELETE_DATA
if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {
struct.deleteData = iprot.readBool();
struct.setDeleteDataIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 7: // ENVIRONMENT_CONTEXT
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.environmentContext = new EnvironmentContext();
struct.environmentContext.read(iprot);
struct.setEnvironmentContextIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, DropPartitionRequest struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.catName != null) {
if (struct.isSetCatName()) {
oprot.writeFieldBegin(CAT_NAME_FIELD_DESC);
oprot.writeString(struct.catName);
oprot.writeFieldEnd();
}
}
if (struct.dbName != null) {
oprot.writeFieldBegin(DB_NAME_FIELD_DESC);
oprot.writeString(struct.dbName);
oprot.writeFieldEnd();
}
if (struct.tblName != null) {
oprot.writeFieldBegin(TBL_NAME_FIELD_DESC);
oprot.writeString(struct.tblName);
oprot.writeFieldEnd();
}
if (struct.partName != null) {
if (struct.isSetPartName()) {
oprot.writeFieldBegin(PART_NAME_FIELD_DESC);
oprot.writeString(struct.partName);
oprot.writeFieldEnd();
}
}
if (struct.partVals != null) {
if (struct.isSetPartVals()) {
oprot.writeFieldBegin(PART_VALS_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, struct.partVals.size()));
for (java.lang.String _iter701 : struct.partVals)
{
oprot.writeString(_iter701);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
}
if (struct.isSetDeleteData()) {
oprot.writeFieldBegin(DELETE_DATA_FIELD_DESC);
oprot.writeBool(struct.deleteData);
oprot.writeFieldEnd();
}
if (struct.environmentContext != null) {
if (struct.isSetEnvironmentContext()) {
oprot.writeFieldBegin(ENVIRONMENT_CONTEXT_FIELD_DESC);
struct.environmentContext.write(oprot);
oprot.writeFieldEnd();
}
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class DropPartitionRequestTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public DropPartitionRequestTupleScheme getScheme() {
return new DropPartitionRequestTupleScheme();
}
}
private static class DropPartitionRequestTupleScheme extends org.apache.thrift.scheme.TupleScheme<DropPartitionRequest> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, DropPartitionRequest struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
oprot.writeString(struct.dbName);
oprot.writeString(struct.tblName);
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetCatName()) {
optionals.set(0);
}
if (struct.isSetPartName()) {
optionals.set(1);
}
if (struct.isSetPartVals()) {
optionals.set(2);
}
if (struct.isSetDeleteData()) {
optionals.set(3);
}
if (struct.isSetEnvironmentContext()) {
optionals.set(4);
}
oprot.writeBitSet(optionals, 5);
if (struct.isSetCatName()) {
oprot.writeString(struct.catName);
}
if (struct.isSetPartName()) {
oprot.writeString(struct.partName);
}
if (struct.isSetPartVals()) {
{
oprot.writeI32(struct.partVals.size());
for (java.lang.String _iter702 : struct.partVals)
{
oprot.writeString(_iter702);
}
}
}
if (struct.isSetDeleteData()) {
oprot.writeBool(struct.deleteData);
}
if (struct.isSetEnvironmentContext()) {
struct.environmentContext.write(oprot);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, DropPartitionRequest struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
struct.dbName = iprot.readString();
struct.setDbNameIsSet(true);
struct.tblName = iprot.readString();
struct.setTblNameIsSet(true);
java.util.BitSet incoming = iprot.readBitSet(5);
if (incoming.get(0)) {
struct.catName = iprot.readString();
struct.setCatNameIsSet(true);
}
if (incoming.get(1)) {
struct.partName = iprot.readString();
struct.setPartNameIsSet(true);
}
if (incoming.get(2)) {
{
org.apache.thrift.protocol.TList _list703 = iprot.readListBegin(org.apache.thrift.protocol.TType.STRING);
struct.partVals = new java.util.ArrayList<java.lang.String>(_list703.size);
@org.apache.thrift.annotation.Nullable java.lang.String _elem704;
for (int _i705 = 0; _i705 < _list703.size; ++_i705)
{
_elem704 = iprot.readString();
struct.partVals.add(_elem704);
}
}
struct.setPartValsIsSet(true);
}
if (incoming.get(3)) {
struct.deleteData = iprot.readBool();
struct.setDeleteDataIsSet(true);
}
if (incoming.get(4)) {
struct.environmentContext = new EnvironmentContext();
struct.environmentContext.read(iprot);
struct.setEnvironmentContextIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
|
apache/hadoop-common | 36,368 | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/bzip2/CBZip2InputStream.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.
*
*/
/*
* This package is based on the work done by Keiron Liddle, Aftex Software
* <keiron@aftexsw.com> to whom the Ant project is very grateful for his
* great code.
*/
package org.apache.hadoop.io.compress.bzip2;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.IOException;
import org.apache.hadoop.io.compress.SplittableCompressionCodec.READ_MODE;
/**
* An input stream that decompresses from the BZip2 format (without the file
* header chars) to be read as any other stream.
*
* <p>
* The decompression requires large amounts of memory. Thus you should call the
* {@link #close() close()} method as soon as possible, to force
* <tt>CBZip2InputStream</tt> to release the allocated memory. See
* {@link CBZip2OutputStream CBZip2OutputStream} for information about memory
* usage.
* </p>
*
* <p>
* <tt>CBZip2InputStream</tt> reads bytes from the compressed source stream via
* the single byte {@link java.io.InputStream#read() read()} method exclusively.
* Thus you should consider to use a buffered source stream.
* </p>
*
* <p>
* This Ant code was enhanced so that it can de-compress blocks of bzip2 data.
* Current position in the stream is an important statistic for Hadoop. For
* example in LineRecordReader, we solely depend on the current position in the
* stream to know about the progess. The notion of position becomes complicated
* for compressed files. The Hadoop splitting is done in terms of compressed
* file. But a compressed file deflates to a large amount of data. So we have
* handled this problem in the following way.
*
* On object creation time, we find the next block start delimiter. Once such a
* marker is found, the stream stops there (we discard any read compressed data
* in this process) and the position is updated (i.e. the caller of this class
* will find out the stream location). At this point we are ready for actual
* reading (i.e. decompression) of data.
*
* The subsequent read calls give out data. The position is updated when the
* caller of this class has read off the current block + 1 bytes. In between the
* block reading, position is not updated. (We can only update the postion on
* block boundaries).
* </p>
*
* <p>
* Instances of this class are not threadsafe.
* </p>
*/
public class CBZip2InputStream extends InputStream implements BZip2Constants {
public static final long BLOCK_DELIMITER = 0X314159265359L;// start of block
public static final long EOS_DELIMITER = 0X177245385090L;// end of bzip2 stream
private static final int DELIMITER_BIT_LENGTH = 48;
READ_MODE readMode = READ_MODE.CONTINUOUS;
// The variable records the current advertised position of the stream.
private long reportedBytesReadFromCompressedStream = 0L;
// The following variable keep record of compressed bytes read.
private long bytesReadFromCompressedStream = 0L;
private boolean lazyInitialization = false;
private byte array[] = new byte[1];
/**
* Index of the last char in the block, so the block size == last + 1.
*/
private int last;
/**
* Index in zptr[] of original string after sorting.
*/
private int origPtr;
/**
* always: in the range 0 .. 9. The current block size is 100000 * this
* number.
*/
private int blockSize100k;
private boolean blockRandomised = false;
private long bsBuff;
private long bsLive;
private final CRC crc = new CRC();
private int nInUse;
private BufferedInputStream in;
private int currentChar = -1;
/**
* A state machine to keep track of current state of the de-coder
*
*/
public enum STATE {
EOF, START_BLOCK_STATE, RAND_PART_A_STATE, RAND_PART_B_STATE, RAND_PART_C_STATE, NO_RAND_PART_A_STATE, NO_RAND_PART_B_STATE, NO_RAND_PART_C_STATE, NO_PROCESS_STATE
};
private STATE currentState = STATE.START_BLOCK_STATE;
private int storedBlockCRC, storedCombinedCRC;
private int computedBlockCRC, computedCombinedCRC;
private boolean skipResult = false;// used by skipToNextMarker
private boolean skipDecompression = false;
// Variables used by setup* methods exclusively
private int su_count;
private int su_ch2;
private int su_chPrev;
private int su_i2;
private int su_j2;
private int su_rNToGo;
private int su_rTPos;
private int su_tPos;
private char su_z;
/**
* All memory intensive stuff. This field is initialized by initBlock().
*/
private CBZip2InputStream.Data data;
/**
* This method reports the processed bytes so far. Please note that this
* statistic is only updated on block boundaries and only when the stream is
* initiated in BYBLOCK mode.
*/
public long getProcessedByteCount() {
return reportedBytesReadFromCompressedStream;
}
/**
* This method keeps track of raw processed compressed
* bytes.
*
* @param count count is the number of bytes to be
* added to raw processed bytes
*/
protected void updateProcessedByteCount(int count) {
this.bytesReadFromCompressedStream += count;
}
/**
* This method is called by the client of this
* class in case there are any corrections in
* the stream position. One common example is
* when client of this code removes starting BZ
* characters from the compressed stream.
*
* @param count count bytes are added to the reported bytes
*
*/
public void updateReportedByteCount(int count) {
this.reportedBytesReadFromCompressedStream += count;
this.updateProcessedByteCount(count);
}
/**
* This method reads a Byte from the compressed stream. Whenever we need to
* read from the underlying compressed stream, this method should be called
* instead of directly calling the read method of the underlying compressed
* stream. This method does important record keeping to have the statistic
* that how many bytes have been read off the compressed stream.
*/
private int readAByte(InputStream inStream) throws IOException {
int read = inStream.read();
if (read >= 0) {
this.updateProcessedByteCount(1);
}
return read;
}
/**
* This method tries to find the marker (passed to it as the first parameter)
* in the stream. It can find bit patterns of length <= 63 bits. Specifically
* this method is used in CBZip2InputStream to find the end of block (EOB)
* delimiter in the stream, starting from the current position of the stream.
* If marker is found, the stream position will be right after marker at the
* end of this call.
*
* @param marker The bit pattern to be found in the stream
* @param markerBitLength No of bits in the marker
*
* @throws IOException
* @throws IllegalArgumentException if marketBitLength is greater than 63
*/
public boolean skipToNextMarker(long marker, int markerBitLength)
throws IOException, IllegalArgumentException {
try {
if (markerBitLength > 63) {
throw new IllegalArgumentException(
"skipToNextMarker can not find patterns greater than 63 bits");
}
// pick next marketBitLength bits in the stream
long bytes = 0;
bytes = this.bsR(markerBitLength);
if (bytes == -1) {
return false;
}
while (true) {
if (bytes == marker) {
return true;
} else {
bytes = bytes << 1;
bytes = bytes & ((1L << markerBitLength) - 1);
int oneBit = (int) this.bsR(1);
if (oneBit != -1) {
bytes = bytes | oneBit;
} else
return false;
}
}
} catch (IOException ex) {
return false;
}
}
protected void reportCRCError() throws IOException {
throw new IOException("crc error");
}
private void makeMaps() {
final boolean[] inUse = this.data.inUse;
final byte[] seqToUnseq = this.data.seqToUnseq;
int nInUseShadow = 0;
for (int i = 0; i < 256; i++) {
if (inUse[i])
seqToUnseq[nInUseShadow++] = (byte) i;
}
this.nInUse = nInUseShadow;
}
/**
* Constructs a new CBZip2InputStream which decompresses bytes read from the
* specified stream.
*
* <p>
* Although BZip2 headers are marked with the magic <tt>"Bz"</tt> this
* constructor expects the next byte in the stream to be the first one after
* the magic. Thus callers have to skip the first two bytes. Otherwise this
* constructor will throw an exception.
* </p>
*
* @throws IOException
* if the stream content is malformed or an I/O error occurs.
* @throws NullPointerException
* if <tt>in == null</tt>
*/
public CBZip2InputStream(final InputStream in, READ_MODE readMode)
throws IOException {
this(in, readMode, false);
}
private CBZip2InputStream(final InputStream in, READ_MODE readMode, boolean skipDecompression)
throws IOException {
super();
int blockSize = 0X39;// i.e 9
this.blockSize100k = blockSize - '0';
this.in = new BufferedInputStream(in, 1024 * 9);// >1 MB buffer
this.readMode = readMode;
this.skipDecompression = skipDecompression;
if (readMode == READ_MODE.CONTINUOUS) {
currentState = STATE.START_BLOCK_STATE;
lazyInitialization = (in.available() == 0)?true:false;
if(!lazyInitialization){
init();
}
} else if (readMode == READ_MODE.BYBLOCK) {
this.currentState = STATE.NO_PROCESS_STATE;
skipResult = this.skipToNextMarker(CBZip2InputStream.BLOCK_DELIMITER,DELIMITER_BIT_LENGTH);
this.reportedBytesReadFromCompressedStream = this.bytesReadFromCompressedStream;
if(!skipDecompression){
changeStateToProcessABlock();
}
}
}
/**
* Returns the number of bytes between the current stream position
* and the immediate next BZip2 block marker.
*
* @param in
* The InputStream
*
* @return long Number of bytes between current stream position and the
* next BZip2 block start marker.
* @throws IOException
*
*/
public static long numberOfBytesTillNextMarker(final InputStream in) throws IOException{
CBZip2InputStream anObject = new CBZip2InputStream(in, READ_MODE.BYBLOCK, true);
return anObject.getProcessedByteCount();
}
public CBZip2InputStream(final InputStream in) throws IOException {
this(in, READ_MODE.CONTINUOUS);
}
private void changeStateToProcessABlock() throws IOException {
if (skipResult == true) {
initBlock();
setupBlock();
} else {
this.currentState = STATE.EOF;
}
}
@Override
public int read() throws IOException {
if (this.in != null) {
int result = this.read(array, 0, 1);
int value = 0XFF & array[0];
return (result > 0 ? value : result);
} else {
throw new IOException("stream closed");
}
}
/**
* In CONTINOUS reading mode, this read method starts from the
* start of the compressed stream and end at the end of file by
* emitting un-compressed data. In this mode stream positioning
* is not announced and should be ignored.
*
* In BYBLOCK reading mode, this read method informs about the end
* of a BZip2 block by returning EOB. At this event, the compressed
* stream position is also announced. This announcement tells that
* how much of the compressed stream has been de-compressed and read
* out of this class. In between EOB events, the stream position is
* not updated.
*
*
* @throws IOException
* if the stream content is malformed or an I/O error occurs.
*
* @return int The return value greater than 0 are the bytes read. A value
* of -1 means end of stream while -2 represents end of block
*/
@Override
public int read(final byte[] dest, final int offs, final int len)
throws IOException {
if (offs < 0) {
throw new IndexOutOfBoundsException("offs(" + offs + ") < 0.");
}
if (len < 0) {
throw new IndexOutOfBoundsException("len(" + len + ") < 0.");
}
if (offs + len > dest.length) {
throw new IndexOutOfBoundsException("offs(" + offs + ") + len("
+ len + ") > dest.length(" + dest.length + ").");
}
if (this.in == null) {
throw new IOException("stream closed");
}
if(lazyInitialization){
this.init();
this.lazyInitialization = false;
}
if(skipDecompression){
changeStateToProcessABlock();
skipDecompression = false;
}
final int hi = offs + len;
int destOffs = offs;
int b = 0;
for (; ((destOffs < hi) && ((b = read0())) >= 0);) {
dest[destOffs++] = (byte) b;
}
int result = destOffs - offs;
if (result == 0) {
//report 'end of block' or 'end of stream'
result = b;
skipResult = this.skipToNextMarker(CBZip2InputStream.BLOCK_DELIMITER, DELIMITER_BIT_LENGTH);
//Exactly when we are about to start a new block, we advertise the stream position.
this.reportedBytesReadFromCompressedStream = this.bytesReadFromCompressedStream;
changeStateToProcessABlock();
}
return result;
}
private int read0() throws IOException {
final int retChar = this.currentChar;
switch (this.currentState) {
case EOF:
return END_OF_STREAM;// return -1
case NO_PROCESS_STATE:
return END_OF_BLOCK;// return -2
case START_BLOCK_STATE:
throw new IllegalStateException();
case RAND_PART_A_STATE:
throw new IllegalStateException();
case RAND_PART_B_STATE:
setupRandPartB();
break;
case RAND_PART_C_STATE:
setupRandPartC();
break;
case NO_RAND_PART_A_STATE:
throw new IllegalStateException();
case NO_RAND_PART_B_STATE:
setupNoRandPartB();
break;
case NO_RAND_PART_C_STATE:
setupNoRandPartC();
break;
default:
throw new IllegalStateException();
}
return retChar;
}
private void init() throws IOException {
int magic2 = this.readAByte(in);
if (magic2 != 'h') {
throw new IOException("Stream is not BZip2 formatted: expected 'h'"
+ " as first byte but got '" + (char) magic2 + "'");
}
int blockSize = this.readAByte(in);
if ((blockSize < '1') || (blockSize > '9')) {
throw new IOException("Stream is not BZip2 formatted: illegal "
+ "blocksize " + (char) blockSize);
}
this.blockSize100k = blockSize - '0';
initBlock();
setupBlock();
}
private void initBlock() throws IOException {
if (this.readMode == READ_MODE.BYBLOCK) {
// this.checkBlockIntegrity();
this.storedBlockCRC = bsGetInt();
this.blockRandomised = bsR(1) == 1;
/**
* Allocate data here instead in constructor, so we do not allocate
* it if the input file is empty.
*/
if (this.data == null) {
this.data = new Data(this.blockSize100k);
}
// currBlockNo++;
getAndMoveToFrontDecode();
this.crc.initialiseCRC();
this.currentState = STATE.START_BLOCK_STATE;
return;
}
char magic0 = bsGetUByte();
char magic1 = bsGetUByte();
char magic2 = bsGetUByte();
char magic3 = bsGetUByte();
char magic4 = bsGetUByte();
char magic5 = bsGetUByte();
if (magic0 == 0x17 && magic1 == 0x72 && magic2 == 0x45
&& magic3 == 0x38 && magic4 == 0x50 && magic5 == 0x90) {
complete(); // end of file
} else if (magic0 != 0x31 || // '1'
magic1 != 0x41 || // ')'
magic2 != 0x59 || // 'Y'
magic3 != 0x26 || // '&'
magic4 != 0x53 || // 'S'
magic5 != 0x59 // 'Y'
) {
this.currentState = STATE.EOF;
throw new IOException("bad block header");
} else {
this.storedBlockCRC = bsGetInt();
this.blockRandomised = bsR(1) == 1;
/**
* Allocate data here instead in constructor, so we do not allocate
* it if the input file is empty.
*/
if (this.data == null) {
this.data = new Data(this.blockSize100k);
}
// currBlockNo++;
getAndMoveToFrontDecode();
this.crc.initialiseCRC();
this.currentState = STATE.START_BLOCK_STATE;
}
}
private void endBlock() throws IOException {
this.computedBlockCRC = this.crc.getFinalCRC();
// A bad CRC is considered a fatal error.
if (this.storedBlockCRC != this.computedBlockCRC) {
// make next blocks readable without error
// (repair feature, not yet documented, not tested)
this.computedCombinedCRC = (this.storedCombinedCRC << 1)
| (this.storedCombinedCRC >>> 31);
this.computedCombinedCRC ^= this.storedBlockCRC;
reportCRCError();
}
this.computedCombinedCRC = (this.computedCombinedCRC << 1)
| (this.computedCombinedCRC >>> 31);
this.computedCombinedCRC ^= this.computedBlockCRC;
}
private void complete() throws IOException {
this.storedCombinedCRC = bsGetInt();
this.currentState = STATE.EOF;
this.data = null;
if (this.storedCombinedCRC != this.computedCombinedCRC) {
reportCRCError();
}
}
@Override
public void close() throws IOException {
InputStream inShadow = this.in;
if (inShadow != null) {
try {
if (inShadow != System.in) {
inShadow.close();
}
} finally {
this.data = null;
this.in = null;
}
}
}
private long bsR(final long n) throws IOException {
long bsLiveShadow = this.bsLive;
long bsBuffShadow = this.bsBuff;
if (bsLiveShadow < n) {
final InputStream inShadow = this.in;
do {
int thech = readAByte(inShadow);
if (thech < 0) {
throw new IOException("unexpected end of stream");
}
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
} while (bsLiveShadow < n);
this.bsBuff = bsBuffShadow;
}
this.bsLive = bsLiveShadow - n;
return (bsBuffShadow >> (bsLiveShadow - n)) & ((1L << n) - 1);
}
private boolean bsGetBit() throws IOException {
long bsLiveShadow = this.bsLive;
long bsBuffShadow = this.bsBuff;
if (bsLiveShadow < 1) {
int thech = this.readAByte(in);
if (thech < 0) {
throw new IOException("unexpected end of stream");
}
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
this.bsBuff = bsBuffShadow;
}
this.bsLive = bsLiveShadow - 1;
return ((bsBuffShadow >> (bsLiveShadow - 1)) & 1) != 0;
}
private char bsGetUByte() throws IOException {
return (char) bsR(8);
}
private int bsGetInt() throws IOException {
return (int) ((((((bsR(8) << 8) | bsR(8)) << 8) | bsR(8)) << 8) | bsR(8));
}
/**
* Called by createHuffmanDecodingTables() exclusively.
*/
private static void hbCreateDecodeTables(final int[] limit,
final int[] base, final int[] perm, final char[] length,
final int minLen, final int maxLen, final int alphaSize) {
for (int i = minLen, pp = 0; i <= maxLen; i++) {
for (int j = 0; j < alphaSize; j++) {
if (length[j] == i) {
perm[pp++] = j;
}
}
}
for (int i = MAX_CODE_LEN; --i > 0;) {
base[i] = 0;
limit[i] = 0;
}
for (int i = 0; i < alphaSize; i++) {
base[length[i] + 1]++;
}
for (int i = 1, b = base[0]; i < MAX_CODE_LEN; i++) {
b += base[i];
base[i] = b;
}
for (int i = minLen, vec = 0, b = base[i]; i <= maxLen; i++) {
final int nb = base[i + 1];
vec += nb - b;
b = nb;
limit[i] = vec - 1;
vec <<= 1;
}
for (int i = minLen + 1; i <= maxLen; i++) {
base[i] = ((limit[i - 1] + 1) << 1) - base[i];
}
}
private void recvDecodingTables() throws IOException {
final Data dataShadow = this.data;
final boolean[] inUse = dataShadow.inUse;
final byte[] pos = dataShadow.recvDecodingTables_pos;
final byte[] selector = dataShadow.selector;
final byte[] selectorMtf = dataShadow.selectorMtf;
int inUse16 = 0;
/* Receive the mapping table */
for (int i = 0; i < 16; i++) {
if (bsGetBit()) {
inUse16 |= 1 << i;
}
}
for (int i = 256; --i >= 0;) {
inUse[i] = false;
}
for (int i = 0; i < 16; i++) {
if ((inUse16 & (1 << i)) != 0) {
final int i16 = i << 4;
for (int j = 0; j < 16; j++) {
if (bsGetBit()) {
inUse[i16 + j] = true;
}
}
}
}
makeMaps();
final int alphaSize = this.nInUse + 2;
/* Now the selectors */
final int nGroups = (int) bsR(3);
final int nSelectors = (int) bsR(15);
for (int i = 0; i < nSelectors; i++) {
int j = 0;
while (bsGetBit()) {
j++;
}
selectorMtf[i] = (byte) j;
}
/* Undo the MTF values for the selectors. */
for (int v = nGroups; --v >= 0;) {
pos[v] = (byte) v;
}
for (int i = 0; i < nSelectors; i++) {
int v = selectorMtf[i] & 0xff;
final byte tmp = pos[v];
while (v > 0) {
// nearly all times v is zero, 4 in most other cases
pos[v] = pos[v - 1];
v--;
}
pos[0] = tmp;
selector[i] = tmp;
}
final char[][] len = dataShadow.temp_charArray2d;
/* Now the coding tables */
for (int t = 0; t < nGroups; t++) {
int curr = (int) bsR(5);
final char[] len_t = len[t];
for (int i = 0; i < alphaSize; i++) {
while (bsGetBit()) {
curr += bsGetBit() ? -1 : 1;
}
len_t[i] = (char) curr;
}
}
// finally create the Huffman tables
createHuffmanDecodingTables(alphaSize, nGroups);
}
/**
* Called by recvDecodingTables() exclusively.
*/
private void createHuffmanDecodingTables(final int alphaSize,
final int nGroups) {
final Data dataShadow = this.data;
final char[][] len = dataShadow.temp_charArray2d;
final int[] minLens = dataShadow.minLens;
final int[][] limit = dataShadow.limit;
final int[][] base = dataShadow.base;
final int[][] perm = dataShadow.perm;
for (int t = 0; t < nGroups; t++) {
int minLen = 32;
int maxLen = 0;
final char[] len_t = len[t];
for (int i = alphaSize; --i >= 0;) {
final char lent = len_t[i];
if (lent > maxLen) {
maxLen = lent;
}
if (lent < minLen) {
minLen = lent;
}
}
hbCreateDecodeTables(limit[t], base[t], perm[t], len[t], minLen,
maxLen, alphaSize);
minLens[t] = minLen;
}
}
private void getAndMoveToFrontDecode() throws IOException {
this.origPtr = (int) bsR(24);
recvDecodingTables();
final InputStream inShadow = this.in;
final Data dataShadow = this.data;
final byte[] ll8 = dataShadow.ll8;
final int[] unzftab = dataShadow.unzftab;
final byte[] selector = dataShadow.selector;
final byte[] seqToUnseq = dataShadow.seqToUnseq;
final char[] yy = dataShadow.getAndMoveToFrontDecode_yy;
final int[] minLens = dataShadow.minLens;
final int[][] limit = dataShadow.limit;
final int[][] base = dataShadow.base;
final int[][] perm = dataShadow.perm;
final int limitLast = this.blockSize100k * 100000;
/*
* Setting up the unzftab entries here is not strictly necessary, but it
* does save having to do it later in a separate pass, and so saves a
* block's worth of cache misses.
*/
for (int i = 256; --i >= 0;) {
yy[i] = (char) i;
unzftab[i] = 0;
}
int groupNo = 0;
int groupPos = G_SIZE - 1;
final int eob = this.nInUse + 1;
int nextSym = getAndMoveToFrontDecode0(0);
int bsBuffShadow = (int) this.bsBuff;
int bsLiveShadow = (int) this.bsLive;
int lastShadow = -1;
int zt = selector[groupNo] & 0xff;
int[] base_zt = base[zt];
int[] limit_zt = limit[zt];
int[] perm_zt = perm[zt];
int minLens_zt = minLens[zt];
while (nextSym != eob) {
if ((nextSym == RUNA) || (nextSym == RUNB)) {
int s = -1;
for (int n = 1; true; n <<= 1) {
if (nextSym == RUNA) {
s += n;
} else if (nextSym == RUNB) {
s += n << 1;
} else {
break;
}
if (groupPos == 0) {
groupPos = G_SIZE - 1;
zt = selector[++groupNo] & 0xff;
base_zt = base[zt];
limit_zt = limit[zt];
perm_zt = perm[zt];
minLens_zt = minLens[zt];
} else {
groupPos--;
}
int zn = minLens_zt;
while (bsLiveShadow < zn) {
final int thech = readAByte(inShadow);
if (thech >= 0) {
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
} else {
throw new IOException("unexpected end of stream");
}
}
long zvec = (bsBuffShadow >> (bsLiveShadow - zn))
& ((1 << zn) - 1);
bsLiveShadow -= zn;
while (zvec > limit_zt[zn]) {
zn++;
while (bsLiveShadow < 1) {
final int thech = readAByte(inShadow);
if (thech >= 0) {
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
} else {
throw new IOException(
"unexpected end of stream");
}
}
bsLiveShadow--;
zvec = (zvec << 1)
| ((bsBuffShadow >> bsLiveShadow) & 1);
}
nextSym = perm_zt[(int) (zvec - base_zt[zn])];
}
final byte ch = seqToUnseq[yy[0]];
unzftab[ch & 0xff] += s + 1;
while (s-- >= 0) {
ll8[++lastShadow] = ch;
}
if (lastShadow >= limitLast) {
throw new IOException("block overrun");
}
} else {
if (++lastShadow >= limitLast) {
throw new IOException("block overrun");
}
final char tmp = yy[nextSym - 1];
unzftab[seqToUnseq[tmp] & 0xff]++;
ll8[lastShadow] = seqToUnseq[tmp];
/*
* This loop is hammered during decompression, hence avoid
* native method call overhead of System.arraycopy for very
* small ranges to copy.
*/
if (nextSym <= 16) {
for (int j = nextSym - 1; j > 0;) {
yy[j] = yy[--j];
}
} else {
System.arraycopy(yy, 0, yy, 1, nextSym - 1);
}
yy[0] = tmp;
if (groupPos == 0) {
groupPos = G_SIZE - 1;
zt = selector[++groupNo] & 0xff;
base_zt = base[zt];
limit_zt = limit[zt];
perm_zt = perm[zt];
minLens_zt = minLens[zt];
} else {
groupPos--;
}
int zn = minLens_zt;
while (bsLiveShadow < zn) {
final int thech = readAByte(inShadow);
if (thech >= 0) {
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
} else {
throw new IOException("unexpected end of stream");
}
}
int zvec = (bsBuffShadow >> (bsLiveShadow - zn))
& ((1 << zn) - 1);
bsLiveShadow -= zn;
while (zvec > limit_zt[zn]) {
zn++;
while (bsLiveShadow < 1) {
final int thech = readAByte(inShadow);
if (thech >= 0) {
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
} else {
throw new IOException("unexpected end of stream");
}
}
bsLiveShadow--;
zvec = ((zvec << 1) | ((bsBuffShadow >> bsLiveShadow) & 1));
}
nextSym = perm_zt[zvec - base_zt[zn]];
}
}
this.last = lastShadow;
this.bsLive = bsLiveShadow;
this.bsBuff = bsBuffShadow;
}
private int getAndMoveToFrontDecode0(final int groupNo) throws IOException {
final InputStream inShadow = this.in;
final Data dataShadow = this.data;
final int zt = dataShadow.selector[groupNo] & 0xff;
final int[] limit_zt = dataShadow.limit[zt];
int zn = dataShadow.minLens[zt];
int zvec = (int) bsR(zn);
int bsLiveShadow = (int) this.bsLive;
int bsBuffShadow = (int) this.bsBuff;
while (zvec > limit_zt[zn]) {
zn++;
while (bsLiveShadow < 1) {
final int thech = readAByte(inShadow);
if (thech >= 0) {
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
} else {
throw new IOException("unexpected end of stream");
}
}
bsLiveShadow--;
zvec = (zvec << 1) | ((bsBuffShadow >> bsLiveShadow) & 1);
}
this.bsLive = bsLiveShadow;
this.bsBuff = bsBuffShadow;
return dataShadow.perm[zt][zvec - dataShadow.base[zt][zn]];
}
private void setupBlock() throws IOException {
if (this.data == null) {
return;
}
final int[] cftab = this.data.cftab;
final int[] tt = this.data.initTT(this.last + 1);
final byte[] ll8 = this.data.ll8;
cftab[0] = 0;
System.arraycopy(this.data.unzftab, 0, cftab, 1, 256);
for (int i = 1, c = cftab[0]; i <= 256; i++) {
c += cftab[i];
cftab[i] = c;
}
for (int i = 0, lastShadow = this.last; i <= lastShadow; i++) {
tt[cftab[ll8[i] & 0xff]++] = i;
}
if ((this.origPtr < 0) || (this.origPtr >= tt.length)) {
throw new IOException("stream corrupted");
}
this.su_tPos = tt[this.origPtr];
this.su_count = 0;
this.su_i2 = 0;
this.su_ch2 = 256; /* not a char and not EOF */
if (this.blockRandomised) {
this.su_rNToGo = 0;
this.su_rTPos = 0;
setupRandPartA();
} else {
setupNoRandPartA();
}
}
private void setupRandPartA() throws IOException {
if (this.su_i2 <= this.last) {
this.su_chPrev = this.su_ch2;
int su_ch2Shadow = this.data.ll8[this.su_tPos] & 0xff;
this.su_tPos = this.data.tt[this.su_tPos];
if (this.su_rNToGo == 0) {
this.su_rNToGo = BZip2Constants.rNums[this.su_rTPos] - 1;
if (++this.su_rTPos == 512) {
this.su_rTPos = 0;
}
} else {
this.su_rNToGo--;
}
this.su_ch2 = su_ch2Shadow ^= (this.su_rNToGo == 1) ? 1 : 0;
this.su_i2++;
this.currentChar = su_ch2Shadow;
this.currentState = STATE.RAND_PART_B_STATE;
this.crc.updateCRC(su_ch2Shadow);
} else {
endBlock();
if (readMode == READ_MODE.CONTINUOUS) {
initBlock();
setupBlock();
} else if (readMode == READ_MODE.BYBLOCK) {
this.currentState = STATE.NO_PROCESS_STATE;
}
}
}
private void setupNoRandPartA() throws IOException {
if (this.su_i2 <= this.last) {
this.su_chPrev = this.su_ch2;
int su_ch2Shadow = this.data.ll8[this.su_tPos] & 0xff;
this.su_ch2 = su_ch2Shadow;
this.su_tPos = this.data.tt[this.su_tPos];
this.su_i2++;
this.currentChar = su_ch2Shadow;
this.currentState = STATE.NO_RAND_PART_B_STATE;
this.crc.updateCRC(su_ch2Shadow);
} else {
this.currentState = STATE.NO_RAND_PART_A_STATE;
endBlock();
if (readMode == READ_MODE.CONTINUOUS) {
initBlock();
setupBlock();
} else if (readMode == READ_MODE.BYBLOCK) {
this.currentState = STATE.NO_PROCESS_STATE;
}
}
}
private void setupRandPartB() throws IOException {
if (this.su_ch2 != this.su_chPrev) {
this.currentState = STATE.RAND_PART_A_STATE;
this.su_count = 1;
setupRandPartA();
} else if (++this.su_count >= 4) {
this.su_z = (char) (this.data.ll8[this.su_tPos] & 0xff);
this.su_tPos = this.data.tt[this.su_tPos];
if (this.su_rNToGo == 0) {
this.su_rNToGo = BZip2Constants.rNums[this.su_rTPos] - 1;
if (++this.su_rTPos == 512) {
this.su_rTPos = 0;
}
} else {
this.su_rNToGo--;
}
this.su_j2 = 0;
this.currentState = STATE.RAND_PART_C_STATE;
if (this.su_rNToGo == 1) {
this.su_z ^= 1;
}
setupRandPartC();
} else {
this.currentState = STATE.RAND_PART_A_STATE;
setupRandPartA();
}
}
private void setupRandPartC() throws IOException {
if (this.su_j2 < this.su_z) {
this.currentChar = this.su_ch2;
this.crc.updateCRC(this.su_ch2);
this.su_j2++;
} else {
this.currentState = STATE.RAND_PART_A_STATE;
this.su_i2++;
this.su_count = 0;
setupRandPartA();
}
}
private void setupNoRandPartB() throws IOException {
if (this.su_ch2 != this.su_chPrev) {
this.su_count = 1;
setupNoRandPartA();
} else if (++this.su_count >= 4) {
this.su_z = (char) (this.data.ll8[this.su_tPos] & 0xff);
this.su_tPos = this.data.tt[this.su_tPos];
this.su_j2 = 0;
setupNoRandPartC();
} else {
setupNoRandPartA();
}
}
private void setupNoRandPartC() throws IOException {
if (this.su_j2 < this.su_z) {
int su_ch2Shadow = this.su_ch2;
this.currentChar = su_ch2Shadow;
this.crc.updateCRC(su_ch2Shadow);
this.su_j2++;
this.currentState = STATE.NO_RAND_PART_C_STATE;
} else {
this.su_i2++;
this.su_count = 0;
setupNoRandPartA();
}
}
private static final class Data extends Object {
// (with blockSize 900k)
final boolean[] inUse = new boolean[256]; // 256 byte
final byte[] seqToUnseq = new byte[256]; // 256 byte
final byte[] selector = new byte[MAX_SELECTORS]; // 18002 byte
final byte[] selectorMtf = new byte[MAX_SELECTORS]; // 18002 byte
/**
* Freq table collected to save a pass over the data during
* decompression.
*/
final int[] unzftab = new int[256]; // 1024 byte
final int[][] limit = new int[N_GROUPS][MAX_ALPHA_SIZE]; // 6192 byte
final int[][] base = new int[N_GROUPS][MAX_ALPHA_SIZE]; // 6192 byte
final int[][] perm = new int[N_GROUPS][MAX_ALPHA_SIZE]; // 6192 byte
final int[] minLens = new int[N_GROUPS]; // 24 byte
final int[] cftab = new int[257]; // 1028 byte
final char[] getAndMoveToFrontDecode_yy = new char[256]; // 512 byte
final char[][] temp_charArray2d = new char[N_GROUPS][MAX_ALPHA_SIZE]; // 3096
// byte
final byte[] recvDecodingTables_pos = new byte[N_GROUPS]; // 6 byte
// ---------------
// 60798 byte
int[] tt; // 3600000 byte
byte[] ll8; // 900000 byte
// ---------------
// 4560782 byte
// ===============
Data(int blockSize100k) {
super();
this.ll8 = new byte[blockSize100k * BZip2Constants.baseBlockSize];
}
/**
* Initializes the {@link #tt} array.
*
* This method is called when the required length of the array is known.
* I don't initialize it at construction time to avoid unneccessary
* memory allocation when compressing small files.
*/
final int[] initTT(int length) {
int[] ttShadow = this.tt;
// tt.length should always be >= length, but theoretically
// it can happen, if the compressor mixed small and large
// blocks. Normally only the last block will be smaller
// than others.
if ((ttShadow == null) || (ttShadow.length < length)) {
this.tt = ttShadow = new int[length];
}
return ttShadow;
}
}
}
|
apache/datasketches-java | 36,746 | src/main/java/org/apache/datasketches/cpc/PreambleUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.datasketches.cpc;
import static java.lang.foreign.ValueLayout.JAVA_BYTE;
import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED;
import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED;
import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED;
import static org.apache.datasketches.common.Util.LS;
import static org.apache.datasketches.common.Util.checkBounds;
import static org.apache.datasketches.common.Util.clear;
import static org.apache.datasketches.common.Util.zeroPad;
import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssert;
import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssertEquals;
import java.lang.foreign.MemorySegment;
import java.util.Objects;
import org.apache.datasketches.common.Family;
import org.apache.datasketches.common.SketchesArgumentException;
import org.apache.datasketches.common.SketchesStateException;
//@formatter:off
/**
* All formats are illustrated as Big-Endian, LSB on the right.
*
* <pre>
* Format = EMPTY_MERGED/EMPTY_HIP: NoWindow, NoSV, HIP or NoHIP = 00X.
* The first 8 bytes are common for all Formats.
* PI = 2, FIcol = 0
* Long adr ||
* || 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
* 0 ||---SEED HASH-----|-Flags--|-FIcol--|---lgK--|-FamID--|-SerVer-|---PI---|
*
*
* Format = SPARSE_HYBRID_MERGED: {NoWindow, SV, NoHIP} = 2 = 010.
* PI = 4, FIcol = 0
* Long adr ||
* || 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 |
* 1 ||-------------SV Length Ints--------|--------numCoupons = numSV---------|
*
* || 23 | 22 | 21 | 20 | 19 | 18 | 17 | 16 |
* 2 || |----------Start SV bit stream------|
*
*
* Format = SPARSE_HYBRID_HIP: {NoWindow, SV, HIP} = 3 = 011
* PI = 8, FIcol = 0
* Long adr ||
* || 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 |
* 1 ||-------------SV Length Ints--------|--------numCoupons = numSV---------|
*
* || 23 | 22 | 21 | 20 | 19 | 18 | 17 | 16 |
* 2 ||----------------------------------KxP----------------------------------|
*
* || 31 | 30 | 29 | 28 | 27 | 26 | 25 | 24 |
* 3 ||-------------------------------HIP Accum-------------------------------|
*
* || 39 | 38 | 37 | 36 | 35 | 34 | 33 | 32 |
* 4 || |----------Start of SV stream-------|
*
*
* Format = PINNED_SLIDING_MERGED_NOSV: {Window, No SV, NoHIP} = 4 = 100
* PI = 4, FIcol = valid
* Long adr ||
* || 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 |
* 1 ||----------Window Length Ints-------|------------numCoupons-------------|
*
* || 23 | 22 | 21 | 20 | 19 | 18 | 17 | 16 |
* 2 || |--------Start of Window stream-----|
*
*
* Format = PINNED_SLIDING_HIP_NOSV: {Window, No SV, HIP} = 5 = 101
* PI = 8, FIcol = valid
* Long adr ||
* || 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 |
* 1 ||----------Window Length Ints-------|------------numCoupons-------------|
*
* || 23 | 22 | 21 | 20 | 19 | 18 | 17 | 16 |
* 2 ||----------------------------------KxP----------------------------------|
*
* || 31 | 30 | 29 | 28 | 27 | 26 | 25 | 24 |
* 3 ||-------------------------------HIP Accum-------------------------------|
*
* || 39 | 38 | 37 | 36 | 35 | 34 | 33 | 32 |
* 4 || |--------Start of Window stream-----|
*
*
* Format = PINNED_SLIDING_MERGED: {Window, SV, NoHIP} = 6 = 110
* PI = 6, FIcol = valid
* Long adr ||
* || 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 |
* 1 ||---------------numSV---------------|------------numCoupons-------------|
*
* || 23 | 22 | 21 | 20 | 19 | 18 | 17 | 16 |
* 2 ||----------Window Length Ints-------|-------------SV Length Ints--------|
*
* || XX | XX | XX | XX | 27 | 26 | 25 | 24 |
* 3 ||--------Start of SV stream---------|--------Start of Window stream-----|
*
*
* Format = PINNED_SLIDING_HIP: {Window, SV, HIP} = 7 = 111
* PI = 10, FIcol = valid
* Long adr ||
* || 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 |
* 1 ||---------------numSV---------------|------------numCoupons-------------|
*
* || 23 | 22 | 21 | 20 | 19 | 18 | 17 | 16 |
* 2 ||----------------------------------KxP----------------------------------|
*
* || 31 | 30 | 29 | 28 | 27 | 26 | 25 | 24 |
* 3 ||-------------------------------HIP Accum-------------------------------|
*
* || 39 | 38 | 37 | 36 | 35 | 34 | 33 | 32 |
* 4 ||----------Window Length Ints-------|-------------SV Length Ints--------|
*
* || XX | XX | XX | XX | 43 | 42 | 41 | 40 |
* 5 ||--------Start of SV stream---------|--------Start of Window stream-----|
* </pre>
*
* @author Lee Rhodes
* @author Kevin Lang
*/
final class PreambleUtil {
private PreambleUtil() {}
private static final String fmt = "%10d%10x";
/**
* The serialization version for the set of serialization formats defined in this class
*/
static final byte SER_VER = 1;
//Flag bit masks, Byte 5
static final int RESERVED_FLAG_MASK = 1; //Reserved.
static final int COMPRESSED_FLAG_MASK = 2;
static final int HIP_FLAG_MASK = 4;
static final int SUP_VAL_FLAG_MASK = 8; //num Suprising Values > 0
static final int WINDOW_FLAG_MASK = 16;//window length > 0
//PREAMBLE SIZE
/**
* This defines the preamble space required by each of the formats in units of 4-byte integers.
*/
private static final byte[] preIntDefs = { 2, 2, 4, 8, 4, 8, 6, 10 };
/**
* Returns the defined size of the preamble in units of integers (4 bytes) given the
* <i>Format</i>.
* @param format the given <i>Format</i>.
* @return the defined size of the preamble in units of integers (4 bytes) given the <i>Format</i>.
*/
static byte getDefinedPreInts(final Format format) {
return preIntDefs[format.ordinal()];
}
//PREAMBLE LO_FIELD DEFINITIONS, OFFSETS, AND GETS
/**
* This defines the seven fields of the first eight bytes of the preamble.
* The ordinal of these values defines the byte offset.
* Do not change the order.
*/
enum LoField { PRE_INTS, SER_VERSION, FAMILY, LG_K, FI_COL, FLAGS, SEED_HASH }
/**
* Returns the defined byte offset from the start of the preamble given a <i>LoField</i>.
* This only applies to the first 8 bytes of the preamble.
* @param loField the given <i>LoField</i>.
* @return the defined byte offset from the start of the preamble given a <i>LoField</i>.
*/
static int getLoFieldOffset(final LoField loField) {
return loField.ordinal();
}
static int getPreInts(final MemorySegment seg) {
return seg.get(JAVA_BYTE, getLoFieldOffset(LoField.PRE_INTS)) & 0XFF;
}
static int getSerVer(final MemorySegment seg) {
return seg.get(JAVA_BYTE, getLoFieldOffset(LoField.SER_VERSION)) & 0XFF;
}
static Family getFamily(final MemorySegment seg) {
final int fam = seg.get(JAVA_BYTE, getLoFieldOffset(LoField.FAMILY)) & 0XFF;
return Family.idToFamily(fam);
}
static int getLgK(final MemorySegment seg) {
return seg.get(JAVA_BYTE, getLoFieldOffset(LoField.LG_K)) & 0XFF;
}
static int getFiCol(final MemorySegment seg) {
return seg.get(JAVA_BYTE, getLoFieldOffset(LoField.FI_COL)) & 0XFF;
}
static int getFlags(final MemorySegment seg) {
return seg.get(JAVA_BYTE, getLoFieldOffset(LoField.FLAGS)) & 0XFF;
}
static short getSeedHash(final MemorySegment seg) {
return seg.get(JAVA_SHORT_UNALIGNED, getLoFieldOffset(LoField.SEED_HASH));
}
static int getFormatOrdinal(final MemorySegment seg) {
final int flags = getFlags(seg);
return (flags >>> 2) & 0x7;
}
static Format getFormat(final MemorySegment seg) {
final int ordinal = getFormatOrdinal(seg);
return Format.ordinalToFormat(ordinal);
}
static boolean hasHip(final MemorySegment seg) {
return (getFlags(seg) & HIP_FLAG_MASK) > 0;
}
static boolean hasSv(final MemorySegment seg) {
return (getFlags(seg) & SUP_VAL_FLAG_MASK) > 0;
}
static boolean hasWindow(final MemorySegment seg) {
return (getFlags(seg) & WINDOW_FLAG_MASK) > 0;
}
static boolean isCompressed(final MemorySegment seg) {
return (getFlags(seg) & COMPRESSED_FLAG_MASK) > 0;
}
//PREAMBLE HI_FIELD DEFINITIONS
/**
* This defines the eight additional preamble fields located after the <i>LoField</i>.
* Do not change the order.
*
* <p>Note: NUM_SV has dual meanings: In sparse and hybrid flavors it is equivalent to
* numCoupons so it isn't stored separately. In pinned and sliding flavors is is the
* numSV of the PairTable, which stores only surprising values.</p>
*/
enum HiField { NUM_COUPONS, NUM_SV, KXP, HIP_ACCUM, SV_LENGTH_INTS, W_LENGTH_INTS, SV_STREAM,
W_STREAM }
//PREAMBLE HI_FIELD OFFSETS
/**
* This defines the byte offset for eac of the 8 <i>HiFields</i>
* given the Format ordinal (1st dimension) and the HiField ordinal (2nd dimension).
*/
private static final byte[][] hiFieldOffset = //[Format][HiField]
{ {0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{8, 0, 0, 0, 12, 0, 16, 0},
{8, 0, 16, 24, 12, 0, 32, 0},
{8, 0, 0, 0, 0, 12, 0, 16},
{8, 0, 16, 24, 0, 12, 0, 32},
{8, 12, 0, 0, 16, 20, 24, 24}, //the 2nd 24 is not used.
{8, 12, 16, 24, 32, 36, 40, 40} //the 2nd 40 is not used.
};
/**
* Returns the defined byte offset from the start of the preamble given the <i>HiField</i>
* and the <i>Format</i>.
* Note this can not be used to obtain the stream offsets.
* @param format the desired <i>Format</i>
* @param hiField the desired preamble <i>HiField</i> after the first eight bytes.
* @return the defined byte offset from the start of the preamble for the given <i>HiField</i>
* and the <i>Format</i>.
*/
static long getHiFieldOffset(final Format format, final HiField hiField) {
final int formatIdx = format.ordinal();
final int hiFieldIdx = hiField.ordinal();
final long fieldOffset = hiFieldOffset[formatIdx][hiFieldIdx] & 0xFF; //initially a byte
if (fieldOffset == 0) {
throw new SketchesStateException("Undefined preamble field given the Format: "
+ "Format: " + format.toString() + ", HiField: " + hiField.toString());
}
return fieldOffset;
}
//PREAMBLE HI_FIELD GETS
static int getNumCoupons(final MemorySegment seg) {
final Format format = getFormat(seg);
final HiField hiField = HiField.NUM_COUPONS;
final long offset = getHiFieldOffset(format, hiField);
return seg.get(JAVA_INT_UNALIGNED, offset);
}
static int getNumSv(final MemorySegment seg) {
final Format format = getFormat(seg);
final HiField hiField = HiField.NUM_SV;
final long offset = getHiFieldOffset(format, hiField);
return seg.get(JAVA_INT_UNALIGNED, offset);
}
static int getSvLengthInts(final MemorySegment seg) {
final Format format = getFormat(seg);
final HiField hiField = HiField.SV_LENGTH_INTS;
final long offset = getHiFieldOffset(format, hiField);
return seg.get(JAVA_INT_UNALIGNED, offset);
}
static int getWLengthInts(final MemorySegment seg) {
final Format format = getFormat(seg);
final HiField hiField = HiField.W_LENGTH_INTS;
final long offset = getHiFieldOffset(format, hiField);
return seg.get(JAVA_INT_UNALIGNED, offset);
}
static double getKxP(final MemorySegment seg) {
final Format format = getFormat(seg);
final HiField hiField = HiField.KXP;
final long offset = getHiFieldOffset(format, hiField);
return seg.get(JAVA_DOUBLE_UNALIGNED, offset);
}
static double getHipAccum(final MemorySegment seg) {
final Format format = getFormat(seg);
final HiField hiField = HiField.HIP_ACCUM;
final long offset = getHiFieldOffset(format, hiField);
return seg.get(JAVA_DOUBLE_UNALIGNED, offset);
}
static long getSvStreamOffset(final MemorySegment seg) {
final Format format = getFormat(seg);
final HiField svLenField = HiField.SV_LENGTH_INTS;
if (!hasSv(seg)) {
fieldError(format, svLenField);
} else {
final long svLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS)) & 0XFFFF_FFFFL;
if (svLengthInts == 0) {
throw new SketchesStateException("svLengthInts cannot be zero");
}
}
long wLengthInts = 0;
if (hasWindow(seg)) {
wLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS)) & 0XFFFF_FFFFL;
if (wLengthInts == 0) {
throw new SketchesStateException("wLengthInts cannot be zero");
}
}
return (getPreInts(seg) + wLengthInts) << 2;
}
static long getWStreamOffset(final MemorySegment seg) {
final Format format = getFormat(seg);
final HiField wLenField = HiField.W_LENGTH_INTS;
if (!hasWindow(seg)) { fieldError(format, wLenField); }
final long wLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS)) & 0XFFFF_FFFFL;
if (wLengthInts == 0) {
throw new SketchesStateException("wLengthInts cannot be zero");
}
return getPreInts(seg) << 2;
}
static int[] getSvStream(final MemorySegment seg) {
final long offset = getSvStreamOffset(seg);
final int svLengthInts = getSvLengthInts(seg);
final int[] svStream = new int[svLengthInts];
MemorySegment.copy(seg, JAVA_INT_UNALIGNED, offset, svStream, 0, svLengthInts);
return svStream;
}
static int[] getWStream(final MemorySegment seg) {
final long offset = getWStreamOffset(seg);
final int wLength = getWLengthInts(seg);
final int[] wStream = new int[wLength];
MemorySegment.copy(seg, JAVA_INT_UNALIGNED, offset, wStream, 0, wLength);
return wStream;
}
// PUT INTO MEMORY
static void putEmptyMerged(final MemorySegment wseg,
final int lgK,
final short seedHash) {
final Format format = Format.EMPTY_MERGED;
final byte preInts = getDefinedPreInts(format);
final byte fiCol = (byte) 0;
final byte flags = (byte) ((format.ordinal() << 2) | COMPRESSED_FLAG_MASK);
checkCapacity(wseg.byteSize(), 8);
putFirst8(wseg, preInts, (byte) lgK, fiCol, flags, seedHash);
}
static void putEmptyHip(final MemorySegment wseg,
final int lgK,
final short seedHash) {
final Format format = Format.EMPTY_HIP;
final byte preInts = getDefinedPreInts(format);
final byte fiCol = (byte) 0;
final byte flags = (byte) ((format.ordinal() << 2) | COMPRESSED_FLAG_MASK);
checkCapacity(wseg.byteSize(), 8);
putFirst8(wseg, preInts, (byte) lgK, fiCol, flags, seedHash);
}
static void putSparseHybridMerged(final MemorySegment wseg,
final int lgK,
final int numCoupons, //unsigned
final int svLengthInts,
final short seedHash,
final int[] svStream) {
final Format format = Format.SPARSE_HYBRID_MERGED;
final byte preInts = getDefinedPreInts(format);
final byte fiCol = (byte) 0;
final byte flags = (byte) ((format.ordinal() << 2) | COMPRESSED_FLAG_MASK);
checkCapacity(wseg.byteSize(), 4L * (preInts + svLengthInts));
putFirst8(wseg, preInts, (byte) lgK, fiCol, flags, seedHash);
wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS), numCoupons);
wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS), svLengthInts);
MemorySegment.copy(svStream, 0, wseg, JAVA_INT_UNALIGNED, getSvStreamOffset(wseg), svLengthInts);
}
static void putSparseHybridHip(final MemorySegment wseg,
final int lgK,
final int numCoupons, //unsigned
final int svLengthInts,
final double kxp,
final double hipAccum,
final short seedHash,
final int[] svStream) {
final Format format = Format.SPARSE_HYBRID_HIP;
final byte preInts = getDefinedPreInts(format);
final byte fiCol = (byte) 0;
final byte flags = (byte) ((format.ordinal() << 2) | COMPRESSED_FLAG_MASK);
checkCapacity(wseg.byteSize(), 4L * (preInts + svLengthInts));
putFirst8(wseg, preInts, (byte) lgK, fiCol, flags, seedHash);
wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS), numCoupons);
wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS), svLengthInts);
wseg.set(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.KXP), kxp);
wseg.set(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.HIP_ACCUM), hipAccum);
MemorySegment.copy(svStream, 0, wseg, JAVA_INT_UNALIGNED, getSvStreamOffset(wseg), svLengthInts);
}
static void putPinnedSlidingMergedNoSv(final MemorySegment wseg,
final int lgK,
final int fiCol,
final int numCoupons, //unsigned
final int wLengthInts,
final short seedHash,
final int[] wStream) {
final Format format = Format.PINNED_SLIDING_MERGED_NOSV;
final byte preInts = getDefinedPreInts(format);
final byte flags = (byte) ((format.ordinal() << 2) | COMPRESSED_FLAG_MASK);
checkCapacity(wseg.byteSize(), 4L * (preInts + wLengthInts));
putFirst8(wseg, preInts, (byte) lgK, (byte) fiCol, flags, seedHash);
wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS), numCoupons);
wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS), wLengthInts);
MemorySegment.copy(wStream, 0, wseg, JAVA_INT_UNALIGNED, getWStreamOffset(wseg), wLengthInts);
}
static void putPinnedSlidingHipNoSv(final MemorySegment wseg,
final int lgK,
final int fiCol,
final int numCoupons, //unsigned
final int wLengthInts,
final double kxp,
final double hipAccum,
final short seedHash,
final int[] wStream) {
final Format format = Format.PINNED_SLIDING_HIP_NOSV;
final byte preInts = getDefinedPreInts(format);
final byte flags = (byte) ((format.ordinal() << 2) | COMPRESSED_FLAG_MASK);
checkCapacity(wseg.byteSize(), 4L * (preInts + wLengthInts));
putFirst8(wseg, preInts, (byte) lgK, (byte) fiCol, flags, seedHash);
wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS), numCoupons);
wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS), wLengthInts);
wseg.set(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.KXP), kxp);
wseg.set(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.HIP_ACCUM), hipAccum);
MemorySegment.copy(wStream, 0, wseg, JAVA_INT_UNALIGNED, getWStreamOffset(wseg), wLengthInts);
}
static void putPinnedSlidingMerged(final MemorySegment wseg,
final int lgK,
final int fiCol,
final int numCoupons, //unsigned
final int numSv,
final int svLengthInts,
final int wLengthInts,
final short seedHash,
final int[] svStream,
final int[] wStream) {
final Format format = Format.PINNED_SLIDING_MERGED;
final byte preInts = getDefinedPreInts(format);
final byte flags = (byte) ((format.ordinal() << 2) | COMPRESSED_FLAG_MASK);
checkCapacity(wseg.byteSize(), 4L * (preInts + svLengthInts + wLengthInts));
putFirst8(wseg, preInts, (byte) lgK, (byte) fiCol, flags, seedHash);
wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS), numCoupons);
wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_SV), numSv);
wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS), svLengthInts);
wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS), wLengthInts);
MemorySegment.copy(svStream, 0, wseg, JAVA_INT_UNALIGNED, getSvStreamOffset(wseg), svLengthInts);
MemorySegment.copy(wStream, 0, wseg, JAVA_INT_UNALIGNED, getWStreamOffset(wseg), wLengthInts);
}
static void putPinnedSlidingHip(final MemorySegment wseg,
final int lgK,
final int fiCol,
final int numCoupons, //unsigned
final int numSv,
final double kxp,
final double hipAccum,
final int svLengthInts,
final int wLengthInts,
final short seedHash,
final int[] svStream,
final int[] wStream) {
final Format format = Format.PINNED_SLIDING_HIP;
final byte preInts = getDefinedPreInts(format);
final byte flags = (byte) ((format.ordinal() << 2) | COMPRESSED_FLAG_MASK);
checkCapacity(wseg.byteSize(), 4L * (preInts + svLengthInts + wLengthInts));
putFirst8(wseg, preInts, (byte) lgK, (byte) fiCol, flags, seedHash);
wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS), numCoupons);
wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_SV), numSv);
wseg.set(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.KXP), kxp);
wseg.set(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.HIP_ACCUM), hipAccum);
wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS), svLengthInts);
wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS), wLengthInts);
MemorySegment.copy(svStream, 0, wseg, JAVA_INT_UNALIGNED, getSvStreamOffset(wseg), svLengthInts);
MemorySegment.copy(wStream, 0, wseg, JAVA_INT_UNALIGNED, getWStreamOffset(wseg), wLengthInts);
}
private static void putFirst8(final MemorySegment wseg, final byte preInts, final byte lgK,
final byte fiCol, final byte flags, final short seedHash) {
clear(wseg, 0L, 4L * preInts);
wseg.set(JAVA_BYTE, getLoFieldOffset(LoField.PRE_INTS), preInts);
wseg.set(JAVA_BYTE, getLoFieldOffset(LoField.SER_VERSION), SER_VER);
wseg.set(JAVA_BYTE, getLoFieldOffset(LoField.FAMILY), (byte) Family.CPC.getID());
wseg.set(JAVA_BYTE, getLoFieldOffset(LoField.LG_K), lgK);
wseg.set(JAVA_BYTE, getLoFieldOffset(LoField.FI_COL), fiCol);
wseg.set(JAVA_BYTE, getLoFieldOffset(LoField.FLAGS), flags);
wseg.set(JAVA_SHORT_UNALIGNED, getLoFieldOffset(LoField.SEED_HASH), seedHash);
}
//TO STRING
static String toString(final byte[] byteArr, final boolean detail) {
final MemorySegment seg = MemorySegment.ofArray(byteArr);
return toString(seg, detail);
}
static String toString(final MemorySegment seg, final boolean detail) {
final long capBytes = seg.byteSize();
//Lo Fields Preamble, first 7 fields, first 8 bytes
final int preInts = seg.get(JAVA_BYTE, getLoFieldOffset(LoField.PRE_INTS)) & 0xFF;
final int serVer = seg.get(JAVA_BYTE, getLoFieldOffset(LoField.SER_VERSION)) & 0xFF;
final Family family = Family.idToFamily(seg.get(JAVA_BYTE, getLoFieldOffset(LoField.FAMILY)) & 0xFF);
final int lgK = seg.get(JAVA_BYTE, getLoFieldOffset(LoField.LG_K)) & 0xFF;
final int fiCol = seg.get(JAVA_BYTE, getLoFieldOffset(LoField.FI_COL)) & 0xFF;
final int flags = seg.get(JAVA_BYTE, getLoFieldOffset(LoField.FLAGS)) & 0XFF;
final int seedHash = seg.get(JAVA_SHORT_UNALIGNED, getLoFieldOffset(LoField.SEED_HASH)) & 0XFFFF;
final String seedHashStr = Integer.toHexString(seedHash);
//Flags of the Flags byte
final String flagsStr = zeroPad(Integer.toBinaryString(flags), 8) + ", " + (flags);
final boolean compressed = (flags & COMPRESSED_FLAG_MASK) > 0;
final boolean hasHip = (flags & HIP_FLAG_MASK) > 0;
final boolean hasSV = (flags & SUP_VAL_FLAG_MASK) > 0;
final boolean hasWindow = (flags & WINDOW_FLAG_MASK) > 0;
final int formatOrdinal = (flags >>> 2) & 0x7;
final Format format = Format.ordinalToFormat(formatOrdinal);
long numCoupons = 0;
long numSv = 0;
long winOffset = 0;
long svLengthInts = 0;
long wLengthInts = 0;
double kxp = 0;
double hipAccum = 0;
long svStreamStart = 0;
long wStreamStart = 0;
long reqBytes = 0;
final StringBuilder sb = new StringBuilder();
sb.append(LS);
sb.append("### CPC SKETCH IMAGE - PREAMBLE:").append(LS);
sb.append("Format : ").append(format.name()).append(LS);
sb.append("Byte 0: Preamble Ints : ").append(preInts).append(LS);
sb.append("Byte 1: SerVer : ").append(serVer).append(LS);
sb.append("Byte 2: Family : ").append(family).append(LS);
sb.append("Byte 3: lgK : ").append(lgK).append(LS);
sb.append("Byte 4: First Interesting Col : ").append(fiCol).append(LS);
sb.append("Byte 5: Flags : ").append(flagsStr).append(LS);
sb.append(" Compressed : ").append(compressed).append(LS);
sb.append(" Has HIP : ").append(hasHip).append(LS);
sb.append(" Has Surprising Values : ").append(hasSV).append(LS);
sb.append(" Has Window Values : ").append(hasWindow).append(LS);
sb.append("Byte 6, 7: Seed Hash : ").append(seedHashStr).append(LS);
final Flavor flavor;
switch (format) {
case EMPTY_MERGED :
case EMPTY_HIP : {
flavor = CpcUtil.determineFlavor(lgK, numCoupons);
sb.append("Flavor : ").append(flavor).append(LS);
break;
}
case SPARSE_HYBRID_MERGED : {
numCoupons = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS)) & 0xFFFF_FFFFL;
numSv = numCoupons;
svLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS)) & 0xFFFF_FFFFL;
svStreamStart = getSvStreamOffset(seg);
reqBytes = svStreamStart + (svLengthInts << 2);
flavor = CpcUtil.determineFlavor(lgK, numCoupons);
sb.append("Flavor : ").append(flavor).append(LS);
sb.append("Num Coupons : ").append(numCoupons).append(LS);
sb.append("Num SV : ").append(numSv).append(LS);
sb.append("SV Length Ints : ").append(svLengthInts).append(LS);
sb.append("SV Stream Start : ").append(svStreamStart).append(LS);
break;
}
case SPARSE_HYBRID_HIP : {
numCoupons = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS)) & 0xFFFF_FFFFL;
numSv = numCoupons;
svLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS)) & 0xFFFF_FFFFL;
svStreamStart = getSvStreamOffset(seg);
kxp = seg.get(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.KXP));
hipAccum = seg.get(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.HIP_ACCUM));
reqBytes = svStreamStart + (svLengthInts << 2);
flavor = CpcUtil.determineFlavor(lgK, numCoupons);
sb.append("Flavor : ").append(flavor).append(LS);
sb.append("Num Coupons : ").append(numCoupons).append(LS);
sb.append("Num SV : ").append(numSv).append(LS);
sb.append("SV Length Ints : ").append(svLengthInts).append(LS);
sb.append("SV Stream Start : ").append(svStreamStart).append(LS);
sb.append("KxP : ").append(kxp).append(LS);
sb.append("HipAccum : ").append(hipAccum).append(LS);
break;
}
case PINNED_SLIDING_MERGED_NOSV : {
numCoupons = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS)) & 0xFFFF_FFFFL;
winOffset = CpcUtil.determineCorrectOffset(lgK, numCoupons);
wLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS)) & 0xFFFF_FFFFL;
wStreamStart = getWStreamOffset(seg);
reqBytes = wStreamStart + (wLengthInts << 2);
flavor = CpcUtil.determineFlavor(lgK, numCoupons);
sb.append("Flavor : ").append(flavor).append(LS);
sb.append("Num Coupons : ").append(numCoupons).append(LS);
sb.append("Window Offset : ").append(winOffset).append(LS);
sb.append("Window Length Ints : ").append(wLengthInts).append(LS);
sb.append("Window Stream Start : ").append(wStreamStart).append(LS);
break;
}
case PINNED_SLIDING_HIP_NOSV : {
numCoupons = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS)) & 0xFFFF_FFFFL;
winOffset = CpcUtil.determineCorrectOffset(lgK, numCoupons);
wLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS)) & 0xFFFF_FFFFL;
wStreamStart = getWStreamOffset(seg);
kxp = seg.get(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.KXP));
hipAccum = seg.get(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.HIP_ACCUM));
reqBytes = wStreamStart + (wLengthInts << 2);
flavor = CpcUtil.determineFlavor(lgK, numCoupons);
sb.append("Flavor : ").append(flavor).append(LS);
sb.append("Num Coupons : ").append(numCoupons).append(LS);
sb.append("Window Offset : ").append(winOffset).append(LS);
sb.append("Window Length Ints : ").append(wLengthInts).append(LS);
sb.append("Window Stream Start : ").append(wStreamStart).append(LS);
sb.append("KxP : ").append(kxp).append(LS);
sb.append("HipAccum : ").append(hipAccum).append(LS);
break;
}
case PINNED_SLIDING_MERGED : {
numCoupons = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS) & 0xFFFF_FFFFL);
winOffset = CpcUtil.determineCorrectOffset(lgK, numCoupons);
wLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS)) & 0xFFFF_FFFFL;
numSv = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_SV)) & 0xFFFF_FFFFL;
svLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS)) & 0xFFFF_FFFFL;
wStreamStart = getWStreamOffset(seg);
svStreamStart = getSvStreamOffset(seg);
reqBytes = svStreamStart + (svLengthInts << 2);
flavor = CpcUtil.determineFlavor(lgK, numCoupons);
sb.append("Flavor : ").append(flavor).append(LS);
sb.append("Num Coupons : ").append(numCoupons).append(LS);
sb.append("Num SV : ").append(numSv).append(LS);
sb.append("SV Length Ints : ").append(svLengthInts).append(LS);
sb.append("SV Stream Start : ").append(svStreamStart).append(LS);
sb.append("Window Offset : ").append(winOffset).append(LS);
sb.append("Window Length Ints : ").append(wLengthInts).append(LS);
sb.append("Window Stream Start : ").append(wStreamStart).append(LS);
break;
}
case PINNED_SLIDING_HIP : {
numCoupons = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS) & 0xFFFF_FFFFL);
winOffset = CpcUtil.determineCorrectOffset(lgK, numCoupons);
wLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS)) & 0xFFFF_FFFFL;
numSv = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_SV)) & 0xFFFF_FFFFL;
svLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS)) & 0xFFFF_FFFFL;
wStreamStart = getWStreamOffset(seg);
svStreamStart = getSvStreamOffset(seg);
kxp = seg.get(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.KXP));
hipAccum = seg.get(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.HIP_ACCUM));
reqBytes = svStreamStart + (svLengthInts << 2);
flavor = CpcUtil.determineFlavor(lgK, numCoupons);
sb.append("Flavor : ").append(flavor).append(LS);
sb.append("Num Coupons : ").append(numCoupons).append(LS);
sb.append("Num SV : ").append(numSv).append(LS);
sb.append("SV Length Ints : ").append(svLengthInts).append(LS);
sb.append("SV Stream Start : ").append(svStreamStart).append(LS);
sb.append("Window Offset : ").append(winOffset).append(LS);
sb.append("Window Length Ints : ").append(wLengthInts).append(LS);
sb.append("Window Stream Start : ").append(wStreamStart).append(LS);
sb.append("KxP : ").append(kxp).append(LS);
sb.append("HipAccum : ").append(hipAccum).append(LS);
break;
}
}
sb.append("Actual Bytes : ").append(capBytes).append(LS);
sb.append("Required Bytes : ").append(reqBytes).append(LS);
if (detail) {
sb.append(LS).append("### CPC SKETCH IMAGE - DATA").append(LS);
if (wLengthInts > 0) {
sb.append(LS).append("Window Stream:").append(LS);
listData(seg, wStreamStart, wLengthInts, sb);
}
if (svLengthInts > 0) {
sb.append(LS).append("SV Stream:").append(LS);
listData(seg, svStreamStart, svLengthInts, sb);
}
}
sb.append("### END CPC SKETCH IMAGE").append(LS);
return sb.toString();
} //end toString(seg)
private static void listData(final MemorySegment seg, final long offsetBytes, final long lengthInts,
final StringBuilder sb) {
final long segCap = seg.byteSize();
final long expectedCap = offsetBytes + (4L * lengthInts);
checkCapacity(segCap, expectedCap);
for (long i = 0; i < lengthInts; i++) {
sb.append(String.format(fmt, i, seg.get(JAVA_INT_UNALIGNED, offsetBytes + (4L * i)))).append(LS);
}
}
static void fieldError(final Format format, final HiField hiField) {
throw new SketchesArgumentException(
"Operation is illegal: Format = " + format.name() + ", HiField = " + hiField);
}
static void checkCapacity(final long segCap, final long expectedCap) {
if (segCap < expectedCap) {
throw new SketchesArgumentException(
"Insufficient Image Bytes = " + segCap + ", Expected = " + expectedCap);
}
}
//basic checks of SerVer, Format, preInts, Family, fiCol, lgK.
static void checkLoPreamble(final MemorySegment seg) {
Objects.requireNonNull(seg, "Source MemorySegment must not be null");
checkBounds(0, 8, seg.byteSize()); //need min 8 bytes
rtAssertEquals(getSerVer(seg), SER_VER & 0XFF);
final Format fmat = getFormat(seg);
final int preIntsDef = getDefinedPreInts(fmat) & 0XFF;
rtAssertEquals(getPreInts(seg), preIntsDef);
final Family fam = getFamily(seg);
rtAssert(fam == Family.CPC);
final int lgK = getLgK(seg);
rtAssert((lgK >= 4) && (lgK <= 26));
final int fiCol = getFiCol(seg);
rtAssert((fiCol <= 63) && (fiCol >= 0));
}
}
//@formatter:on
|
apache/harmony | 36,614 | classlib/modules/swing/src/main/java/common/javax/swing/plaf/basic/BasicTextUI.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Evgeniya G. Maenkova
*/
package javax.swing.plaf.basic;
import java.awt.AWTKeyStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.KeyboardFocusManager;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.KeyStroke;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.MouseInputAdapter;
import javax.swing.plaf.ActionMapUIResource;
import javax.swing.plaf.ComponentInputMapUIResource;
import javax.swing.plaf.InputMapUIResource;
import javax.swing.plaf.TextUI;
import javax.swing.plaf.UIResource;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.Caret;
import javax.swing.text.DefaultCaret;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Document;
import javax.swing.text.EditorKit;
import javax.swing.text.Element;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;
import javax.swing.text.Keymap;
import javax.swing.text.Position;
import javax.swing.text.TextAction;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;
import org.apache.harmony.awt.text.RootViewContext;
import org.apache.harmony.awt.text.TextFactory;
import org.apache.harmony.awt.text.TextUtils;
import org.apache.harmony.x.swing.StringConstants;
import org.apache.harmony.x.swing.Utilities;
import org.apache.harmony.x.swing.internal.nls.Messages;
public abstract class BasicTextUI extends TextUI implements ViewFactory {
public static class BasicCaret extends DefaultCaret implements UIResource {
public BasicCaret() {
super();
}
}
public static class BasicHighlighter extends DefaultHighlighter implements
UIResource {
public BasicHighlighter() {
super();
}
}
// Text Component, concerned with this BasicTextUI
private JTextComponent component;
// Editor Kit for all components excluding JTextPane and JEditorPane
private static final EditorKit EDITOR_KIT = new DefaultEditorKit();
// The Parent of all view Hierarchy. In never changes. When document
// changes,
// a child of rootView will be replaced only.
private RootViewContext rootViewContext;
// PropertyChangeListener, DocumentListener
private Listener listener = new Listener();
// Document, concerned with this BasicTextUI (component.getDocument)
private Document document;
// Simple TransferHandler to support cut, copy, paste operations
private static TransferHandler transferHandler;
// This flag is used in paintSafely, modelToView, viewToModel methods.
private boolean isActive = false;
// This flag is used in Listener.InsertUpdate method. It need not to lock
// document in DocumentListener. Then modelChanged method defines, it need
// to lock document or not
private boolean needLock = true;
// if document i18n property changes, then ViewHierarchy must be rebuild.
private boolean i18nProperty = false;
// Action to request focus on Text Component (support FocusAcceleratorKey
//on JTextComponent).
private final Action focusAction = new RequestFocusAction();
// Key for FOCUS_ACTION in ActionMap
private static final String FOCUS_ACTION_NAME = "request-focus";
// Flag is used in UpdateFocus AcceleratorKey method
private char lastFocusAccelerator = '\0';
//Listener for drop target
private DropListener dropListener;
//Initiator for DnD
private GestureRecognizer gestureRecognizer;
private final RootViewContext.ViewFactoryGetter viewFactoryGetter =
new RootViewContext.ViewFactoryGetter() {
public ViewFactory getViewFactory() {
ViewFactory viewFactory = getEditorKit(component).getViewFactory();
return (viewFactory == null) ? BasicTextUI.this : viewFactory;
}
};
/**
* Action to request focus on Text Component, concerned with this
* BasicTextUI
*/
private class RequestFocusAction extends TextAction {
public RequestFocusAction() {
super(FOCUS_ACTION_NAME);
}
public void actionPerformed(final ActionEvent e) {
JTextComponent jtc = null;
if (e != null && e.getSource() != null) {
jtc = (JTextComponent)e.getSource();
}
if (jtc != null) {
jtc.requestFocusInWindow();
}
}
}
/**
* Transfer Handler to support basic transfer operation. It need to redefine
* javax.swing.TransferHandler because it doesn't support required
* operations. See java.beans (Introspector, BeanInfo,...)
*/
private static class TextTransferHandler extends TransferHandler
implements UIResource {
boolean isDrag = false;
public boolean canImport(final JComponent comp,
final DataFlavor[] dataFlavor) {
//Note: temporary solution
return true; //super.canImport(arg0, arg1);
}
public void exportToClipboard(final JComponent c, final Clipboard clip,
final int action) {
TextUtils.exportToClipboard(TextUtils.getTextKit(c), clip, action);
}
public boolean importData(final JComponent c, final Transferable t) {
if (isDrag || !(c instanceof JTextComponent)) {
return false;
}
return TextUtils.importData(TextUtils.getTextKit(c), t);
}
protected void exportDone(final JComponent c, final Transferable data,
final int action) {
isDrag = false;
TextUtils.exportDone(TextUtils.getTextKit(c), data, action);
}
protected Transferable createTransferable(final JComponent c) {
return TextUtils.createTransferable(TextUtils.getTextKit(c));
}
public int getSourceActions(final JComponent c) {
return TextUtils.getSourceActions(TextUtils.getTextKit(c));
}
public void exportAsDrag(final JComponent comp, final InputEvent ie,
final int action) {
isDrag = true;
super.exportAsDrag(comp, ie, action);
}
}
private class Listener implements DocumentListener, PropertyChangeListener {
/**
* Call rootView.changeUpdate
*/
public void changedUpdate(final DocumentEvent e) {
getRootView().changedUpdate(e, getVisibleEditorRect(),
getRootView().getViewFactory());
}
/**
* If "i18n" property of document is changed call modelChanged.
* Otherwise, call rooView.insertUpdate
*/
public void insertUpdate(final DocumentEvent e) {
boolean currentI18nProperty = ((Boolean)document
.getProperty(StringConstants.BIDI_PROPERTY)).booleanValue();
if (currentI18nProperty && !i18nProperty) {
needLock = false;
modelChanged();
needLock = true;
i18nProperty = true;
} else {
getRootView().insertUpdate(e, getVisibleEditorRect(),
getRootView().getViewFactory());
}
}
/**
* Call rootView.removeUpdate
*/
public void removeUpdate(final DocumentEvent e) {
getRootView().removeUpdate(e, getVisibleEditorRect(), getRootView()
.getViewFactory());
}
/**
* If document is changed on Text Component, handle this event. In
* particular remove DocumentListener from old document, add Document
* Listener to new document, Rebuild view hierarchy. If
* "componentOrientaion" property is changes, call modelChanged. If
* JTextComponent.FOCUS_ACCELERATOR_KEY property is changes, call
* private method UpdateFocusAcceleratorBinding (to reflect changes on
* InputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)). Call propertyChange
* method.
*/
public void propertyChange(final PropertyChangeEvent e) {
String name = e.getPropertyName();
if (StringConstants.TEXT_COMPONENT_DOCUMENT_PROPERTY.equals(name)) {
if (document != null) {
document.removeDocumentListener(listener);
}
Object doc = e.getNewValue();
if (doc != null) {
setDocument((Document)doc);
document.addDocumentListener(listener);
modelChanged();
}
} else if (StringConstants.COMPONENT_ORIENTATION.equals(name)) {
modelChanged();
} else if (JTextComponent.FOCUS_ACCELERATOR_KEY.equals(name)) {
lastFocusAccelerator = ((Character)e.getOldValue()).charValue();
updateFocusAcceleratorBinding(true);
}
propertyChangeImpl(e);
BasicTextUI.this.propertyChange(e);
}
}
/*
* Performs drop, instances of this class are added to
* component.getDropTarget()
*/
final class DropListener implements DropTargetListener {
String str = null;
int start = 0;
int end = 0;
JTextComponent textComponent;
public void dragEnter(final DropTargetDragEvent e) {
}
public void dragExit(final DropTargetEvent e) {
}
public void dragOver(final DropTargetDragEvent e) {
/*
* Component comp = e.getDropTargetContext().getComponent(); if
* (comp == null || ! (comp instanceof JTextComponent)) return;
* textComponent = (JTextComponent)comp; Transferable t =
* e.getTransferable(); start = textComponent.getSelectionStart();
* end = textComponent.getSelectionEnd(); try { str = (String) t
* .getTransferData(DataFlavor.stringFlavor); } catch (final
* UnsupportedFlavorException ufe) { } catch (final IOException
* ioe) {}
*/
}
public void dropActionChanged(final DropTargetDragEvent arg0) {
}
public void drop(final DropTargetDropEvent e) {
int length = end - start;
int insertPosition = textComponent.viewToModel(e.getLocation());
try {
textComponent.getDocument().remove(start, length);
if (insertPosition > end) {
insertPosition -= length;
} else {
if (insertPosition >= start) {
insertPosition = start;
}
}
textComponent.getDocument().insertString(insertPosition, str,
null);
textComponent.replaceSelection("");
textComponent.setCaretPosition(insertPosition + length);
} catch (final BadLocationException ex) {
}
e.dropComplete(true);
}
}
/*
* Initiates DnD, instances of this class are added to current component
*/
final class GestureRecognizer extends MouseInputAdapter {
boolean wasMousePressed = false;
public void mousePressed(final MouseEvent arg0) {
String selectedText = component.getSelectedText();
if (selectedText != null && selectedText != ""
&& component.getDragEnabled()) {
wasMousePressed = true;
}
}
public void mouseDragged(final MouseEvent me) {
if (wasMousePressed) {
wasMousePressed = false;
component.getTransferHandler()
.exportAsDrag(component, me, TransferHandler.MOVE);
}
}
}
/**
* Creates parent of all view hierarchy.
*/
public BasicTextUI() {
initRootViewContext(null);
dropListener = new DropListener();
gestureRecognizer = new GestureRecognizer();
}
public View create(final Element elem) {
return null;
}
public View create(final Element elem, final int p0, final int p1) {
return null;
}
protected Caret createCaret() {
return new BasicCaret();
}
protected Highlighter createHighlighter() {
return new BasicHighlighter();
}
protected Keymap createKeymap() {
String name = getKeymapName();
Keymap keymap = JTextComponent.getKeymap(name);
if (keymap == null) {
keymap = JTextComponent.addKeymap(name, JTextComponent
.getKeymap(JTextComponent.DEFAULT_KEYMAP));
}
Object bindings = UIManager.get(addPrefix(".keyBindings"));
if (bindings != null) {
JTextComponent.loadKeymap(keymap,
(JTextComponent.KeyBinding[])bindings,
component.getActions());
}
return keymap;
}
public void damageRange(final JTextComponent c, final int p0,
final int p1) {
damageRange(c, p0, p1, Position.Bias.Forward, Position.Bias.Forward);
}
/**
* Calculates rectangle(r, for example), corresponding these position and
* biases. Then call component.repaint(r.x, r.y, r.width, r.height)
*/
public void damageRange(final JTextComponent c, final int p0, final int p1,
final Position.Bias b1, final Position.Bias b2) {
Shape shape = null;
try {
shape = getRootView()
.modelToView(p0, b1, p1, b2, getVisibleEditorRect());
} catch (final BadLocationException e) {
}
Rectangle rect;
if (shape != null) {
rect = shape.getBounds();
component.repaint(rect.x, rect.y, rect.width, rect.height);
}
}
protected final JTextComponent getComponent() {
return component;
}
/**
* Always returns DefaultEditorKit
*/
public EditorKit getEditorKit(final JTextComponent comp) {
return EDITOR_KIT;
}
protected String getKeymapName() {
String className = getClass().getName();
final int lastDot = className.lastIndexOf('.');
return className.substring(lastDot + 1);
}
public Dimension getMaximumSize(final JComponent c) {
//See description for getRootView().getMaximumSpan
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
/**
* Uses getMinimumSpan of View Hierarchy and getInsets of TextComponent
*/
public Dimension getMinimumSize(final JComponent c) {
Insets insets = c.getInsets();
int minX = TextUtils.getHrzInsets(insets)
+ (int)getRootView().getMinimumSpan(View.X_AXIS);
int minY = TextUtils.getVrtInsets(insets)
+ (int)getRootView().getMinimumSpan(View.Y_AXIS);
return new Dimension(minX, minY);
}
/**
* Calls getNextVisualPosition on root view. If root view returns -1, then
* this method will return p0 and biasRet[0] will be the same as bias
*/
public int getNextVisualPositionFrom(final JTextComponent c, final int p0,
final Position.Bias bias,
final int p1,
final Position.Bias[] biasRet)
throws BadLocationException {
int pos = getRootView().getNextVisualPositionFrom(p0, bias,
getVisibleEditorRect(),
p1, biasRet);
if (pos == -1) {
pos = p0;
biasRet[0] = bias;
}
return pos;
}
/**
* Uses getPrefferedSpan of View Hierarchy and getInsets of TextComponent
*/
public Dimension getPreferredSize(final JComponent c) {
Insets insets = c.getInsets();
int prefX = TextUtils.getHrzInsets(insets)
+ (int)getRootView().getPreferredSpan(View.X_AXIS);
int prefY = TextUtils.getVrtInsets(insets)
+ (int)getRootView().getPreferredSpan(View.Y_AXIS);
return new Dimension(prefX, prefY);
}
protected abstract String getPropertyPrefix();
public View getRootView(final JTextComponent c) {
return getRootView();
}
public String getToolTipText(final JTextComponent c, final Point p) {
Rectangle r = getVisibleEditorRect();
return (r != null) ? getRootView().getToolTipText(p.x, p.y, r) : null;
}
private TransferHandler getTransferHandler() {
if (transferHandler == null) {
transferHandler = new TextTransferHandler();
}
return transferHandler;
}
/**
* Returns, component getSize, excluding insets.
*/
protected Rectangle getVisibleEditorRect() {
return TextUtils.getEditorRect(component);
}
final String addPrefix(final String property) {
return getPropertyPrefix() + property;
}
protected void installDefaults() {
LookAndFeel.installColorsAndFont(component, addPrefix(".background"),
addPrefix(".foreground"),
addPrefix(".font"));
if (Utilities.isUIResource(component.getBorder())) {
component.setBorder(UIManager.getBorder(addPrefix(".border")));
}
if (Utilities.isUIResource(component.getMargin())) {
component.setMargin(UIManager.getInsets(addPrefix(".margin")));
}
//RI 6251901. Documentation error
if (Utilities.isUIResource(component.getCaretColor())) {
component.setCaretColor(UIManager.getColor(addPrefix(
".caretForeground")));
}
if (Utilities.isUIResource(component.getSelectionColor())) {
component.setSelectionColor(UIManager.getColor(addPrefix(
".selectionBackground")));
}
if (Utilities.isUIResource(component.getSelectedTextColor())) {
component.setSelectedTextColor(UIManager
.getColor(addPrefix(".selectionForeground")));
}
if (Utilities.isUIResource(component.getDisabledTextColor())) {
component.setDisabledTextColor(UIManager.getColor(addPrefix(
".inactiveForeground")));
}
}
final Set<AWTKeyStroke> getDefaultFocusTraversalKeys(final int mode) {
Set<AWTKeyStroke> result = component.getFocusTraversalKeys(mode);
if (result == null) {
result = new LinkedHashSet<AWTKeyStroke>();
if (mode == KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS) {
result.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,
InputEvent.CTRL_DOWN_MASK));
} else {
result.add(KeyStroke
.getKeyStroke(KeyEvent.VK_TAB,
InputEvent.CTRL_DOWN_MASK
| InputEvent.SHIFT_DOWN_MASK));
}
} else {
result = new LinkedHashSet<AWTKeyStroke>(result);
}
return result;
}
void updateFocusTraversalKeys() {
if (component == null) {
return;
}
Set<AWTKeyStroke> forwardFocusTraversalKeys =
getDefaultFocusTraversalKeys(KeyboardFocusManager
.FORWARD_TRAVERSAL_KEYS);
Set<AWTKeyStroke> backwardFocusTraversalKeys =
getDefaultFocusTraversalKeys(KeyboardFocusManager
.BACKWARD_TRAVERSAL_KEYS);
KeyStroke tabPressed = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
KeyStroke shiftTabPressed = KeyStroke
.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_DOWN_MASK);
if (component.isEditable()) {
forwardFocusTraversalKeys.remove(tabPressed);
backwardFocusTraversalKeys.remove(shiftTabPressed);
} else {
if (!forwardFocusTraversalKeys.contains(tabPressed)) {
forwardFocusTraversalKeys.add(tabPressed);
}
if (!forwardFocusTraversalKeys.contains(shiftTabPressed)) {
backwardFocusTraversalKeys.add(shiftTabPressed);
}
}
component.setFocusTraversalKeys(KeyboardFocusManager
.FORWARD_TRAVERSAL_KEYS,
forwardFocusTraversalKeys);
component.setFocusTraversalKeys(KeyboardFocusManager
.BACKWARD_TRAVERSAL_KEYS,
backwardFocusTraversalKeys);
}
final void installUIInputMap() {
String propertyName = addPrefix(".focusInputMap");
InputMapUIResource inputMap1 = new InputMapUIResource();
InputMapUIResource inputMap2 = (InputMapUIResource)UIManager
.get(propertyName);
inputMap1.setParent(inputMap2);
SwingUtilities.replaceUIInputMap(component, JComponent.WHEN_FOCUSED,
inputMap1);
}
final void putActionToActionMap(final Action a, final ActionMap map) {
Object name = a.getValue(Action.NAME);
map.put(name, a);
}
final void installUIActionMap() {
UIDefaults uiDefaults = UIManager.getLookAndFeelDefaults();
String propertyName = getPropertyPrefix() + ".actionMap";
ActionMap actionMap1 = new ActionMapUIResource();
putActionToActionMap(focusAction, actionMap1);
Object actionMap2 = uiDefaults.get(propertyName);
if (actionMap2 == null) {
ActionMapUIResource map = new ActionMapUIResource();
Action[] actions = component.getActions();
for (int i = 0; i < actions.length; i++) {
putActionToActionMap(actions[i], map);
}
putActionToActionMap(TransferHandler.getPasteAction(), map);
putActionToActionMap(TransferHandler.getCutAction(), map);
putActionToActionMap(TransferHandler.getCopyAction(), map);
actionMap2 = map;
if (!(component instanceof JEditorPane)) {
uiDefaults.put(propertyName, map);
}
}
actionMap1.setParent((ActionMap)actionMap2);
SwingUtilities.replaceUIActionMap(component, actionMap1);
}
/**
* Sets InputMap(JComponent.WHEN_FOCUSED), ActionMap, Keymap on
* TextComponent.
*
*/
protected void installKeyboardActions() {
installUIActionMap();
installUIInputMap();
Keymap keymap = createKeymap();
component.setKeymap(keymap);
}
protected void installListeners() {
}
public void installUI(final JComponent c) {
if (!(c instanceof JTextComponent)) {
throw new Error(Messages.getString("swing.B1")); //$NON-NLS-1$
}
super.installUI(c);
setComponent((JTextComponent)c);
installDefaults();
LookAndFeel.installProperty(component, StringConstants.OPAQUE_PROPERTY,
Boolean.TRUE);
if (Utilities.isUIResource(component.getCaret())) {
Caret caret = createCaret();
component.setCaret(caret);
caret.setBlinkRate(UIManager.getInt(getPropertyPrefix()
+ ".caretBlinkRate"));
}
if (Utilities.isUIResource(component.getHighlighter())) {
component.setHighlighter(createHighlighter());
}
if (Utilities.isUIResource(component.getTransferHandler())) {
component.setTransferHandler(getTransferHandler());
}
if (component.getDocument() == null) {
setDocument(getEditorKit(component).createDefaultDocument());
component.setDocument(document);
} else {
setDocument(component.getDocument());
}
modelChanged();
((AbstractDocument)component.getDocument())
.addDocumentListener(listener);
component.addPropertyChangeListener(listener);
JTextComponent.addKeymap(getKeymapName(), JTextComponent
.getKeymap(JTextComponent.DEFAULT_KEYMAP));
installListeners();
installKeyboardActions();
isActive = true;
component.setAutoscrolls(true);
updateFocusAcceleratorBinding(true);
//DnD support
// java.awt.Component doesn't support DnD
/*
* try { component.getDropTarget().addDropTargetListener(dropListener);
* } catch (final TooManyListenersException e){}
*/
component.addMouseListener(gestureRecognizer);
component.addMouseMotionListener(gestureRecognizer);
updateFocusTraversalKeys();
}
/**
* Rebuilts view hierarchy.
*
*/
protected void modelChanged() {
final Document doc = document;
if (needLock) {
readLock(doc);
}
try {
setDocument(document);
View view = getRootView().getViewFactory()
.create(document.getDefaultRootElement());
setView(view);
setViewSize();
} finally {
if (needLock) {
readUnlock(doc);
}
}
if (component != null) {
component.repaint();
}
}
public Rectangle modelToView(final JTextComponent c, final int p)
throws BadLocationException {
return modelToView(c, p, Position.Bias.Forward);
}
public Rectangle modelToView(final JTextComponent comp, final int p,
final Position.Bias b)
throws BadLocationException {
final Document doc = document;
readLock(doc);
try {
Rectangle r = null;
if (isActive) {
Rectangle rect = getVisibleEditorRect();
if (rect != null) {
getRootView().setSize(rect.width, rect.height);
Shape shape = getRootView().modelToView(p, rect, b);
if (shape != null) {
r = shape.getBounds();
}
}
}
return r;
} finally {
readUnlock(doc);
}
}
public final void paint(final Graphics g, final JComponent c) {
//super.paint(g, c);//???
paintSafely(g);
}
protected void paintBackground(final Graphics g) {
Color color = component.getBackground();
if (color != null) {
g.setColor(color);
}
Rectangle rect = getVisibleEditorRect();
if (rect != null) {
g.fillRect(rect.x, rect.y, rect.width, rect.height);
}
}
protected void paintSafely(final Graphics g) {
if (!isActive) {
return;
}
final Document doc = document;
readLock(doc);
try {
Highlighter highlighter = component.getHighlighter();
Caret caret = component.getCaret();
if (component.isOpaque()) {
paintBackground(g);
}
if (highlighter != null) {
highlighter.paint(g);
}
Rectangle visibleRect = getVisibleEditorRect();
if (visibleRect != null) {
getRootView().setSize(visibleRect.width, visibleRect.height);
getRootView().paint(g, visibleRect);
}
caret.paint(g);
} finally {
readUnlock(doc);
}
}
void propertyChangeImpl(final PropertyChangeEvent e) {
if (org.apache.harmony.x.swing.StringConstants.EDITABLE_PROPERTY_CHANGED
.equals(e.getPropertyName())
&& !e.getOldValue().equals(e.getNewValue())) {
updateFocusTraversalKeys();
}
}
protected void propertyChange(final PropertyChangeEvent e) {
}
/**
* Replaces child of the root view
*/
protected final void setView(final View v) {
component.removeAll();
if (v != null) {
getRootView().append(v);
}
if (component != null) {
component.invalidate();
}
}
protected void uninstallDefaults() {
if (Utilities.isUIResource(component.getForeground())) {
component.setForeground(null);
}
if (Utilities.isUIResource(component.getBackground())) {
component.setBackground(null);
}
if (Utilities.isUIResource(component.getFont())) {
component.setFont(null);
}
if (Utilities.isUIResource(component.getBorder())) {
component.setBorder(null);
}
if (Utilities.isUIResource(component.getMargin())) {
component.setMargin(null);
}
if (Utilities.isUIResource(component.getCaretColor())) {
component.setCaretColor(null);
}
if (Utilities.isUIResource(component.getSelectionColor())) {
component.setSelectionColor(null);
}
if (Utilities.isUIResource(component.getSelectedTextColor())) {
component.setSelectedTextColor(null);
}
if (Utilities.isUIResource(component.getDisabledTextColor())) {
component.setDisabledTextColor(null);
}
}
/**
* Sets ActionMap and Keymap of TextComponent to null.
*
*/
protected void uninstallKeyboardActions() {
component.setKeymap(null);
SwingUtilities.replaceUIActionMap(component, null);
}
protected void uninstallListeners() {
}
public void uninstallUI(final JComponent c) {
if (component != c) {
return;
}
isActive = false;
super.uninstallUI(c);
if (Utilities.isUIResource(component.getCaret())) {
component.setCaret(null);
}
if (Utilities.isUIResource(component.getHighlighter())) {
component.setHighlighter(null);
}
uninstallDefaults();
uninstallKeyboardActions();
uninstallListeners();
((AbstractDocument) component.getDocument())
.removeDocumentListener(listener);
component.removePropertyChangeListener(listener);
//DnD support
//java.awt.Component doesn't support DnD
/*
* component.getDropTarget().removeDropTargetListener(dropListener);
*/
component.removeMouseListener(gestureRecognizer);
component.removeMouseMotionListener(gestureRecognizer);
setComponent(null);
}
public void update(final Graphics g, final JComponent c) {
super.update(g, c);
}
final void updateFocusAcceleratorBinding(final boolean changed) {
if (!changed) {
return;
}
char accelerator = component.getFocusAccelerator();
InputMap im = SwingUtilities.getUIInputMap(component,
JComponent.WHEN_IN_FOCUSED_WINDOW);
boolean wasInputMap = (im != null);
boolean needToRemove = (lastFocusAccelerator != '\0');
boolean needToAdd = (accelerator != '\0');
if (needToAdd) {
if (needToRemove && wasInputMap) {
im.remove(KeyStroke.getKeyStroke(lastFocusAccelerator,
InputEvent.ALT_DOWN_MASK));
} else if (!wasInputMap) {
im = new ComponentInputMapUIResource(component);
im.put(KeyStroke.getKeyStroke(accelerator,
InputEvent.ALT_DOWN_MASK),
FOCUS_ACTION_NAME);
if (!wasInputMap) {
SwingUtilities.replaceUIInputMap(component,
JComponent.WHEN_IN_FOCUSED_WINDOW, im);
}
} else if (wasInputMap) {
im.remove(KeyStroke.getKeyStroke(lastFocusAccelerator,
InputEvent.ALT_DOWN_MASK));
}
}
}
public int viewToModel(final JTextComponent c, final Point p) {
return viewToModel(c, p, new Position.Bias[1]);
}
public int viewToModel(final JTextComponent c, final Point p,
final Position.Bias[] b) {
return getRootView().viewToModel(p.x, p.y, getVisibleEditorRect(), b);
}
private void setViewSize() {
Rectangle rect = getVisibleEditorRect();
if (rect != null) {
getRootView().setSize(rect.width, rect.height);
}
}
private void readLock(final Document doc) {
if (doc instanceof AbstractDocument) {
((AbstractDocument)doc).readLock();
}
}
private void readUnlock(final Document doc) {
if (doc instanceof AbstractDocument) {
((AbstractDocument)doc).readUnlock();
}
}
final boolean getI18nProperty() {
return document == null
? false
: ((Boolean)document.getProperty(StringConstants.BIDI_PROPERTY))
.booleanValue();
}
private View getRootView() {
return rootViewContext.getView();
}
private void setDocument(final Document document) {
this.document = document;
rootViewContext.setDocument(document);
}
private void setComponent(final JTextComponent component) {
this.component = component;
rootViewContext.setComponent(component);
}
private void initRootViewContext(final Element elem) {
rootViewContext = TextFactory.getTextFactory().createRootView(elem);
rootViewContext.setViewFactoryGetter(viewFactoryGetter);
setComponent(component);
setDocument(document);
}
}
|
apache/wicket | 34,037 | wicket-core-tests/src/test/java/org/apache/wicket/MarkupContainerTest.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.wicket;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.stream.Collectors;
import org.apache.commons.collections4.map.LinkedMap;
import org.apache.wicket.core.util.lang.WicketObjects;
import org.apache.wicket.markup.IMarkupResourceStreamProvider;
import org.apache.wicket.markup.html.WebComponent;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.util.resource.IResourceStream;
import org.apache.wicket.util.resource.StringResourceStream;
import org.apache.wicket.util.tester.WicketTestCase;
import org.junit.jupiter.api.Test;
class MarkupContainerTest extends WicketTestCase
{
private static final int NUMBER_OF_CHILDREN_FOR_A_MAP = MarkupContainer.MAPIFY_THRESHOLD + 1;
/**
* Make sure components are iterated in the order they were added. Required e.g. for Repeaters
*/
@Test
void iteratorOrder()
{
MarkupContainer container = new WebMarkupContainer("component");
for (int i = 0; i < 10; i++)
{
container.add(new WebComponent(Integer.toString(i)));
}
int i = 0;
for (Component component : container)
{
assertEquals(Integer.toString(i++), component.getId());
}
}
@Test
void markupId() throws Exception
{
executeTest(MarkupIdTestPage.class, "MarkupIdTestPageExpectedResult.html");
}
@Test
void get()
{
WebMarkupContainer a = new WebMarkupContainer("a");
WebMarkupContainer b = new WebMarkupContainer("b");
WebMarkupContainer c = new WebMarkupContainer("c");
WebMarkupContainer d = new WebMarkupContainer("d");
WebMarkupContainer e = new WebMarkupContainer("e");
WebMarkupContainer f = new WebMarkupContainer("f");
// ....A
// ...B....C
// .......D..E
// ...........F
a.add(b);
a.add(c);
c.add(d);
c.add(e);
e.add(f);
// basic gets
assertSame(a.get(null), a);
assertSame(a.get(""), a);
assertSame(a.get("b"), b);
assertSame(a.get("c"), c);
assertSame(a.get("c:d"), d);
assertSame(a.get("c:e:f"), f);
// parent path gets
assertSame(b.get(".."), a);
assertSame(e.get("..:.."), a);
assertSame(d.get("..:..:c:e:f"), f);
assertSame(e.get("..:d:..:e:f"), f);
assertSame(e.get("..:d:..:.."), a);
// invalid gets
assertNull(a.get(".."));
assertNull(a.get("..:a"));
assertNull(b.get("..|.."));
assertNull(a.get("q"));
}
/**
* https://issues.apache.org/jira/browse/WICKET-4006
*/
@Test
void addMyself()
{
WebMarkupContainer me = new WebMarkupContainer("a");
assertThrows(IllegalArgumentException.class, () -> me.add(me));
}
/**
* https://issues.apache.org/jira/browse/WICKET-5911
*/
@Test
void rerenderAfterRenderFailure()
{
FirstRenderFailsPage page = new FirstRenderFailsPage();
try
{
tester.startPage(page);
}
catch (WicketRuntimeException expected)
{
}
tester.startPage(page);
// rendering flags where properly reset, so second rendering works properly
assertEquals(2, page.beforeRenderCalls);
}
@Test
void hierarchyChangeDuringRender()
{
HierarchyChangePage page = new HierarchyChangePage();
try
{
tester.startPage(page);
fail();
}
catch (WicketRuntimeException expected)
{
assertEquals(
"Cannot modify component hierarchy after render phase has started (page version cant change then anymore)",
expected.getMessage());
}
}
/**
* https://issues.apache.org/jira/browse/WICKET-4012
*/
@Test
void afterRenderJustOnce()
{
AfterRenderJustOncePage page = new AfterRenderJustOncePage();
tester.startPage(page);
assertEquals(1, page.afterRenderCalls);
}
/**
* https://issues.apache.org/jira/browse/WICKET-4016
*/
@Test
void callToStringFromConstructor()
{
new ToStringComponent();
}
@Test
void noChildShouldNotIterate()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Iterator<Component> iterator = wmc.iterator();
assertFalse(iterator.hasNext());
}
@Test
void noChildAddingChildAfterIteratorAcquiredShouldIterateAndReturnNewChild()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Iterator<Component> iterator = wmc.iterator();
Label label1 = new Label("label1", "Label1");
wmc.add(label1);
assertEquals(1, wmc.size());
assertTrue(iterator.hasNext());
assertEquals(label1, iterator.next());
assertFalse(iterator.hasNext());
}
@Test
void noChildAddingNChildrenAfterIteratorAcquiredShouldIterateAndReturnNewChildren()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Iterator<Component> iterator = wmc.iterator();
addNChildren(wmc, NUMBER_OF_CHILDREN_FOR_A_MAP);
assertEquals(NUMBER_OF_CHILDREN_FOR_A_MAP, wmc.size());
Label label1 = new Label("label1", "Label1");
wmc.add(label1);
assertTrue(iterator.hasNext());
takeNChildren(iterator, NUMBER_OF_CHILDREN_FOR_A_MAP);
assertEquals(label1, iterator.next());
assertFalse(iterator.hasNext());
}
@Test
void noChildAddingNChildrenAfterIteratorAcquiredShouldIterateAndReturnNewChildren2()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, NUMBER_OF_CHILDREN_FOR_A_MAP);
assertEquals(NUMBER_OF_CHILDREN_FOR_A_MAP, wmc.size());
Iterator<Component> iterator = wmc.iterator();
takeNChildren(iterator, NUMBER_OF_CHILDREN_FOR_A_MAP);
Label label1 = new Label("label1", "Label1");
wmc.add(label1);
assertTrue(iterator.hasNext());
assertEquals(label1, iterator.next());
assertFalse(iterator.hasNext());
}
/*
* Iterator tests
*
* The tests below are specific for testing addition and removal of children while maintaining
* the correct order of iterators without throwing ConcurrentModificationException.
*/
@Test
void noChildAddingAndRemoveChildAfterIteratorAcquiredShouldNotIterate()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label1 = new Label("label1", "Label1");
Iterator<Component> iterator = wmc.iterator();
wmc.add(label1);
wmc.remove(label1);
assertEquals(0, wmc.size());
assertFalse(iterator.hasNext());
}
@Test
void addingNewChildAfterIterationHasStartedShouldIterateNewChild()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
// add one child
addNChildren(wmc, 1);
Iterator<Component> iterator = wmc.iterator();
// iterate
takeNChildren(iterator, 1);
// there are no more children to iterate
assertFalse(iterator.hasNext());
// add the new child
Label newChild = new Label("label1", "Label1");
wmc.add(newChild);
assertEquals(2, wmc.size());
// ensure that the newChild is up next (as it was added)
assertEquals(newChild, iterator.next());
assertFalse(iterator.hasNext());
}
@Test
void replacingTheFirstChildAfterIteratingDoesntIterateTheNewChild()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label1 = new Label("label1", "Label1");
Component label2 = new Label("label2", "Label2");
addNChildren(wmc, NUMBER_OF_CHILDREN_FOR_A_MAP);
wmc.add(label1);
wmc.add(label2);
Iterator<Component> iterator = wmc.iterator();
takeNChildren(iterator, NUMBER_OF_CHILDREN_FOR_A_MAP);
iterator.next();
// replace the first child **after** we already passed the child with the iterator
Label newChild = new Label("label1", "newChild");
wmc.replace(newChild);
// the next child is still label 2
assertSame(label2, iterator.next());
// and the new child is not iterated (was replaced before the current position of the
// iterator).
assertFalse(iterator.hasNext());
}
@Test
void removingComponentsDuringIterationDoesntFail()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Component label1 = new Label("label1", "Label1");
Component label2 = new Label("label2", "Label2");
Component label3 = new Label("label3", "Label3");
Component label4 = new Label("label4", "Label4");
Component label5 = new Label("label5", "Label5");
wmc.add(label1);
wmc.add(label2);
wmc.add(label3);
wmc.add(label4);
wmc.add(label5);
// start iterating the 5 children
Iterator<Component> iterator = wmc.iterator();
assertSame(label1, iterator.next());
assertSame(label2, iterator.next());
assertSame(label3, iterator.next());
// remove the current, previous and next children
wmc.remove(label3);
wmc.remove(label2);
wmc.remove(label4);
// ensure that the next iterated child is the 5th label
assertSame(label5, iterator.next());
// and that there are no more children to iterate
assertFalse(iterator.hasNext());
}
@Test
void childrenBecomesListWhenMoreThanOneChild() throws Exception
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, 5);
Field childrenField = MarkupContainer.class.getDeclaredField("children");
childrenField.setAccessible(true);
Object field = childrenField.get(wmc);
assertThat(field).isInstanceOf(List.class);
}
@Test
void childrenListBecomesMapWhenThresholdPassed()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, NUMBER_OF_CHILDREN_FOR_A_MAP - 1);
assertChildrenType(wmc, List.class);
addNChildren(wmc, 1);
assertChildrenType(wmc, LinkedMap.class);
}
@Test
void childrenBecomesLinkedMapWhenThresholdPassed()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, NUMBER_OF_CHILDREN_FOR_A_MAP + 1);
assertChildrenType(wmc, LinkedMap.class);
}
@Test
void linkedMapChildrenBecomesChild()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, NUMBER_OF_CHILDREN_FOR_A_MAP);
wmc.add(new EmptyPanel("panel"));
assertChildrenType(wmc, LinkedMap.class);
Iterator<Component> iterator = wmc.iterator();
removeNChildren(iterator, NUMBER_OF_CHILDREN_FOR_A_MAP);
assertChildrenType(wmc, EmptyPanel.class);
}
@Test
void listChildrenBecomesChild()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, NUMBER_OF_CHILDREN_FOR_A_MAP - 2);
wmc.add(new EmptyPanel("panel"));
assertChildrenType(wmc, List.class);
Iterator<Component> iterator = wmc.iterator();
removeNChildren(iterator, NUMBER_OF_CHILDREN_FOR_A_MAP - 2);
assertChildrenType(wmc, EmptyPanel.class);
}
@Test
void geenIdee3()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, NUMBER_OF_CHILDREN_FOR_A_MAP + 1);
Iterator<Component> iterator = wmc.iterator();
removeNChildren(iterator, NUMBER_OF_CHILDREN_FOR_A_MAP);
assertTrue(iterator.hasNext());
assertEquals(1, wmc.size());
iterator.next();
assertFalse(iterator.hasNext());
}
@Test
void noChildAddIterateAndRemoveChildShouldIterateChild()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label1 = new Label("label1", "Label1");
Iterator<Component> iterator = wmc.iterator();
wmc.add(label1);
assertEquals(label1, iterator.next());
wmc.remove(label1);
assertFalse(iterator.hasNext());
}
@Test
void noChildAddIterateAndRemoveAndAddSameChildShouldIterateChildTwice()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label1 = new Label("label1", "Label1");
Iterator<Component> iterator = wmc.iterator();
wmc.add(label1);
assertEquals(label1, iterator.next());
assertFalse(iterator.hasNext());
wmc.remove(label1);
assertFalse(iterator.hasNext());
wmc.add(label1);
assertEquals(label1, iterator.next());
}
@Test
void noChildAddIterateAndRemoveAndAddDifferentChildShouldIterateNewChild()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label1 = new Label("label1", "Label1");
Label label2 = new Label("label1", "Label2");
Iterator<Component> iterator = wmc.iterator();
wmc.add(label1);
assertEquals(label1, iterator.next());
assertFalse(iterator.hasNext());
wmc.remove(label1);
assertFalse(iterator.hasNext());
wmc.add(label2);
assertEquals(label2, iterator.next());
}
@Test
void noChildAddingAndReplaceChildAfterIteratorAcquiredShouldIterateAndReturnNewReplacementChild()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label1 = new Label("label1", "Label1");
Label label2 = new Label("label1", "Label2");
Iterator<Component> iterator = wmc.iterator();
wmc.add(label1);
wmc.replace(label2);
assertTrue(iterator.hasNext());
assertEquals(label2, iterator.next());
assertFalse(iterator.hasNext());
}
@Test
void singleChildIterateOneChild()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label1;
wmc.add(label1 = new Label("label1", "Label1"));
Iterator<Component> iterator = wmc.iterator();
assertTrue(iterator.hasNext());
assertEquals(label1, iterator.next());
assertFalse(iterator.hasNext());
}
@Test
void singleChildShouldAllowReplacingChildAfterIterationHasStarted()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Component label1 = new Label("label1", "Label1");
Component label2 = new Label("label1", "Label2");
wmc.add(label1);
Iterator<Component> iterator = wmc.iterator();
wmc.replace(label2);
assertTrue(iterator.hasNext());
assertSame(label2, iterator.next());
assertFalse(iterator.hasNext());
}
@Test
void singleChildShouldAllowReplacingVisitedChildButNotRevisitReplacementChild()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label1 = new Label("label1", "Label1");
Label label2 = new Label("label1", "Label2");
wmc.add(label1);
Iterator<Component> iterator = wmc.iterator();
assertTrue(iterator.hasNext());
assertEquals(label1, iterator.next());
wmc.replace(label2);
assertFalse(iterator.hasNext());
}
@Test
void multipleChildIteratorRetainsOrderOfAddition()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label1;
Label label2;
Label label3;
wmc.add(label1 = new Label("label1", "Label1"));
wmc.add(label2 = new Label("label2", "Label2"));
wmc.add(label3 = new Label("label3", "Label3"));
Iterator<Component> iterator = wmc.iterator();
assertEquals(label1, iterator.next());
assertEquals(label2, iterator.next());
assertEquals(label3, iterator.next());
assertFalse(iterator.hasNext());
}
@Test
void iteratorShouldAllowAddingComponentAfterIterationStarted()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label1;
Label label2;
Label label3;
wmc.add(label1 = new Label("label1", "Label1"));
wmc.add(label2 = new Label("label2", "Label2"));
Iterator<Component> iterator = wmc.iterator();
assertEquals(label1, iterator.next());
assertEquals(label2, iterator.next());
wmc.add(label3 = new Label("label3", "Label3"));
assertEquals(label3, iterator.next());
assertFalse(iterator.hasNext());
}
@Test
void iteratorShouldAllowRemovingComponentAfterIterationStarted0()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label1;
Label label2;
Label label3;
wmc.add(label1 = new Label("label1", "Label1"));
wmc.add(label2 = new Label("label2", "Label2"));
wmc.add(label3 = new Label("label3", "Label3"));
Iterator<Component> iterator = wmc.iterator();
wmc.remove(label1);
assertEquals(label2, iterator.next());
assertEquals(label3, iterator.next());
assertFalse(iterator.hasNext());
}
@Test
void iteratorShouldAllowRemovingComponentAfterIterationStarted1()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label1 = new Label("label1", "Label1");
Label label2 = new Label("label2", "Label2");
Label label3 = new Label("label3", "Label3");
wmc.add(label1);
wmc.add(label2);
wmc.add(label3);
Iterator<Component> iterator = wmc.iterator();
assertEquals(label1, iterator.next());
wmc.remove(label1);
assertEquals(label2, iterator.next());
assertEquals(label3, iterator.next());
assertFalse(iterator.hasNext());
}
@Test
void iteratorShouldAllowRemovingComponentAfterIterationStarted2()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label1;
Label label2;
Label label3;
wmc.add(label1 = new Label("label1", "Label1"));
wmc.add(label2 = new Label("label2", "Label2"));
wmc.add(label3 = new Label("label3", "Label3"));
Iterator<Component> iterator = wmc.iterator();
assertEquals(label1, iterator.next());
assertEquals(label2, iterator.next());
wmc.remove(label1);
assertEquals(label3, iterator.next());
assertFalse(iterator.hasNext());
}
@Test
void iteratorShouldAllowRemovingComponentAfterIterationStarted3()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label1;
Label label2;
Label label3;
wmc.add(label1 = new Label("label1", "Label1"));
wmc.add(label2 = new Label("label2", "Label2"));
wmc.add(label3 = new Label("label3", "Label3"));
Iterator<Component> iterator = wmc.iterator();
assertEquals(label1, iterator.next());
assertEquals(label2, iterator.next());
assertEquals(label3, iterator.next());
wmc.remove(label1);
assertFalse(iterator.hasNext());
}
@Test
void iteratorShouldAllowReplacingComponentAfterIterationStarted0()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label2;
Label label3;
wmc.add(new Label("label1", "Label1"));
wmc.add(label2 = new Label("label2", "Label2"));
Iterator<Component> iterator = wmc.iterator();
wmc.replace(label3 = new Label("label1", "Label3"));
assertEquals(label3, iterator.next());
assertEquals(label2, iterator.next());
assertFalse(iterator.hasNext());
}
@Test
void iteratorShouldAllowReplacingComponentAfterIterationStarted1()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label2;
Label label3;
wmc.add(new Label("label1", "Label1"));
wmc.add(label2 = new Label("label2", "Label2"));
Iterator<Component> iterator = wmc.iterator();
wmc.replace(label3 = new Label("label1", "Label3"));
assertEquals(label3, iterator.next());
assertEquals(label2, iterator.next());
assertFalse(iterator.hasNext());
}
@Test
void iteratorShouldAllowReplacingComponentAfterIterationStarted()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label1;
Label label2;
wmc.add(label1 = new Label("label1", "Label1"));
wmc.add(label2 = new Label("label2", "Label2"));
Iterator<Component> iterator = wmc.iterator();
assertEquals(label1, iterator.next());
assertEquals(label2, iterator.next());
wmc.replace(new Label("label1", "Label3"));
assertFalse(iterator.hasNext());
}
@Test
void iteratorShouldAllowReplacingComponentAfterIterationStarted24()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Label label1;
Label label3;
wmc.add(label1 = new Label("label1", "Label1"));
wmc.add(new Label("label2", "Label2"));
addNChildren(wmc, NUMBER_OF_CHILDREN_FOR_A_MAP);
Iterator<Component> iterator = wmc.iterator();
assertEquals(label1, iterator.next());
wmc.replace(label3 = new Label("label2", "Label3"));
assertEquals(label3, iterator.next());
takeNChildren(iterator, NUMBER_OF_CHILDREN_FOR_A_MAP);
assertFalse(iterator.hasNext());
}
@Test
void noChildLeftBehindRemoveEach()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, NUMBER_OF_CHILDREN_FOR_A_MAP);
Iterator<Component> iterator = wmc.iterator();
while (iterator.hasNext())
{
iterator.next();
iterator.remove();
}
assertEquals(0, wmc.size());
}
@Test
void noChildLeftBehindRemoveAll()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, NUMBER_OF_CHILDREN_FOR_A_MAP);
Iterator<Component> iterator = wmc.iterator();
wmc.removeAll();
assertEquals(0, wmc.size());
assertFalse(iterator.hasNext());
}
@Test
void noChildLeftBehindRemoveAll2()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, NUMBER_OF_CHILDREN_FOR_A_MAP);
Iterator<Component> iterator = wmc.iterator();
iterator.next();
wmc.removeAll();
assertEquals(0, wmc.size());
assertFalse(iterator.hasNext());
}
@Test
void ensureSerializationDeserializationWorks()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Iterator<Component> iterator = wmc.iterator();
addNChildren(wmc, NUMBER_OF_CHILDREN_FOR_A_MAP);
assertEquals(NUMBER_OF_CHILDREN_FOR_A_MAP, wmc.size());
assertNotNull(WicketObjects.cloneObject(wmc));
removeNChildren(iterator, 1);
assertEquals(NUMBER_OF_CHILDREN_FOR_A_MAP - 1, wmc.size());
assertNotNull(WicketObjects.cloneObject(wmc));
removeNChildren(iterator, NUMBER_OF_CHILDREN_FOR_A_MAP - 2);
assertNotNull(WicketObjects.cloneObject(wmc));
assertEquals(1, wmc.size());
removeNChildren(iterator, 1);
assertEquals(0, wmc.size());
assertNotNull(WicketObjects.cloneObject(wmc));
}
@Test
void detachDuringIterationWorks()
{
int halfOfChildren = NUMBER_OF_CHILDREN_FOR_A_MAP / 2;
int numberOfRemainingChildren = halfOfChildren + NUMBER_OF_CHILDREN_FOR_A_MAP % 2;
WebMarkupContainer wmc = new WebMarkupContainer("id");
Iterator<Component> iterator = wmc.iterator();
addNChildren(wmc, NUMBER_OF_CHILDREN_FOR_A_MAP);
takeNChildren(iterator, halfOfChildren);
wmc.detach();
takeNChildren(iterator, numberOfRemainingChildren);
assertFalse(iterator.hasNext());
}
@Test
void detachDuringIterationWithRemovalsSucceeds()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
Iterator<Component> iterator = wmc.iterator();
addNChildren(wmc, 2);
removeNChildren(iterator, 1);
wmc.detach();
takeNChildren(iterator, 1);
assertFalse(iterator.hasNext());
assertEquals(1, wmc.size());
}
/**
* Tests whether two iterators being used simultaneously keep correct score of where they are.
*/
@Test
void twoIteratorsWorkInTandem()
{
int n = NUMBER_OF_CHILDREN_FOR_A_MAP * 2;
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, n);
Iterator<Component> iterator1 = wmc.iterator();
Iterator<Component> iterator2 = wmc.iterator();
Random r = new Random();
for (int i = 0; i < n; i++)
{
if (r.nextBoolean())
{
iterator1.next();
iterator1.remove();
}
else
{
iterator2.next();
iterator2.remove();
}
}
// after 2*N removals there should not be any child left
assertFalse(iterator1.hasNext());
assertFalse(iterator2.hasNext());
}
/**
* Tests removing a child when an iterator is active, followed by a detach still has the correct
* state for the iterator.
*/
@Test
void detachWithOneIteratorOneChild()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, 1);
Iterator<Component> iterator1 = wmc.iterator();
iterator1.next();
iterator1.remove();
wmc.detach();
assertFalse(iterator1.hasNext());
}
/**
* Tests removing and adding a component when an iterator is active, followed by a detach still
* has the correct state for the iterator.
*/
@Test
void detachWithOneIteratorOneChildRemovedAndAdded()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, 1);
Iterator<Component> iterator1 = wmc.iterator();
iterator1.next();
iterator1.remove();
addNChildren(wmc, 1);
assertTrue(iterator1.hasNext());
wmc.detach();
assertTrue(iterator1.hasNext());
assertNotNull(iterator1.next());
}
/**
* Tests the case when one child is removed from a list the iterator still works after a detach.
*/
@Test
void detachWithOneIteratorTwoChildren()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, 2);
Iterator<Component> iterator1 = wmc.iterator();
iterator1.next();
iterator1.remove();
assertTrue(iterator1.hasNext());
wmc.detach();
assertTrue(iterator1.hasNext());
assertNotNull(iterator1.next());
}
/**
* Tests whether when the children is a list, removal and iteration still work after a detach.
*/
@Test
void detachWithOneIteratorWithListForChildren()
{
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, NUMBER_OF_CHILDREN_FOR_A_MAP - 2);
assertChildrenType(wmc, List.class);
Iterator<Component> iterator = wmc.iterator();
takeNChildren(iterator, 1);
removeNChildren(iterator, 1);
wmc.detach();
takeNChildren(iterator, NUMBER_OF_CHILDREN_FOR_A_MAP - 4);
assertFalse(iterator.hasNext());
}
/**
* Tests whether when the children is a map, removal and iteration still work after a detach.
*/
@Test
void detachWithOneIteratorsWithMapForChildren()
{
int n = NUMBER_OF_CHILDREN_FOR_A_MAP * 2;
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, n);
Iterator<Component> iterator1 = wmc.iterator();
for (int i = 0; i < NUMBER_OF_CHILDREN_FOR_A_MAP; i++)
{
iterator1.next();
iterator1.remove();
}
wmc.detach();
for (int i = 0; i < NUMBER_OF_CHILDREN_FOR_A_MAP; i++)
{
iterator1.next();
iterator1.remove();
}
assertFalse(iterator1.hasNext());
}
@Test
void detachWithTwoIteratorsAndRemovals()
{
int n = NUMBER_OF_CHILDREN_FOR_A_MAP * 2;
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, n);
Iterator<Component> iterator1 = wmc.iterator();
Iterator<Component> iterator2 = wmc.iterator();
Random r = new Random();
for (int i = 0; i < NUMBER_OF_CHILDREN_FOR_A_MAP; i++)
{
if (r.nextBoolean())
{
iterator1.next();
iterator1.remove();
}
else
{
iterator2.next();
iterator2.remove();
}
}
wmc.detach();
iterator1.next();
iterator1.remove();
iterator2.next();
}
@Test
void detachWithTwoIteratorsAndRemovals2()
{
int n = NUMBER_OF_CHILDREN_FOR_A_MAP * 2;
WebMarkupContainer wmc = new WebMarkupContainer("id");
addNChildren(wmc, n);
Iterator<Component> iterator1 = wmc.iterator();
Iterator<Component> iterator2 = wmc.iterator();
Random r = new Random();
for (int i = 0; i < NUMBER_OF_CHILDREN_FOR_A_MAP; i++)
{
Iterator<Component> iterator = r.nextBoolean() ? iterator1 : iterator2;
if (iterator.hasNext())
{
iterator.next();
iterator.remove();
}
}
wmc.detach();
iterator1.next();
iterator2.next();
iterator1.remove();
while (iterator1.hasNext() || iterator2.hasNext())
{
Iterator<Component> iterator = r.nextBoolean() ? iterator1 : iterator2;
if (iterator.hasNext())
{
iterator.next();
iterator.remove();
}
}
assertFalse(iterator1.hasNext());
assertFalse(iterator2.hasNext());
}
/**
* Asserts that the children property of the {@code wmc} is of a particular {@code type}.
*
* @param wmc
* the web markup container whose children property is to be checked
* @param type
* the expected type
*/
private void assertChildrenType(WebMarkupContainer wmc, Class<?> type)
{
try
{
Field childrenField = MarkupContainer.class.getDeclaredField("children");
childrenField.setAccessible(true);
Object field = childrenField.get(wmc);
assertThat(field).isInstanceOf(type);
}
catch (Exception e)
{
throw new AssertionError("Unable to read children", e);
}
}
/**
* Adds {@code numberOfChildrenToAdd} anonymous children to the {@code parent}.
*
* @param parent
* the parent to add the children to
* @param numberOfChildrenToAdd
* the number of children
*/
private void addNChildren(WebMarkupContainer parent, int numberOfChildrenToAdd)
{
assertThat(numberOfChildrenToAdd).isGreaterThanOrEqualTo(0);
int start = parent.size();
for (int i = 0; i < numberOfChildrenToAdd; i++)
{
int index = start + i;
parent.add(new Label("padding" + index, "padding" + index));
}
}
/**
* Removes {@code numberOfChildrenToRemove} anonymous children from the parent using the
* {@code iterator}.
*
* @param iterator
* the iterator to remove the children with
* @param numberOfChildrenToRemove
* the number of children
*/
private void removeNChildren(Iterator<Component> iterator, int numberOfChildrenToRemove)
{
for (int i = 0; i < numberOfChildrenToRemove; i++)
{
iterator.next();
iterator.remove();
}
}
/**
* Progresses the {@code iterator} with {@code numberOfChildrenToTake} anonymous children.
*
* @param iterator
* the iterator to progress
* @param numberOfChildrenToTake
* the number of children
*/
private void takeNChildren(Iterator<Component> iterator, int numberOfChildrenToTake)
{
for (int i = 0; i < numberOfChildrenToTake; i++)
iterator.next();
}
@Test
void stream()
{
LoginPage loginPage = new LoginPage();
Optional<Component> first = loginPage.stream()
.filter(c -> c.getId().equals("form"))
.findFirst();
assertFalse(first.isPresent());
loginPage.add(new Form<>("form"));
Optional<Component> second = loginPage.stream()
.filter(c -> c.getId().equals("form"))
.findFirst();
assertTrue(second.isPresent());
loginPage.add(new WebMarkupContainer("wmc"));
Optional<Form> form = loginPage.stream()
.filter(Form.class::isInstance)
.map(Form.class::cast)
.findFirst();
assertTrue(form.isPresent());
Optional<WebMarkupContainer> wmc = loginPage.stream()
.filter(WebMarkupContainer.class::isInstance)
.map(WebMarkupContainer.class::cast)
.findFirst();
assertTrue(wmc.isPresent());
}
@Test
void streamChildren()
{
LoginPage loginPage = new LoginPage();
Optional<Component> first = loginPage.stream()
.filter(c -> c.getId().equals("form"))
.findFirst();
assertFalse(first.isPresent());
Form<Object> form = new Form<>("form");
loginPage.add(form);
form.add(new TextField<>("field"));
assertTrue(loginPage.streamChildren()
.anyMatch(c -> c.getId().equals("form")));
assertTrue(loginPage.streamChildren()
.anyMatch(c -> c.getId().equals("field")));
assertTrue(loginPage.streamChildren()
.filter(TextField.class::isInstance)
.anyMatch(c -> c.getId().equals("field")));
}
// https://issues.apache.org/jira/browse/WICKET-6754
@Test
void streamChildrenNestedContainer() {
WebMarkupContainer wmc = new WebMarkupContainer("parent");
WebMarkupContainer wmc1 = new WebMarkupContainer("wmc1");
wmc.add(wmc1);
WebMarkupContainer wmc1_2= new WebMarkupContainer("wmc1_2");
wmc1.add(wmc1_2);
Label lbl2 = new Label("lbl2");
wmc.add(lbl2);
List l = wmc.streamChildren().map(Component::getId).collect(Collectors.toList());
assertEquals("[wmc1, wmc1_2, lbl2]", l.toString());
}
private static class HierarchyChangePage extends WebPage
implements
IMarkupResourceStreamProvider
{
@Override
protected void onRender()
{
// change hierarchy during render
add(new Label("child"));
}
@Override
public IResourceStream getMarkupResourceStream(MarkupContainer container,
Class<?> containerClass)
{
return new StringResourceStream("<html><body></body></html>");
}
}
private static class ToStringComponent extends WebMarkupContainer
{
private ToStringComponent()
{
super("id");
toString(true);
}
}
private static class AfterRenderJustOncePage extends WebPage
implements
IMarkupResourceStreamProvider
{
private int afterRenderCalls = 0;
private AfterRenderJustOncePage()
{
WebMarkupContainer a1 = new WebMarkupContainer("a1");
add(a1);
WebMarkupContainer a2 = new WebMarkupContainer("a2");
a1.add(a2);
WebMarkupContainer a3 = new WebMarkupContainer("a3")
{
@Override
protected void onAfterRender()
{
super.onAfterRender();
afterRenderCalls++;
}
};
a2.add(a3);
}
@Override
public IResourceStream getMarkupResourceStream(MarkupContainer container,
Class<?> containerClass)
{
return new StringResourceStream(
"<html><body><div wicket:id='a1'><div wicket:id='a2'><div wicket:id='a3'></div></div></div></body></html>");
}
}
private static class FirstRenderFailsPage extends WebPage
implements
IMarkupResourceStreamProvider
{
private boolean firstRender = true;
private int beforeRenderCalls = 0;
private FirstRenderFailsPage()
{
WebMarkupContainer a1 = new WebMarkupContainer("a1")
{
@Override
protected void onBeforeRender()
{
super.onBeforeRender();
beforeRenderCalls++;
if (firstRender)
{
firstRender = false;
throw new WicketRuntimeException();
}
}
};
add(a1);
}
@Override
public IResourceStream getMarkupResourceStream(MarkupContainer container,
Class<?> containerClass)
{
return new StringResourceStream("<html><body><div wicket:id='a1'></div></body></html>");
}
}
}
|
googleapis/google-cloud-java | 36,459 | java-automl/proto-google-cloud-automl-v1beta1/src/main/java/com/google/cloud/automl/v1beta1/RegressionProto.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/automl/v1beta1/regression.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.automl.v1beta1;
public final class RegressionProto {
private RegressionProto() {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
}
public interface RegressionEvaluationMetricsOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.automl.v1beta1.RegressionEvaluationMetrics)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Output only. Root Mean Squared Error (RMSE).
* </pre>
*
* <code>float root_mean_squared_error = 1;</code>
*
* @return The rootMeanSquaredError.
*/
float getRootMeanSquaredError();
/**
*
*
* <pre>
* Output only. Mean Absolute Error (MAE).
* </pre>
*
* <code>float mean_absolute_error = 2;</code>
*
* @return The meanAbsoluteError.
*/
float getMeanAbsoluteError();
/**
*
*
* <pre>
* Output only. Mean absolute percentage error. Only set if all ground truth
* values are are positive.
* </pre>
*
* <code>float mean_absolute_percentage_error = 3;</code>
*
* @return The meanAbsolutePercentageError.
*/
float getMeanAbsolutePercentageError();
/**
*
*
* <pre>
* Output only. R squared.
* </pre>
*
* <code>float r_squared = 4;</code>
*
* @return The rSquared.
*/
float getRSquared();
/**
*
*
* <pre>
* Output only. Root mean squared log error.
* </pre>
*
* <code>float root_mean_squared_log_error = 5;</code>
*
* @return The rootMeanSquaredLogError.
*/
float getRootMeanSquaredLogError();
}
/**
*
*
* <pre>
* Metrics for regression problems.
* </pre>
*
* Protobuf type {@code google.cloud.automl.v1beta1.RegressionEvaluationMetrics}
*/
public static final class RegressionEvaluationMetrics
extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.automl.v1beta1.RegressionEvaluationMetrics)
RegressionEvaluationMetricsOrBuilder {
private static final long serialVersionUID = 0L;
// Use RegressionEvaluationMetrics.newBuilder() to construct.
private RegressionEvaluationMetrics(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private RegressionEvaluationMetrics() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new RegressionEvaluationMetrics();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.automl.v1beta1.RegressionProto
.internal_static_google_cloud_automl_v1beta1_RegressionEvaluationMetrics_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.automl.v1beta1.RegressionProto
.internal_static_google_cloud_automl_v1beta1_RegressionEvaluationMetrics_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics.class,
com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics.Builder
.class);
}
public static final int ROOT_MEAN_SQUARED_ERROR_FIELD_NUMBER = 1;
private float rootMeanSquaredError_ = 0F;
/**
*
*
* <pre>
* Output only. Root Mean Squared Error (RMSE).
* </pre>
*
* <code>float root_mean_squared_error = 1;</code>
*
* @return The rootMeanSquaredError.
*/
@java.lang.Override
public float getRootMeanSquaredError() {
return rootMeanSquaredError_;
}
public static final int MEAN_ABSOLUTE_ERROR_FIELD_NUMBER = 2;
private float meanAbsoluteError_ = 0F;
/**
*
*
* <pre>
* Output only. Mean Absolute Error (MAE).
* </pre>
*
* <code>float mean_absolute_error = 2;</code>
*
* @return The meanAbsoluteError.
*/
@java.lang.Override
public float getMeanAbsoluteError() {
return meanAbsoluteError_;
}
public static final int MEAN_ABSOLUTE_PERCENTAGE_ERROR_FIELD_NUMBER = 3;
private float meanAbsolutePercentageError_ = 0F;
/**
*
*
* <pre>
* Output only. Mean absolute percentage error. Only set if all ground truth
* values are are positive.
* </pre>
*
* <code>float mean_absolute_percentage_error = 3;</code>
*
* @return The meanAbsolutePercentageError.
*/
@java.lang.Override
public float getMeanAbsolutePercentageError() {
return meanAbsolutePercentageError_;
}
public static final int R_SQUARED_FIELD_NUMBER = 4;
private float rSquared_ = 0F;
/**
*
*
* <pre>
* Output only. R squared.
* </pre>
*
* <code>float r_squared = 4;</code>
*
* @return The rSquared.
*/
@java.lang.Override
public float getRSquared() {
return rSquared_;
}
public static final int ROOT_MEAN_SQUARED_LOG_ERROR_FIELD_NUMBER = 5;
private float rootMeanSquaredLogError_ = 0F;
/**
*
*
* <pre>
* Output only. Root mean squared log error.
* </pre>
*
* <code>float root_mean_squared_log_error = 5;</code>
*
* @return The rootMeanSquaredLogError.
*/
@java.lang.Override
public float getRootMeanSquaredLogError() {
return rootMeanSquaredLogError_;
}
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 (java.lang.Float.floatToRawIntBits(rootMeanSquaredError_) != 0) {
output.writeFloat(1, rootMeanSquaredError_);
}
if (java.lang.Float.floatToRawIntBits(meanAbsoluteError_) != 0) {
output.writeFloat(2, meanAbsoluteError_);
}
if (java.lang.Float.floatToRawIntBits(meanAbsolutePercentageError_) != 0) {
output.writeFloat(3, meanAbsolutePercentageError_);
}
if (java.lang.Float.floatToRawIntBits(rSquared_) != 0) {
output.writeFloat(4, rSquared_);
}
if (java.lang.Float.floatToRawIntBits(rootMeanSquaredLogError_) != 0) {
output.writeFloat(5, rootMeanSquaredLogError_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (java.lang.Float.floatToRawIntBits(rootMeanSquaredError_) != 0) {
size += com.google.protobuf.CodedOutputStream.computeFloatSize(1, rootMeanSquaredError_);
}
if (java.lang.Float.floatToRawIntBits(meanAbsoluteError_) != 0) {
size += com.google.protobuf.CodedOutputStream.computeFloatSize(2, meanAbsoluteError_);
}
if (java.lang.Float.floatToRawIntBits(meanAbsolutePercentageError_) != 0) {
size +=
com.google.protobuf.CodedOutputStream.computeFloatSize(3, meanAbsolutePercentageError_);
}
if (java.lang.Float.floatToRawIntBits(rSquared_) != 0) {
size += com.google.protobuf.CodedOutputStream.computeFloatSize(4, rSquared_);
}
if (java.lang.Float.floatToRawIntBits(rootMeanSquaredLogError_) != 0) {
size += com.google.protobuf.CodedOutputStream.computeFloatSize(5, rootMeanSquaredLogError_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj
instanceof com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics)) {
return super.equals(obj);
}
com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics other =
(com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics) obj;
if (java.lang.Float.floatToIntBits(getRootMeanSquaredError())
!= java.lang.Float.floatToIntBits(other.getRootMeanSquaredError())) return false;
if (java.lang.Float.floatToIntBits(getMeanAbsoluteError())
!= java.lang.Float.floatToIntBits(other.getMeanAbsoluteError())) return false;
if (java.lang.Float.floatToIntBits(getMeanAbsolutePercentageError())
!= java.lang.Float.floatToIntBits(other.getMeanAbsolutePercentageError())) return false;
if (java.lang.Float.floatToIntBits(getRSquared())
!= java.lang.Float.floatToIntBits(other.getRSquared())) return false;
if (java.lang.Float.floatToIntBits(getRootMeanSquaredLogError())
!= java.lang.Float.floatToIntBits(other.getRootMeanSquaredLogError())) 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) + ROOT_MEAN_SQUARED_ERROR_FIELD_NUMBER;
hash = (53 * hash) + java.lang.Float.floatToIntBits(getRootMeanSquaredError());
hash = (37 * hash) + MEAN_ABSOLUTE_ERROR_FIELD_NUMBER;
hash = (53 * hash) + java.lang.Float.floatToIntBits(getMeanAbsoluteError());
hash = (37 * hash) + MEAN_ABSOLUTE_PERCENTAGE_ERROR_FIELD_NUMBER;
hash = (53 * hash) + java.lang.Float.floatToIntBits(getMeanAbsolutePercentageError());
hash = (37 * hash) + R_SQUARED_FIELD_NUMBER;
hash = (53 * hash) + java.lang.Float.floatToIntBits(getRSquared());
hash = (37 * hash) + ROOT_MEAN_SQUARED_LOG_ERROR_FIELD_NUMBER;
hash = (53 * hash) + java.lang.Float.floatToIntBits(getRootMeanSquaredLogError());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics 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>
* Metrics for regression problems.
* </pre>
*
* Protobuf type {@code google.cloud.automl.v1beta1.RegressionEvaluationMetrics}
*/
public static final class Builder
extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.automl.v1beta1.RegressionEvaluationMetrics)
com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetricsOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.automl.v1beta1.RegressionProto
.internal_static_google_cloud_automl_v1beta1_RegressionEvaluationMetrics_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.automl.v1beta1.RegressionProto
.internal_static_google_cloud_automl_v1beta1_RegressionEvaluationMetrics_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics.class,
com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics.Builder
.class);
}
// Construct using
// com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
rootMeanSquaredError_ = 0F;
meanAbsoluteError_ = 0F;
meanAbsolutePercentageError_ = 0F;
rSquared_ = 0F;
rootMeanSquaredLogError_ = 0F;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.automl.v1beta1.RegressionProto
.internal_static_google_cloud_automl_v1beta1_RegressionEvaluationMetrics_descriptor;
}
@java.lang.Override
public com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
getDefaultInstanceForType() {
return com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics build() {
com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics result =
buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
buildPartial() {
com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics result =
new com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.rootMeanSquaredError_ = rootMeanSquaredError_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.meanAbsoluteError_ = meanAbsoluteError_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.meanAbsolutePercentageError_ = meanAbsolutePercentageError_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.rSquared_ = rSquared_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.rootMeanSquaredLogError_ = rootMeanSquaredLogError_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index,
java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other
instanceof
com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics) {
return mergeFrom(
(com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics other) {
if (other
== com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
.getDefaultInstance()) return this;
if (other.getRootMeanSquaredError() != 0F) {
setRootMeanSquaredError(other.getRootMeanSquaredError());
}
if (other.getMeanAbsoluteError() != 0F) {
setMeanAbsoluteError(other.getMeanAbsoluteError());
}
if (other.getMeanAbsolutePercentageError() != 0F) {
setMeanAbsolutePercentageError(other.getMeanAbsolutePercentageError());
}
if (other.getRSquared() != 0F) {
setRSquared(other.getRSquared());
}
if (other.getRootMeanSquaredLogError() != 0F) {
setRootMeanSquaredLogError(other.getRootMeanSquaredLogError());
}
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 13:
{
rootMeanSquaredError_ = input.readFloat();
bitField0_ |= 0x00000001;
break;
} // case 13
case 21:
{
meanAbsoluteError_ = input.readFloat();
bitField0_ |= 0x00000002;
break;
} // case 21
case 29:
{
meanAbsolutePercentageError_ = input.readFloat();
bitField0_ |= 0x00000004;
break;
} // case 29
case 37:
{
rSquared_ = input.readFloat();
bitField0_ |= 0x00000008;
break;
} // case 37
case 45:
{
rootMeanSquaredLogError_ = input.readFloat();
bitField0_ |= 0x00000010;
break;
} // case 45
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 float rootMeanSquaredError_;
/**
*
*
* <pre>
* Output only. Root Mean Squared Error (RMSE).
* </pre>
*
* <code>float root_mean_squared_error = 1;</code>
*
* @return The rootMeanSquaredError.
*/
@java.lang.Override
public float getRootMeanSquaredError() {
return rootMeanSquaredError_;
}
/**
*
*
* <pre>
* Output only. Root Mean Squared Error (RMSE).
* </pre>
*
* <code>float root_mean_squared_error = 1;</code>
*
* @param value The rootMeanSquaredError to set.
* @return This builder for chaining.
*/
public Builder setRootMeanSquaredError(float value) {
rootMeanSquaredError_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Root Mean Squared Error (RMSE).
* </pre>
*
* <code>float root_mean_squared_error = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearRootMeanSquaredError() {
bitField0_ = (bitField0_ & ~0x00000001);
rootMeanSquaredError_ = 0F;
onChanged();
return this;
}
private float meanAbsoluteError_;
/**
*
*
* <pre>
* Output only. Mean Absolute Error (MAE).
* </pre>
*
* <code>float mean_absolute_error = 2;</code>
*
* @return The meanAbsoluteError.
*/
@java.lang.Override
public float getMeanAbsoluteError() {
return meanAbsoluteError_;
}
/**
*
*
* <pre>
* Output only. Mean Absolute Error (MAE).
* </pre>
*
* <code>float mean_absolute_error = 2;</code>
*
* @param value The meanAbsoluteError to set.
* @return This builder for chaining.
*/
public Builder setMeanAbsoluteError(float value) {
meanAbsoluteError_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Mean Absolute Error (MAE).
* </pre>
*
* <code>float mean_absolute_error = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearMeanAbsoluteError() {
bitField0_ = (bitField0_ & ~0x00000002);
meanAbsoluteError_ = 0F;
onChanged();
return this;
}
private float meanAbsolutePercentageError_;
/**
*
*
* <pre>
* Output only. Mean absolute percentage error. Only set if all ground truth
* values are are positive.
* </pre>
*
* <code>float mean_absolute_percentage_error = 3;</code>
*
* @return The meanAbsolutePercentageError.
*/
@java.lang.Override
public float getMeanAbsolutePercentageError() {
return meanAbsolutePercentageError_;
}
/**
*
*
* <pre>
* Output only. Mean absolute percentage error. Only set if all ground truth
* values are are positive.
* </pre>
*
* <code>float mean_absolute_percentage_error = 3;</code>
*
* @param value The meanAbsolutePercentageError to set.
* @return This builder for chaining.
*/
public Builder setMeanAbsolutePercentageError(float value) {
meanAbsolutePercentageError_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Mean absolute percentage error. Only set if all ground truth
* values are are positive.
* </pre>
*
* <code>float mean_absolute_percentage_error = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearMeanAbsolutePercentageError() {
bitField0_ = (bitField0_ & ~0x00000004);
meanAbsolutePercentageError_ = 0F;
onChanged();
return this;
}
private float rSquared_;
/**
*
*
* <pre>
* Output only. R squared.
* </pre>
*
* <code>float r_squared = 4;</code>
*
* @return The rSquared.
*/
@java.lang.Override
public float getRSquared() {
return rSquared_;
}
/**
*
*
* <pre>
* Output only. R squared.
* </pre>
*
* <code>float r_squared = 4;</code>
*
* @param value The rSquared to set.
* @return This builder for chaining.
*/
public Builder setRSquared(float value) {
rSquared_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. R squared.
* </pre>
*
* <code>float r_squared = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearRSquared() {
bitField0_ = (bitField0_ & ~0x00000008);
rSquared_ = 0F;
onChanged();
return this;
}
private float rootMeanSquaredLogError_;
/**
*
*
* <pre>
* Output only. Root mean squared log error.
* </pre>
*
* <code>float root_mean_squared_log_error = 5;</code>
*
* @return The rootMeanSquaredLogError.
*/
@java.lang.Override
public float getRootMeanSquaredLogError() {
return rootMeanSquaredLogError_;
}
/**
*
*
* <pre>
* Output only. Root mean squared log error.
* </pre>
*
* <code>float root_mean_squared_log_error = 5;</code>
*
* @param value The rootMeanSquaredLogError to set.
* @return This builder for chaining.
*/
public Builder setRootMeanSquaredLogError(float value) {
rootMeanSquaredLogError_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. Root mean squared log error.
* </pre>
*
* <code>float root_mean_squared_log_error = 5;</code>
*
* @return This builder for chaining.
*/
public Builder clearRootMeanSquaredLogError() {
bitField0_ = (bitField0_ & ~0x00000010);
rootMeanSquaredLogError_ = 0F;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.automl.v1beta1.RegressionEvaluationMetrics)
}
// @@protoc_insertion_point(class_scope:google.cloud.automl.v1beta1.RegressionEvaluationMetrics)
private static final com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE =
new com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics();
}
public static com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<RegressionEvaluationMetrics> PARSER =
new com.google.protobuf.AbstractParser<RegressionEvaluationMetrics>() {
@java.lang.Override
public RegressionEvaluationMetrics 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<RegressionEvaluationMetrics> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<RegressionEvaluationMetrics> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.automl.v1beta1.RegressionProto.RegressionEvaluationMetrics
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_automl_v1beta1_RegressionEvaluationMetrics_descriptor;
private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_automl_v1beta1_RegressionEvaluationMetrics_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
java.lang.String[] descriptorData = {
"\n,google/cloud/automl/v1beta1/regression"
+ ".proto\022\033google.cloud.automl.v1beta1\"\273\001\n\033"
+ "RegressionEvaluationMetrics\022\037\n\027root_mean"
+ "_squared_error\030\001 \001(\002\022\033\n\023mean_absolute_er"
+ "ror\030\002 \001(\002\022&\n\036mean_absolute_percentage_er"
+ "ror\030\003 \001(\002\022\021\n\tr_squared\030\004 \001(\002\022#\n\033root_mea"
+ "n_squared_log_error\030\005 \001(\002B\252\001\n\037com.google"
+ ".cloud.automl.v1beta1B\017RegressionProtoZ7"
+ "cloud.google.com/go/automl/apiv1beta1/au"
+ "tomlpb;automlpb\312\002\033Google\\Cloud\\AutoMl\\V1"
+ "beta1\352\002\036Google::Cloud::AutoML::V1beta1b\006"
+ "proto3"
};
descriptor =
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {});
internal_static_google_cloud_automl_v1beta1_RegressionEvaluationMetrics_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_cloud_automl_v1beta1_RegressionEvaluationMetrics_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_automl_v1beta1_RegressionEvaluationMetrics_descriptor,
new java.lang.String[] {
"RootMeanSquaredError",
"MeanAbsoluteError",
"MeanAbsolutePercentageError",
"RSquared",
"RootMeanSquaredLogError",
});
}
// @@protoc_insertion_point(outer_class_scope)
}
|
googleapis/google-cloud-java | 36,478 | java-analytics-admin/proto-google-analytics-admin-v1alpha/src/main/java/com/google/analytics/admin/v1alpha/UpdatePropertyRequest.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 UpdateProperty RPC.
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1alpha.UpdatePropertyRequest}
*/
public final class UpdatePropertyRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.analytics.admin.v1alpha.UpdatePropertyRequest)
UpdatePropertyRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdatePropertyRequest.newBuilder() to construct.
private UpdatePropertyRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdatePropertyRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdatePropertyRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdatePropertyRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdatePropertyRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1alpha.UpdatePropertyRequest.class,
com.google.analytics.admin.v1alpha.UpdatePropertyRequest.Builder.class);
}
private int bitField0_;
public static final int PROPERTY_FIELD_NUMBER = 1;
private com.google.analytics.admin.v1alpha.Property property_;
/**
*
*
* <pre>
* Required. The property to update.
* The property's `name` field is used to identify the property to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Property property = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the property field is set.
*/
@java.lang.Override
public boolean hasProperty() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The property to update.
* The property's `name` field is used to identify the property to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Property property = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The property.
*/
@java.lang.Override
public com.google.analytics.admin.v1alpha.Property getProperty() {
return property_ == null
? com.google.analytics.admin.v1alpha.Property.getDefaultInstance()
: property_;
}
/**
*
*
* <pre>
* Required. The property to update.
* The property's `name` field is used to identify the property to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Property property = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.analytics.admin.v1alpha.PropertyOrBuilder getPropertyOrBuilder() {
return property_ == null
? com.google.analytics.admin.v1alpha.Property.getDefaultInstance()
: property_;
}
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, getProperty());
}
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, getProperty());
}
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.UpdatePropertyRequest)) {
return super.equals(obj);
}
com.google.analytics.admin.v1alpha.UpdatePropertyRequest other =
(com.google.analytics.admin.v1alpha.UpdatePropertyRequest) obj;
if (hasProperty() != other.hasProperty()) return false;
if (hasProperty()) {
if (!getProperty().equals(other.getProperty())) 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 (hasProperty()) {
hash = (37 * hash) + PROPERTY_FIELD_NUMBER;
hash = (53 * hash) + getProperty().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.UpdatePropertyRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.UpdatePropertyRequest 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.UpdatePropertyRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.UpdatePropertyRequest 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.UpdatePropertyRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.UpdatePropertyRequest 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.UpdatePropertyRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.UpdatePropertyRequest 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.UpdatePropertyRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.UpdatePropertyRequest 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.UpdatePropertyRequest 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.UpdatePropertyRequest 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.UpdatePropertyRequest 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 UpdateProperty RPC.
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1alpha.UpdatePropertyRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.analytics.admin.v1alpha.UpdatePropertyRequest)
com.google.analytics.admin.v1alpha.UpdatePropertyRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdatePropertyRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_UpdatePropertyRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1alpha.UpdatePropertyRequest.class,
com.google.analytics.admin.v1alpha.UpdatePropertyRequest.Builder.class);
}
// Construct using com.google.analytics.admin.v1alpha.UpdatePropertyRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getPropertyFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
property_ = null;
if (propertyBuilder_ != null) {
propertyBuilder_.dispose();
propertyBuilder_ = 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_UpdatePropertyRequest_descriptor;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.UpdatePropertyRequest getDefaultInstanceForType() {
return com.google.analytics.admin.v1alpha.UpdatePropertyRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.UpdatePropertyRequest build() {
com.google.analytics.admin.v1alpha.UpdatePropertyRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.UpdatePropertyRequest buildPartial() {
com.google.analytics.admin.v1alpha.UpdatePropertyRequest result =
new com.google.analytics.admin.v1alpha.UpdatePropertyRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.analytics.admin.v1alpha.UpdatePropertyRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.property_ = propertyBuilder_ == null ? property_ : propertyBuilder_.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.UpdatePropertyRequest) {
return mergeFrom((com.google.analytics.admin.v1alpha.UpdatePropertyRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.analytics.admin.v1alpha.UpdatePropertyRequest other) {
if (other == com.google.analytics.admin.v1alpha.UpdatePropertyRequest.getDefaultInstance())
return this;
if (other.hasProperty()) {
mergeProperty(other.getProperty());
}
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(getPropertyFieldBuilder().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.Property property_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.analytics.admin.v1alpha.Property,
com.google.analytics.admin.v1alpha.Property.Builder,
com.google.analytics.admin.v1alpha.PropertyOrBuilder>
propertyBuilder_;
/**
*
*
* <pre>
* Required. The property to update.
* The property's `name` field is used to identify the property to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Property property = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the property field is set.
*/
public boolean hasProperty() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The property to update.
* The property's `name` field is used to identify the property to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Property property = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The property.
*/
public com.google.analytics.admin.v1alpha.Property getProperty() {
if (propertyBuilder_ == null) {
return property_ == null
? com.google.analytics.admin.v1alpha.Property.getDefaultInstance()
: property_;
} else {
return propertyBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The property to update.
* The property's `name` field is used to identify the property to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Property property = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setProperty(com.google.analytics.admin.v1alpha.Property value) {
if (propertyBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
property_ = value;
} else {
propertyBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The property to update.
* The property's `name` field is used to identify the property to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Property property = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setProperty(
com.google.analytics.admin.v1alpha.Property.Builder builderForValue) {
if (propertyBuilder_ == null) {
property_ = builderForValue.build();
} else {
propertyBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The property to update.
* The property's `name` field is used to identify the property to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Property property = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeProperty(com.google.analytics.admin.v1alpha.Property value) {
if (propertyBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& property_ != null
&& property_ != com.google.analytics.admin.v1alpha.Property.getDefaultInstance()) {
getPropertyBuilder().mergeFrom(value);
} else {
property_ = value;
}
} else {
propertyBuilder_.mergeFrom(value);
}
if (property_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The property to update.
* The property's `name` field is used to identify the property to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Property property = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearProperty() {
bitField0_ = (bitField0_ & ~0x00000001);
property_ = null;
if (propertyBuilder_ != null) {
propertyBuilder_.dispose();
propertyBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The property to update.
* The property's `name` field is used to identify the property to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Property property = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.analytics.admin.v1alpha.Property.Builder getPropertyBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getPropertyFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The property to update.
* The property's `name` field is used to identify the property to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Property property = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.analytics.admin.v1alpha.PropertyOrBuilder getPropertyOrBuilder() {
if (propertyBuilder_ != null) {
return propertyBuilder_.getMessageOrBuilder();
} else {
return property_ == null
? com.google.analytics.admin.v1alpha.Property.getDefaultInstance()
: property_;
}
}
/**
*
*
* <pre>
* Required. The property to update.
* The property's `name` field is used to identify the property to be
* updated.
* </pre>
*
* <code>
* .google.analytics.admin.v1alpha.Property property = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.analytics.admin.v1alpha.Property,
com.google.analytics.admin.v1alpha.Property.Builder,
com.google.analytics.admin.v1alpha.PropertyOrBuilder>
getPropertyFieldBuilder() {
if (propertyBuilder_ == null) {
propertyBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.analytics.admin.v1alpha.Property,
com.google.analytics.admin.v1alpha.Property.Builder,
com.google.analytics.admin.v1alpha.PropertyOrBuilder>(
getProperty(), getParentForChildren(), isClean());
property_ = null;
}
return propertyBuilder_;
}
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.UpdatePropertyRequest)
}
// @@protoc_insertion_point(class_scope:google.analytics.admin.v1alpha.UpdatePropertyRequest)
private static final com.google.analytics.admin.v1alpha.UpdatePropertyRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.analytics.admin.v1alpha.UpdatePropertyRequest();
}
public static com.google.analytics.admin.v1alpha.UpdatePropertyRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdatePropertyRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdatePropertyRequest>() {
@java.lang.Override
public UpdatePropertyRequest 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<UpdatePropertyRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdatePropertyRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.UpdatePropertyRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/ranger | 36,877 | intg/src/main/java/org/apache/ranger/RangerClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ranger;
import com.fasterxml.jackson.core.type.TypeReference;
import com.sun.jersey.api.client.ClientResponse;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.ranger.admin.client.datatype.RESTResponse;
import org.apache.ranger.audit.provider.MiscUtil;
import org.apache.ranger.authorization.hadoop.config.RangerPluginConfig;
import org.apache.ranger.plugin.model.RangerPluginInfo;
import org.apache.ranger.plugin.model.RangerPolicy;
import org.apache.ranger.plugin.model.RangerRole;
import org.apache.ranger.plugin.model.RangerSecurityZone;
import org.apache.ranger.plugin.model.RangerSecurityZoneHeaderInfo;
import org.apache.ranger.plugin.model.RangerService;
import org.apache.ranger.plugin.model.RangerServiceDef;
import org.apache.ranger.plugin.model.RangerServiceHeaderInfo;
import org.apache.ranger.plugin.model.RangerServiceTags;
import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
import org.apache.ranger.plugin.util.JsonUtilsV2;
import org.apache.ranger.plugin.util.RangerPurgeResult;
import org.apache.ranger.plugin.util.RangerRESTClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.security.PrivilegedExceptionAction;
import java.util.Collections;
import java.util.HashMap;
import java.util.IllegalFormatException;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class RangerClient {
private static final Logger LOG = LoggerFactory.getLogger(RangerClient.class);
private static final String AUTH_KERBEROS = "kerberos";
// QueryParams
private static final String PARAM_DAYS = "days";
private static final String PARAM_EXEC_USER = "execUser";
private static final String PARAM_POLICY_NAME = "policyname";
private static final String PARAM_SERVICE_NAME = "serviceName";
private static final String PARAM_ZONE_NAME = "zoneName";
private static final String PARAM_PURGE_RECORD_TYPE = "type";
private static final String PARAM_PURGE_RETENTION_DAYS = "retentionDays";
private static final String PARAM_RELOAD_SERVICE_POLICIES_CACHE = "reloadServicePoliciesCache";
// URIs
private static final String URI_BASE = "/service/public/v2/api";
private static final String URI_SERVICEDEF = URI_BASE + "/servicedef";
private static final String URI_SERVICEDEF_BY_ID = URI_SERVICEDEF + "/%d";
private static final String URI_SERVICEDEF_BY_NAME = URI_SERVICEDEF + "/name/%s";
private static final String URI_SERVICE = URI_BASE + "/service";
private static final String URI_SERVICE_BY_ID = URI_SERVICE + "/%d";
private static final String URI_SERVICE_BY_NAME = URI_SERVICE + "/name/%s";
private static final String URI_POLICIES_IN_SERVICE = URI_SERVICE + "/%s/policy";
private static final String URI_POLICY = URI_BASE + "/policy";
private static final String URI_APPLY_POLICY = URI_POLICY + "/apply";
private static final String URI_POLICY_BY_ID = URI_POLICY + "/%d";
private static final String URI_POLICY_BY_NAME = URI_SERVICE + "/%s/policy/%s";
private static final String URI_ROLE = URI_BASE + "/roles";
private static final String URI_ROLE_NAMES = URI_ROLE + "/names";
private static final String URI_ROLE_BY_ID = URI_ROLE + "/%d";
private static final String URI_ROLE_BY_NAME = URI_ROLE + "/name/%s";
private static final String URI_USER_ROLES = URI_ROLE + "/user/%s";
private static final String URI_GRANT_ROLE = URI_ROLE + "/grant/%s";
private static final String URI_REVOKE_ROLE = URI_ROLE + "/revoke/%s";
private static final String URI_ZONE = URI_BASE + "/zones";
private static final String URI_ZONE_BY_ID = URI_ZONE + "/%d";
private static final String URI_ZONE_BY_NAME = URI_ZONE + "/name/%s";
private static final String URI_ZONE_HEADERS = URI_BASE + "/zone-headers";
private static final String URI_ZONE_SERVICE_HEADERS = URI_ZONE + "/%d/service-headers";
private static final String URI_ZONE_NAMES_FOR_RES = URI_BASE + "/zone-names/%s/resource";
private static final String URI_SERVICE_TAGS = URI_SERVICE + "/%s/tags";
private static final String URI_PLUGIN_INFO = URI_BASE + "/plugins/info";
private static final String URI_POLICY_DELTAS = URI_BASE + "/server/policydeltas";
private static final String URI_PURGE_RECORDS = URI_BASE + "/server/purge/records";
private static final String URI_LOGGERS_SET_LEVEL = "/service/admin/set-logger-level";
// APIs
public static final API CREATE_SERVICEDEF = new API(URI_SERVICEDEF, HttpMethod.POST, Response.Status.OK);
public static final API UPDATE_SERVICEDEF_BY_ID = new API(URI_SERVICEDEF_BY_ID, HttpMethod.PUT, Response.Status.OK);
public static final API UPDATE_SERVICEDEF_BY_NAME = new API(URI_SERVICEDEF_BY_NAME, HttpMethod.PUT, Response.Status.OK);
public static final API DELETE_SERVICEDEF_BY_ID = new API(URI_SERVICEDEF_BY_ID, HttpMethod.DELETE, Response.Status.NO_CONTENT);
public static final API DELETE_SERVICEDEF_BY_NAME = new API(URI_SERVICEDEF_BY_NAME, HttpMethod.DELETE, Response.Status.NO_CONTENT);
public static final API GET_SERVICEDEF_BY_ID = new API(URI_SERVICEDEF_BY_ID, HttpMethod.GET, Response.Status.OK);
public static final API GET_SERVICEDEF_BY_NAME = new API(URI_SERVICEDEF_BY_NAME, HttpMethod.GET, Response.Status.OK);
public static final API FIND_SERVICEDEFS = new API(URI_SERVICEDEF, HttpMethod.GET, Response.Status.OK);
public static final API CREATE_SERVICE = new API(URI_SERVICE, HttpMethod.POST, Response.Status.OK);
public static final API UPDATE_SERVICE_BY_ID = new API(URI_SERVICE_BY_ID, HttpMethod.PUT, Response.Status.OK);
public static final API UPDATE_SERVICE_BY_NAME = new API(URI_SERVICE_BY_NAME, HttpMethod.PUT, Response.Status.OK);
public static final API DELETE_SERVICE_BY_ID = new API(URI_SERVICE_BY_ID, HttpMethod.DELETE, Response.Status.NO_CONTENT);
public static final API DELETE_SERVICE_BY_NAME = new API(URI_SERVICE_BY_NAME, HttpMethod.DELETE, Response.Status.NO_CONTENT);
public static final API GET_SERVICE_BY_ID = new API(URI_SERVICE_BY_ID, HttpMethod.GET, Response.Status.OK);
public static final API GET_SERVICE_BY_NAME = new API(URI_SERVICE_BY_NAME, HttpMethod.GET, Response.Status.OK);
public static final API FIND_SERVICES = new API(URI_SERVICE, HttpMethod.GET, Response.Status.OK);
public static final API CREATE_POLICY = new API(URI_POLICY, HttpMethod.POST, Response.Status.OK);
public static final API UPDATE_POLICY_BY_ID = new API(URI_POLICY_BY_ID, HttpMethod.PUT, Response.Status.OK);
public static final API UPDATE_POLICY_BY_NAME = new API(URI_POLICY_BY_NAME, HttpMethod.PUT, Response.Status.OK);
public static final API APPLY_POLICY = new API(URI_APPLY_POLICY, HttpMethod.POST, Response.Status.OK);
public static final API DELETE_POLICY_BY_ID = new API(URI_POLICY_BY_ID, HttpMethod.DELETE, Response.Status.NO_CONTENT);
public static final API DELETE_POLICY_BY_NAME = new API(URI_POLICY, HttpMethod.DELETE, Response.Status.NO_CONTENT);
public static final API GET_POLICY_BY_ID = new API(URI_POLICY_BY_ID, HttpMethod.GET, Response.Status.OK);
public static final API GET_POLICY_BY_NAME = new API(URI_POLICY_BY_NAME, HttpMethod.GET, Response.Status.OK);
public static final API GET_POLICIES_IN_SERVICE = new API(URI_POLICIES_IN_SERVICE, HttpMethod.GET, Response.Status.OK);
public static final API FIND_POLICIES = new API(URI_POLICY, HttpMethod.GET, Response.Status.OK);
public static final API CREATE_ZONE = new API(URI_ZONE, HttpMethod.POST, Response.Status.OK);
public static final API UPDATE_ZONE_BY_ID = new API(URI_ZONE_BY_ID, HttpMethod.PUT, Response.Status.OK);
public static final API DELETE_ZONE_BY_ID = new API(URI_ZONE_BY_ID, HttpMethod.DELETE, Response.Status.NO_CONTENT);
public static final API DELETE_ZONE_BY_NAME = new API(URI_ZONE_BY_NAME, HttpMethod.DELETE, Response.Status.NO_CONTENT);
public static final API GET_ZONE_BY_ID = new API(URI_ZONE_BY_ID, HttpMethod.GET, Response.Status.OK);
public static final API GET_ZONE_BY_NAME = new API(URI_ZONE_BY_NAME, HttpMethod.GET, Response.Status.OK);
public static final API GET_ZONE_HEADERS = new API(URI_ZONE_HEADERS, HttpMethod.GET, Response.Status.OK);
public static final API GET_ZONE_SERVICE_HEADERS = new API(URI_ZONE_SERVICE_HEADERS, HttpMethod.GET, Response.Status.OK);
public static final API GET_ZONE_NAMES_FOR_RES = new API(URI_ZONE_NAMES_FOR_RES, HttpMethod.GET, Response.Status.OK);
public static final API FIND_ZONES = new API(URI_ZONE, HttpMethod.GET, Response.Status.OK);
public static final API CREATE_ROLE = new API(URI_ROLE, HttpMethod.POST, Response.Status.OK);
public static final API UPDATE_ROLE_BY_ID = new API(URI_ROLE_BY_ID, HttpMethod.PUT, Response.Status.OK);
public static final API DELETE_ROLE_BY_ID = new API(URI_ROLE_BY_ID, HttpMethod.DELETE, Response.Status.NO_CONTENT);
public static final API DELETE_ROLE_BY_NAME = new API(URI_ROLE_BY_NAME, HttpMethod.DELETE, Response.Status.NO_CONTENT);
public static final API GET_ROLE_BY_ID = new API(URI_ROLE_BY_ID, HttpMethod.GET, Response.Status.OK);
public static final API GET_ROLE_BY_NAME = new API(URI_ROLE_BY_NAME, HttpMethod.GET, Response.Status.OK);
public static final API GET_ALL_ROLE_NAMES = new API(URI_ROLE_NAMES, HttpMethod.GET, Response.Status.OK);
public static final API GET_USER_ROLES = new API(URI_USER_ROLES, HttpMethod.GET, Response.Status.OK);
public static final API GRANT_ROLE = new API(URI_GRANT_ROLE, HttpMethod.PUT, Response.Status.OK);
public static final API REVOKE_ROLE = new API(URI_REVOKE_ROLE, HttpMethod.PUT, Response.Status.OK);
public static final API FIND_ROLES = new API(URI_ROLE, HttpMethod.GET, Response.Status.OK);
public static final API IMPORT_SERVICE_TAGS = new API(URI_SERVICE_TAGS, HttpMethod.PUT, Response.Status.NO_CONTENT);
public static final API GET_SERVICE_TAGS = new API(URI_SERVICE_TAGS, HttpMethod.GET, Response.Status.OK);
public static final API GET_PLUGIN_INFO = new API(URI_PLUGIN_INFO, HttpMethod.GET, Response.Status.OK);
public static final API DELETE_POLICY_DELTAS = new API(URI_POLICY_DELTAS, HttpMethod.DELETE, Response.Status.NO_CONTENT);
public static final API PURGE_RECORDS = new API(URI_PURGE_RECORDS, HttpMethod.DELETE, Response.Status.OK);
public static final API SET_LOG_LEVEL = new API(URI_LOGGERS_SET_LEVEL, HttpMethod.POST, Response.Status.OK);
private static final TypeReference<Void> TYPE_VOID = new TypeReference<Void>() {};
private static final TypeReference<Set<String>> TYPE_SET_STRING = new TypeReference<Set<String>>() {};
private static final TypeReference<List<String>> TYPE_LIST_STRING = new TypeReference<List<String>>() {};
private static final TypeReference<List<RangerServiceDef>> TYPE_LIST_SERVICE_DEF = new TypeReference<List<RangerServiceDef>>() {};
private static final TypeReference<List<RangerService>> TYPE_LIST_SERVICE = new TypeReference<List<RangerService>>() {};
private static final TypeReference<List<RangerPolicy>> TYPE_LIST_POLICY = new TypeReference<List<RangerPolicy>>() {};
private static final TypeReference<List<RangerSecurityZone>> TYPE_LIST_SZ = new TypeReference<List<RangerSecurityZone>>() {};
private static final TypeReference<List<RangerRole>> TYPE_LIST_ROLE = new TypeReference<List<RangerRole>>() {};
private static final TypeReference<List<RangerPluginInfo>> TYPE_LIST_PLUGIN_INFO = new TypeReference<List<RangerPluginInfo>>() {};
private static final TypeReference<List<RangerPurgeResult>> TYPE_LIST_PURGE_RESULT = new TypeReference<List<RangerPurgeResult>>() {};
private static final TypeReference<List<RangerSecurityZoneHeaderInfo>> TYPE_LIST_SZ_HEADER_INFO = new TypeReference<List<RangerSecurityZoneHeaderInfo>>() {};
private static final TypeReference<List<RangerServiceHeaderInfo>> TYPE_LIST_SVC_HEADER_INFO = new TypeReference<List<RangerServiceHeaderInfo>>() {};
private final RangerRESTClient restClient;
private boolean isSecureMode;
public RangerClient(String hostName, String authType, String username, String password, String configFile) {
restClient = new RangerRESTClient(hostName, configFile, new Configuration());
authInit(authType, username, password);
}
public RangerClient(String hostname, String authType, String username, String password, String appId, String serviceType) {
this(hostname, authType, username, password,
new RangerPluginConfig(serviceType, null, appId, null, null, null)
.get("ranger.plugin." + serviceType + ".policy.rest.ssl.config.file"));
}
public RangerClient(RangerRESTClient restClient) {
this.restClient = restClient;
}
/*
* ServiceDef APIs
*/
public RangerServiceDef createServiceDef(RangerServiceDef serviceDef) throws RangerServiceException {
return callAPI(CREATE_SERVICEDEF, null, serviceDef, RangerServiceDef.class);
}
public RangerServiceDef updateServiceDef(long serviceDefId, RangerServiceDef serviceDef) throws RangerServiceException {
return callAPI(UPDATE_SERVICEDEF_BY_ID.applyUrlFormat(serviceDefId), null, serviceDef, RangerServiceDef.class);
}
public RangerServiceDef updateServiceDef(String serviceDefName, RangerServiceDef serviceDef) throws RangerServiceException {
return callAPI(UPDATE_SERVICEDEF_BY_NAME.applyUrlFormat(serviceDefName), null, serviceDef, RangerServiceDef.class);
}
public void deleteServiceDef(long serviceDefId) throws RangerServiceException {
callAPI(DELETE_SERVICEDEF_BY_ID.applyUrlFormat(serviceDefId), null);
}
public void deleteServiceDef(String serviceDefName) throws RangerServiceException {
callAPI(DELETE_SERVICEDEF_BY_NAME.applyUrlFormat(serviceDefName), null);
}
public RangerServiceDef getServiceDef(long serviceDefId) throws RangerServiceException {
return callAPI(GET_SERVICEDEF_BY_ID.applyUrlFormat(serviceDefId), null, null, RangerServiceDef.class);
}
public RangerServiceDef getServiceDef(String serviceDefName) throws RangerServiceException {
return callAPI(GET_SERVICEDEF_BY_NAME.applyUrlFormat(serviceDefName), null, null, RangerServiceDef.class);
}
public List<RangerServiceDef> findServiceDefs(Map<String, String> filter) throws RangerServiceException {
return callAPI(FIND_SERVICEDEFS, filter, null, TYPE_LIST_SERVICE_DEF);
}
/*
* Service APIs
*/
public RangerService createService(RangerService service) throws RangerServiceException {
return callAPI(CREATE_SERVICE, null, service, RangerService.class);
}
public RangerService updateService(long serviceId, RangerService service) throws RangerServiceException {
return callAPI(UPDATE_SERVICE_BY_ID.applyUrlFormat(serviceId), null, service, RangerService.class);
}
public RangerService updateService(String serviceName, RangerService service) throws RangerServiceException {
return callAPI(UPDATE_SERVICE_BY_NAME.applyUrlFormat(serviceName), null, service, RangerService.class);
}
public void deleteService(long serviceId) throws RangerServiceException {
callAPI(DELETE_SERVICE_BY_ID.applyUrlFormat(serviceId), null);
}
public void deleteService(String serviceName) throws RangerServiceException {
callAPI(DELETE_SERVICE_BY_NAME.applyUrlFormat(serviceName), null);
}
public RangerService getService(long serviceId) throws RangerServiceException {
return callAPI(GET_SERVICE_BY_ID.applyUrlFormat(serviceId), null, null, RangerService.class);
}
public RangerService getService(String serviceName) throws RangerServiceException {
return callAPI(GET_SERVICE_BY_NAME.applyUrlFormat(serviceName), null, null, RangerService.class);
}
public List<RangerService> findServices(Map<String, String> filter) throws RangerServiceException {
return callAPI(FIND_SERVICES, filter, null, TYPE_LIST_SERVICE);
}
/*
* Policy APIs
*/
public RangerPolicy createPolicy(RangerPolicy policy) throws RangerServiceException {
return callAPI(CREATE_POLICY, null, policy, RangerPolicy.class);
}
public RangerPolicy updatePolicy(long policyId, RangerPolicy policy) throws RangerServiceException {
return callAPI(UPDATE_POLICY_BY_ID.applyUrlFormat(policyId), null, policy, RangerPolicy.class);
}
public RangerPolicy updatePolicy(String serviceName, String policyName, RangerPolicy policy) throws RangerServiceException {
return callAPI(UPDATE_POLICY_BY_NAME.applyUrlFormat(serviceName, policyName), null, policy, RangerPolicy.class);
}
public RangerPolicy updatePolicyByNameAndZone(String serviceName, String policyName, String zoneName, RangerPolicy policy) throws RangerServiceException {
Map<String, String> queryParams = new HashMap<>();
queryParams.put(PARAM_ZONE_NAME, zoneName);
return callAPI(UPDATE_POLICY_BY_NAME.applyUrlFormat(serviceName, policyName), queryParams, policy, RangerPolicy.class);
}
public RangerPolicy applyPolicy(RangerPolicy policy) throws RangerServiceException {
return callAPI(APPLY_POLICY, null, policy, RangerPolicy.class);
}
public void deletePolicy(long policyId) throws RangerServiceException {
callAPI(DELETE_POLICY_BY_ID.applyUrlFormat(policyId), null);
}
public void deletePolicy(String serviceName, String policyName) throws RangerServiceException {
Map<String, String> queryParams = new HashMap<>();
queryParams.put(PARAM_POLICY_NAME, policyName);
queryParams.put("servicename", serviceName);
callAPI(DELETE_POLICY_BY_NAME, queryParams);
}
public void deletePolicyByNameAndZone(String serviceName, String policyName, String zoneName) throws RangerServiceException {
Map<String, String> queryParams = new HashMap<>();
queryParams.put(PARAM_POLICY_NAME, policyName);
queryParams.put(PARAM_SERVICE_NAME, serviceName);
queryParams.put(PARAM_ZONE_NAME, zoneName);
callAPI(DELETE_POLICY_BY_NAME, queryParams);
}
public RangerPolicy getPolicy(long policyId) throws RangerServiceException {
return callAPI(GET_POLICY_BY_ID.applyUrlFormat(policyId), null, null, RangerPolicy.class);
}
public RangerPolicy getPolicy(String serviceName, String policyName) throws RangerServiceException {
return callAPI(GET_POLICY_BY_NAME.applyUrlFormat(serviceName, policyName), null, null, RangerPolicy.class);
}
public RangerPolicy getPolicyByNameAndZone(String serviceName, String policyName, String zoneName) throws RangerServiceException {
Map<String, String> queryParams = new HashMap<>();
queryParams.put(PARAM_ZONE_NAME, zoneName);
return callAPI(GET_POLICY_BY_NAME.applyUrlFormat(serviceName, policyName), queryParams, null, RangerPolicy.class);
}
public List<RangerPolicy> getPoliciesInService(String serviceName) throws RangerServiceException {
return callAPI(GET_POLICIES_IN_SERVICE.applyUrlFormat(serviceName), null, null, TYPE_LIST_POLICY);
}
public List<RangerPolicy> findPolicies(Map<String, String> filter) throws RangerServiceException {
return callAPI(FIND_POLICIES, filter, null, TYPE_LIST_POLICY);
}
/*
* SecurityZone APIs
*/
public RangerSecurityZone createSecurityZone(RangerSecurityZone securityZone) throws RangerServiceException {
return callAPI(CREATE_ZONE, null, securityZone, RangerSecurityZone.class);
}
public RangerSecurityZone updateSecurityZone(long zoneId, RangerSecurityZone securityZone) throws RangerServiceException {
return callAPI(UPDATE_ZONE_BY_ID.applyUrlFormat(zoneId), null, securityZone, RangerSecurityZone.class);
}
public void deleteSecurityZone(long zoneId) throws RangerServiceException {
callAPI(DELETE_ZONE_BY_ID.applyUrlFormat(zoneId), null);
}
public void deleteSecurityZone(String zoneName) throws RangerServiceException {
callAPI(DELETE_ZONE_BY_NAME.applyUrlFormat(zoneName), null);
}
public RangerSecurityZone getSecurityZone(long zoneId) throws RangerServiceException {
return callAPI(GET_ZONE_BY_ID.applyUrlFormat(zoneId), null, null, RangerSecurityZone.class);
}
public RangerSecurityZone getSecurityZone(String zoneName) throws RangerServiceException {
return callAPI(GET_ZONE_BY_NAME.applyUrlFormat(zoneName), null, null, RangerSecurityZone.class);
}
public List<RangerSecurityZoneHeaderInfo> getSecurityZoneHeaders(Map<String, String> filter) throws RangerServiceException {
return callAPI(GET_ZONE_HEADERS, filter, null, TYPE_LIST_SZ_HEADER_INFO);
}
public List<RangerServiceHeaderInfo> getSecurityZoneServiceHeaders(Map<String, String> filter) throws RangerServiceException {
return callAPI(GET_ZONE_SERVICE_HEADERS, filter, null, TYPE_LIST_SVC_HEADER_INFO);
}
public Set<String> getSecurityZoneNamesForResource(String serviceName, Map<String, String> resource) throws RangerServiceException {
return callAPI(GET_ZONE_NAMES_FOR_RES.applyUrlFormat(serviceName), resource, null, TYPE_SET_STRING);
}
public List<RangerSecurityZone> findSecurityZones(Map<String, String> filter) throws RangerServiceException {
return callAPI(FIND_ZONES, filter, null, TYPE_LIST_SZ);
}
/*
* Role APIs
*/
public RangerRole createRole(String serviceName, RangerRole role) throws RangerServiceException {
return callAPI(CREATE_ROLE, Collections.singletonMap(PARAM_SERVICE_NAME, serviceName), role, RangerRole.class);
}
public RangerRole updateRole(long roleId, RangerRole role) throws RangerServiceException {
return callAPI(UPDATE_ROLE_BY_ID.applyUrlFormat(roleId), null, role, RangerRole.class);
}
public void deleteRole(long roleId) throws RangerServiceException {
callAPI(DELETE_ROLE_BY_ID.applyUrlFormat(roleId), null);
}
public void deleteRole(String roleName, String execUser, String serviceName) throws RangerServiceException {
Map<String, String> queryParams = new HashMap<>();
queryParams.put(PARAM_EXEC_USER, execUser);
queryParams.put(PARAM_SERVICE_NAME, serviceName);
callAPI(DELETE_ROLE_BY_NAME.applyUrlFormat(roleName), queryParams);
}
public RangerRole getRole(long roleId) throws RangerServiceException {
return callAPI(GET_ROLE_BY_ID.applyUrlFormat(roleId), null, null, RangerRole.class);
}
public RangerRole getRole(String roleName, String execUser, String serviceName) throws RangerServiceException {
Map<String, String> queryParams = new HashMap<>();
queryParams.put(PARAM_EXEC_USER, execUser);
queryParams.put(PARAM_SERVICE_NAME, serviceName);
return callAPI(GET_ROLE_BY_NAME.applyUrlFormat(roleName), queryParams, null, RangerRole.class);
}
public List<String> getAllRoleNames(String execUser, String serviceName) throws RangerServiceException {
Map<String, String> queryParams = new HashMap<>();
queryParams.put(PARAM_EXEC_USER, execUser);
queryParams.put(PARAM_SERVICE_NAME, serviceName);
return callAPI(GET_ALL_ROLE_NAMES.applyUrlFormat(serviceName), queryParams, null, TYPE_LIST_STRING);
}
public List<String> getUserRoles(String user) throws RangerServiceException {
return callAPI(GET_USER_ROLES.applyUrlFormat(user), null, null, TYPE_LIST_STRING);
}
public List<RangerRole> findRoles(Map<String, String> filter) throws RangerServiceException {
return callAPI(FIND_ROLES, filter, null, TYPE_LIST_ROLE);
}
public RESTResponse grantRole(String serviceName, GrantRevokeRoleRequest request) throws RangerServiceException {
return callAPI(GRANT_ROLE.applyUrlFormat(serviceName), null, request, RESTResponse.class);
}
public RESTResponse revokeRole(String serviceName, GrantRevokeRoleRequest request) throws RangerServiceException {
return callAPI(REVOKE_ROLE.applyUrlFormat(serviceName), null, request, RESTResponse.class);
}
/*
* Admin APIs
*/
public void importServiceTags(String serviceName, RangerServiceTags svcTags) throws RangerServiceException {
callAPI(IMPORT_SERVICE_TAGS.applyUrlFormat(serviceName), null, svcTags, TYPE_VOID);
}
public RangerServiceTags getServiceTags(String serviceName) throws RangerServiceException {
return callAPI(GET_SERVICE_TAGS.applyUrlFormat(serviceName), null, null, RangerServiceTags.class);
}
public List<RangerPluginInfo> getPluginsInfo() throws RangerServiceException {
return callAPI(GET_PLUGIN_INFO, null, null, TYPE_LIST_PLUGIN_INFO);
}
public void deletePolicyDeltas(int days, boolean reloadServicePoliciesCache) throws RangerServiceException {
Map<String, String> queryParams = new HashMap<>();
queryParams.put(PARAM_DAYS, String.valueOf(days));
queryParams.put(PARAM_RELOAD_SERVICE_POLICIES_CACHE, String.valueOf(reloadServicePoliciesCache));
callAPI(DELETE_POLICY_DELTAS, queryParams);
}
public List<RangerPurgeResult> purgeRecords(String recordType, int retentionDays) throws RangerServiceException {
Map<String, String> queryParams = new HashMap<>();
queryParams.put(PARAM_PURGE_RECORD_TYPE, recordType);
queryParams.put(PARAM_PURGE_RETENTION_DAYS, String.valueOf(retentionDays));
return callAPI(PURGE_RECORDS, queryParams, null, TYPE_LIST_PURGE_RESULT);
}
/**
* Sets the log level for a specific class or package.
* This operation requires ROLE_SYS_ADMIN role.
*
* @param loggerName The name of the logger (class or package name)
* @param logLevel The log level to set (TRACE, DEBUG, INFO, WARN, ERROR, OFF)
* @return A message indicating the result of the operation
* @throws RangerServiceException if the operation fails
*/
public String setLogLevel(String loggerName, String logLevel) throws RangerServiceException {
Map<String, Object> requestData = new HashMap<>();
requestData.put("loggerName", loggerName);
requestData.put("logLevel", logLevel);
return callAPI(SET_LOG_LEVEL, null, requestData, new TypeReference<String>() {});
}
private void authInit(String authType, String username, String password) {
if (AUTH_KERBEROS.equalsIgnoreCase(authType)) {
isSecureMode = true;
MiscUtil.loginWithKeyTab(password, username, null);
UserGroupInformation ugi = MiscUtil.getUGILoginUser();
LOG.info("RangerClient.authInit() UGI user: {} principal: {}", ugi.getUserName(), username);
} else {
restClient.setBasicAuthInfo(username, password);
}
}
private ClientResponse invokeREST(API api, Map<String, String> params, Object request) throws RangerServiceException {
final ClientResponse clientResponse;
try {
switch (api.getMethod()) {
case HttpMethod.POST:
clientResponse = restClient.post(api.getPath(), params, request);
break;
case HttpMethod.PUT:
clientResponse = restClient.put(api.getPath(), params, request);
break;
case HttpMethod.GET:
clientResponse = restClient.get(api.getPath(), params);
break;
case HttpMethod.DELETE:
clientResponse = restClient.delete(api.getPath(), params);
break;
default:
LOG.error("{}: unsupported HTTP method", api.getMethod());
clientResponse = null;
}
} catch (Exception excp) {
throw new RangerServiceException(excp);
}
return clientResponse;
}
private ClientResponse responseHandler(API api, Map<String, String> params, Object request) throws RangerServiceException {
final ClientResponse clientResponse;
if (LOG.isDebugEnabled()) {
LOG.debug("Call : {} {}", api.getMethod(), api.getNormalizedPath());
LOG.debug("Content-type : {} ", api.getConsumes());
LOG.debug("Accept : {} ", api.getProduces());
if (request != null) {
LOG.debug("Request : {}", request);
}
}
if (isSecureMode) {
try {
clientResponse = MiscUtil.executePrivilegedAction((PrivilegedExceptionAction<ClientResponse>) () -> {
try {
return invokeREST(api, params, request);
} catch (RangerServiceException e) {
LOG.error(e.getMessage());
}
return null;
});
} catch (Exception excp) {
throw new RangerServiceException(excp);
}
} else {
clientResponse = invokeREST(api, params, request);
}
if (LOG.isDebugEnabled()) {
LOG.debug("method={}, path={}, contentType={}, accept={}, httpStatus={}", api.getMethod(), api.getNormalizedPath(), api.getConsumes(), api.getProduces(), (clientResponse != null ? clientResponse.getStatus() : "null"));
}
if (clientResponse == null) {
throw new RangerServiceException(api, null);
} else if (clientResponse.getStatus() == api.getExpectedStatus().getStatusCode()) {
return clientResponse;
} else if (clientResponse.getStatus() == ClientResponse.Status.SERVICE_UNAVAILABLE.getStatusCode()) {
LOG.error("Ranger Admin unavailable. HTTP Status: {}", clientResponse.getStatus());
} else {
throw new RangerServiceException(api, clientResponse);
}
return clientResponse;
}
private void callAPI(API api, Map<String, String> params) throws RangerServiceException {
if (LOG.isDebugEnabled()) {
LOG.debug("==> callAPI({},{})", api, params);
}
responseHandler(api, params, null);
if (LOG.isDebugEnabled()) {
LOG.debug("<== callAPI({},{})", api, params);
}
}
private <T> T callAPI(API api, Map<String, String> params, Object request, TypeReference<T> responseType) throws RangerServiceException {
T ret = null;
if (LOG.isDebugEnabled()) {
LOG.debug("==> callAPI({},{},{})", api, params, request);
LOG.debug("------------------------------------------------------");
}
final ClientResponse clientResponse = responseHandler(api, params, request);
if (responseType != null) {
try {
ret = JsonUtilsV2.readResponse(clientResponse, responseType);
} catch (Exception excp) {
LOG.error("failed to read response: api={}", api, excp);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Response: {}", restClient.toJson(ret));
LOG.debug("------------------------------------------------------");
LOG.debug("<== callAPI({},{},{},{}), result = {}", api, params, request, responseType, ret);
}
}
return ret;
}
private <T> T callAPI(API api, Map<String, String> params, Object request, Class<T> responseType) throws RangerServiceException {
T ret = null;
if (LOG.isDebugEnabled()) {
LOG.debug("==> callAPI({},{},{})", api, params, request);
LOG.debug("------------------------------------------------------");
}
final ClientResponse clientResponse = responseHandler(api, params, request);
if (responseType != null) {
try {
ret = JsonUtilsV2.readResponse(clientResponse, responseType);
} catch (Exception excp) {
throw new RangerServiceException(api, clientResponse);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Response: {}", restClient.toJson(ret));
LOG.debug("------------------------------------------------------");
LOG.debug("<== callAPI({},{},{},{}), result = {}", api, params, request, responseType, ret);
}
}
return ret;
}
public static class API {
private static final Logger LOG = LoggerFactory.getLogger(API.class);
private final String path;
private final String method;
private final Response.Status expectedStatus;
private final String consumes;
private final String produces;
public API(String path, String method, Response.Status expectedStatus) {
this(path, method, expectedStatus, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON);
}
public API(String path, String method, Response.Status expectedStatus, String consumes, String produces) {
this.path = path;
this.method = method;
this.expectedStatus = expectedStatus;
this.consumes = consumes;
this.produces = produces;
}
public String getPath() {
return path;
}
public String getMethod() {
return method;
}
public Response.Status getExpectedStatus() {
return expectedStatus;
}
public String getConsumes() {
return consumes;
}
public String getProduces() {
return produces;
}
public String getNormalizedPath() {
// This method used to return Paths.get(path).normalize().toString(), but
// the use of Paths.get(path) on Windows produces a path with Windows
// path separators (i.e. back-slashes) which is not valid for a URI
// and will result in an HTTP 404 status code.
String ret = null;
try {
URI uri = new URI(path);
URI normalizedUri = uri.normalize();
ret = normalizedUri.toString();
} catch (Exception e) {
LOG.error("getNormalizedPath() caught exception for path={}", path, e);
ret = null;
}
return ret;
}
public API applyUrlFormat(Object... params) throws RangerServiceException {
try {
return new API(String.format(path, params), method, expectedStatus, consumes, produces);
} catch (IllegalFormatException e) {
LOG.error("Arguments not formatted properly");
throw new RangerServiceException(e);
}
}
}
}
|
hibernate/hibernate-search | 34,240 | integrationtest/mapper/orm/src/test/java/org/hibernate/search/integrationtest/mapper/orm/automaticindexing/association/bytype/onetoone/ownedbycontained/AutomaticIndexingOneToOneOwnedByContainedLazyOnContainingSideIT.java | /*
* SPDX-License-Identifier: Apache-2.0
* Copyright Red Hat Inc. and Hibernate Authors
*/
package org.hibernate.search.integrationtest.mapper.orm.automaticindexing.association.bytype.onetoone.ownedbycontained;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import jakarta.persistence.Basic;
import jakarta.persistence.CollectionTable;
import jakarta.persistence.Column;
import jakarta.persistence.ElementCollection;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToOne;
import jakarta.persistence.OrderColumn;
import jakarta.persistence.Transient;
import org.hibernate.annotations.LazyGroup;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.search.integrationtest.mapper.orm.automaticindexing.association.bytype.AbstractAutomaticIndexingSingleValuedAssociationBaseIT;
import org.hibernate.search.integrationtest.mapper.orm.automaticindexing.association.bytype.ContainerPrimitives;
import org.hibernate.search.integrationtest.mapper.orm.automaticindexing.association.bytype.accessor.MultiValuedPropertyAccessor;
import org.hibernate.search.integrationtest.mapper.orm.automaticindexing.association.bytype.accessor.PropertyAccessor;
import org.hibernate.search.mapper.pojo.automaticindexing.ReindexOnUpdate;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.AssociationInverseSide;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.GenericField;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.IndexedEmbedded;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.IndexingDependency;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.ObjectPath;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.PropertyValue;
import org.hibernate.search.util.impl.integrationtest.mapper.orm.OrmSetupHelper;
import org.hibernate.search.util.impl.test.annotation.TestForIssue;
import org.hibernate.testing.bytecode.enhancement.EnhancementOptions;
import org.hibernate.testing.bytecode.enhancement.extension.BytecodeEnhanced;
import org.junit.jupiter.api.Test;
/**
* Test automatic indexing caused by single-valued association updates
* or by updates of associated (contained) entities,
* with a {@code @OneToOne} association owned by the contained side,
* and with lazy associations on the containing side.
*/
@BytecodeEnhanced // So that we can have lazy *ToOne associations
@EnhancementOptions(lazyLoading = true)
@TestForIssue(jiraKey = "HSEARCH-4305")
class AutomaticIndexingOneToOneOwnedByContainedLazyOnContainingSideIT
extends AbstractAutomaticIndexingSingleValuedAssociationBaseIT<
AutomaticIndexingOneToOneOwnedByContainedLazyOnContainingSideIT.IndexedEntity,
AutomaticIndexingOneToOneOwnedByContainedLazyOnContainingSideIT.ContainingEntity,
AutomaticIndexingOneToOneOwnedByContainedLazyOnContainingSideIT.ContainingEmbeddable,
AutomaticIndexingOneToOneOwnedByContainedLazyOnContainingSideIT.ContainedEntity,
AutomaticIndexingOneToOneOwnedByContainedLazyOnContainingSideIT.ContainedEmbeddable> {
public AutomaticIndexingOneToOneOwnedByContainedLazyOnContainingSideIT() {
super( IndexedEntity.PRIMITIVES, ContainingEntity.PRIMITIVES, ContainingEmbeddable.PRIMITIVES,
ContainedEntity.PRIMITIVES, ContainedEmbeddable.PRIMITIVES );
}
@Override
protected boolean isAssociationMultiValuedOnContainedSide() {
return false;
}
@Override
protected boolean isAssociationOwnedByContainedSide() {
return true;
}
@Override
protected boolean isAssociationLazyOnContainingSide() {
return true;
}
@Override
protected OrmSetupHelper.SetupContext additionalSetup(OrmSetupHelper.SetupContext setupContext) {
// Avoid problems with deep chains of eager associations in ORM 6
// See https://github.com/hibernate/hibernate-orm/blob/6.0/migration-guide.adoc#fetch-circularity-determination
// See https://hibernate.zulipchat.com/#narrow/stream/132094-hibernate-orm-dev/topic/lazy.20associations.20with.20ORM.206
setupContext.withProperty( AvailableSettings.MAX_FETCH_DEPTH, 1 );
// Necessary for BytecodeEnhancerRunner, see BytecodeEnhancementIT.setup
setupContext.withTcclLookupPrecedenceBefore();
return setupContext;
}
@Test
void testBytecodeEnhancementWorked() {
assertThat( ContainingEntity.class.getDeclaredMethods() )
.extracting( Method::getName )
.anyMatch( name -> name.startsWith( "$$_hibernate_" ) );
}
@Entity(name = "containing")
public static class ContainingEntity {
@Id
private Integer id;
private String nonIndexedField;
@OneToOne
private ContainingEntity parent;
@OneToOne(mappedBy = "parent")
@IndexedEmbedded(includePaths = {
"containedIndexedEmbedded.indexedField",
"containedIndexedEmbedded.indexedElementCollectionField",
"containedIndexedEmbedded.containedDerivedField",
"containedIndexedEmbeddedShallowReindexOnUpdate.indexedField",
"containedIndexedEmbeddedShallowReindexOnUpdate.indexedElementCollectionField",
"containedIndexedEmbeddedShallowReindexOnUpdate.containedDerivedField",
"containedIndexedEmbeddedNoReindexOnUpdate.indexedField",
"containedIndexedEmbeddedNoReindexOnUpdate.indexedElementCollectionField",
"containedIndexedEmbeddedNoReindexOnUpdate.containedDerivedField",
"containedIndexedEmbeddedWithCast.indexedField",
"embeddedAssociations.containedIndexedEmbedded.indexedField",
"embeddedAssociations.containedIndexedEmbedded.indexedElementCollectionField",
"embeddedAssociations.containedIndexedEmbedded.containedDerivedField",
"containedElementCollectionAssociationsIndexedEmbedded.indexedField",
"containedElementCollectionAssociationsIndexedEmbedded.indexedElementCollectionField",
"containedElementCollectionAssociationsIndexedEmbedded.containedDerivedField",
"crossEntityDerivedField"
})
private ContainingEntity child;
@OneToOne(mappedBy = "containingAsIndexedEmbedded", fetch = FetchType.LAZY)
@LazyGroup("containedIndexedEmbedded")
@IndexedEmbedded(includePaths = { "indexedField", "indexedElementCollectionField", "containedDerivedField" })
private ContainedEntity containedIndexedEmbedded;
@OneToOne(mappedBy = "containingAsNonIndexedEmbedded", fetch = FetchType.LAZY)
@LazyGroup("containedNonIndexedEmbedded")
private ContainedEntity containedNonIndexedEmbedded;
@OneToOne(mappedBy = "containingAsIndexedEmbeddedShallowReindexOnUpdate", fetch = FetchType.LAZY)
@LazyGroup("containedIndexedEmbeddedShallowReindexOnUpdate")
@IndexedEmbedded(includePaths = { "indexedField", "indexedElementCollectionField", "containedDerivedField" })
@IndexingDependency(reindexOnUpdate = ReindexOnUpdate.SHALLOW)
private ContainedEntity containedIndexedEmbeddedShallowReindexOnUpdate;
@OneToOne(mappedBy = "containingAsIndexedEmbeddedNoReindexOnUpdate", fetch = FetchType.LAZY)
@LazyGroup("containedIndexedEmbeddedNoReindexOnUpdate")
@IndexedEmbedded(includePaths = { "indexedField", "indexedElementCollectionField", "containedDerivedField" })
@IndexingDependency(reindexOnUpdate = ReindexOnUpdate.NO)
private ContainedEntity containedIndexedEmbeddedNoReindexOnUpdate;
@OneToOne(mappedBy = "containingAsUsedInCrossEntityDerivedProperty", fetch = FetchType.LAZY)
@LazyGroup("containedUsedInCrossEntityDerivedProperty")
private ContainedEntity containedUsedInCrossEntityDerivedProperty;
@OneToOne(mappedBy = "containingAsIndexedEmbeddedWithCast", targetEntity = ContainedEntity.class,
fetch = FetchType.LAZY)
@LazyGroup("containedIndexedEmbeddedWithCast")
@IndexedEmbedded(includePaths = { "indexedField" }, targetType = ContainedEntity.class)
private Object containedIndexedEmbeddedWithCast;
@IndexedEmbedded
@Embedded
private ContainingEmbeddable embeddedAssociations;
/*
* No mappedBy here. The inverse side of associations within an element collection cannot use mappedBy.
* If they do, Hibernate ORM will fail (throw an exception) while attempting to walk down the mappedBy path,
* because it assumes the prefix of that path is an embeddable,
* and in this case it is a List.
* TODO use mappedBy when the above gets fixed in Hibernate ORM
*/
@OneToOne(fetch = FetchType.LAZY)
@LazyGroup("containedElementCollectionAssociationsIndexedEmbedded")
@JoinColumn(name = "CECAssocIdxEmb")
@AssociationInverseSide(inversePath = @ObjectPath({
@PropertyValue(propertyName = "elementCollectionAssociations"),
@PropertyValue(propertyName = "containingAsIndexedEmbedded")
}))
@IndexedEmbedded(includePaths = { "indexedField", "indexedElementCollectionField", "containedDerivedField" })
private ContainedEntity containedElementCollectionAssociationsIndexedEmbedded;
/*
* No mappedBy here. Same reason as just above.
* TODO use mappedBy when the above gets fixed in Hibernate ORM
*/
@OneToOne(fetch = FetchType.LAZY)
@LazyGroup("containedElementCollectionAssociationsNonIndexedEmbedded")
@JoinColumn(name = "CECAssocNonIdxEmb")
@AssociationInverseSide(inversePath = @ObjectPath({
@PropertyValue(propertyName = "elementCollectionAssociations"),
@PropertyValue(propertyName = "containingAsNonIndexedEmbedded")
}))
private ContainedEntity containedElementCollectionAssociationsNonIndexedEmbedded;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNonIndexedField() {
return nonIndexedField;
}
public void setNonIndexedField(String nonIndexedField) {
this.nonIndexedField = nonIndexedField;
}
public ContainingEntity getParent() {
return parent;
}
public void setParent(ContainingEntity parent) {
this.parent = parent;
}
public ContainingEntity getChild() {
return child;
}
public void setChild(ContainingEntity child) {
this.child = child;
}
public ContainedEntity getContainedIndexedEmbedded() {
return containedIndexedEmbedded;
}
public void setContainedIndexedEmbedded(ContainedEntity containedIndexedEmbedded) {
this.containedIndexedEmbedded = containedIndexedEmbedded;
}
public ContainedEntity getContainedNonIndexedEmbedded() {
return containedNonIndexedEmbedded;
}
public void setContainedNonIndexedEmbedded(ContainedEntity containedNonIndexedEmbedded) {
this.containedNonIndexedEmbedded = containedNonIndexedEmbedded;
}
public ContainedEntity getContainedIndexedEmbeddedShallowReindexOnUpdate() {
return containedIndexedEmbeddedShallowReindexOnUpdate;
}
public void setContainedIndexedEmbeddedShallowReindexOnUpdate(
ContainedEntity containedIndexedEmbeddedShallowReindexOnUpdate) {
this.containedIndexedEmbeddedShallowReindexOnUpdate = containedIndexedEmbeddedShallowReindexOnUpdate;
}
public ContainedEntity getContainedIndexedEmbeddedNoReindexOnUpdate() {
return containedIndexedEmbeddedNoReindexOnUpdate;
}
public void setContainedIndexedEmbeddedNoReindexOnUpdate(
ContainedEntity containedIndexedEmbeddedNoReindexOnUpdate) {
this.containedIndexedEmbeddedNoReindexOnUpdate = containedIndexedEmbeddedNoReindexOnUpdate;
}
public ContainedEntity getContainedUsedInCrossEntityDerivedProperty() {
return containedUsedInCrossEntityDerivedProperty;
}
public void setContainedUsedInCrossEntityDerivedProperty(
ContainedEntity containedUsedInCrossEntityDerivedProperty) {
this.containedUsedInCrossEntityDerivedProperty = containedUsedInCrossEntityDerivedProperty;
}
public Object getContainedIndexedEmbeddedWithCast() {
return containedIndexedEmbeddedWithCast;
}
public void setContainedIndexedEmbeddedWithCast(Object containedIndexedEmbeddedWithCast) {
this.containedIndexedEmbeddedWithCast = containedIndexedEmbeddedWithCast;
}
public ContainingEmbeddable getEmbeddedAssociations() {
return embeddedAssociations;
}
public void setEmbeddedAssociations(ContainingEmbeddable embeddedAssociations) {
this.embeddedAssociations = embeddedAssociations;
}
public ContainedEntity getContainedElementCollectionAssociationsIndexedEmbedded() {
return containedElementCollectionAssociationsIndexedEmbedded;
}
public void setContainedElementCollectionAssociationsIndexedEmbedded(
ContainedEntity containedElementCollectionAssociationsIndexedEmbedded) {
this.containedElementCollectionAssociationsIndexedEmbedded = containedElementCollectionAssociationsIndexedEmbedded;
}
public ContainedEntity getContainedElementCollectionAssociationsNonIndexedEmbedded() {
return containedElementCollectionAssociationsNonIndexedEmbedded;
}
public void setContainedElementCollectionAssociationsNonIndexedEmbedded(
ContainedEntity containedElementCollectionAssociationsNonIndexedEmbedded) {
this.containedElementCollectionAssociationsNonIndexedEmbedded =
containedElementCollectionAssociationsNonIndexedEmbedded;
}
@Transient
@GenericField
@IndexingDependency(derivedFrom = {
@ObjectPath({
@PropertyValue(propertyName = "containedUsedInCrossEntityDerivedProperty"),
@PropertyValue(propertyName = "fieldUsedInCrossEntityDerivedField1")
}),
@ObjectPath({
@PropertyValue(propertyName = "containedUsedInCrossEntityDerivedProperty"),
@PropertyValue(propertyName = "fieldUsedInCrossEntityDerivedField2")
})
})
public Optional<String> getCrossEntityDerivedField() {
return containedUsedInCrossEntityDerivedProperty == null
? Optional.empty()
: computeDerived( Stream.of(
containedUsedInCrossEntityDerivedProperty.getFieldUsedInCrossEntityDerivedField1(),
containedUsedInCrossEntityDerivedProperty.getFieldUsedInCrossEntityDerivedField2()
) );
}
static final ContainingEntityPrimitives<ContainingEntity, ContainingEmbeddable, ContainedEntity> PRIMITIVES =
new ContainingEntityPrimitives<ContainingEntity, ContainingEmbeddable, ContainedEntity>() {
@Override
public Class<ContainingEntity> entityClass() {
return ContainingEntity.class;
}
@Override
public ContainingEntity newInstance(int id) {
ContainingEntity entity = new ContainingEntity();
entity.setId( id );
return entity;
}
@Override
public PropertyAccessor<ContainingEntity, ContainingEntity> child() {
return PropertyAccessor.create( ContainingEntity::setChild );
}
@Override
public PropertyAccessor<ContainingEntity, ContainingEntity> parent() {
return PropertyAccessor.create( ContainingEntity::setParent );
}
@Override
public PropertyAccessor<ContainingEntity, ContainedEntity> containedIndexedEmbedded() {
return PropertyAccessor.create( ContainingEntity::setContainedIndexedEmbedded,
ContainingEntity::getContainedIndexedEmbedded );
}
@Override
public PropertyAccessor<ContainingEntity, ContainedEntity> containedNonIndexedEmbedded() {
return PropertyAccessor.create( ContainingEntity::setContainedNonIndexedEmbedded,
ContainingEntity::getContainedNonIndexedEmbedded );
}
@Override
public PropertyAccessor<ContainingEntity,
ContainedEntity> containedIndexedEmbeddedShallowReindexOnUpdate() {
return PropertyAccessor.create( ContainingEntity::setContainedIndexedEmbeddedShallowReindexOnUpdate,
ContainingEntity::getContainedIndexedEmbeddedShallowReindexOnUpdate );
}
@Override
public PropertyAccessor<ContainingEntity, ContainedEntity> containedIndexedEmbeddedNoReindexOnUpdate() {
return PropertyAccessor.create( ContainingEntity::setContainedIndexedEmbeddedNoReindexOnUpdate,
ContainingEntity::getContainedIndexedEmbeddedNoReindexOnUpdate );
}
@Override
public PropertyAccessor<ContainingEntity, ContainedEntity> containedUsedInCrossEntityDerivedProperty() {
return PropertyAccessor.create( ContainingEntity::setContainedUsedInCrossEntityDerivedProperty,
ContainingEntity::getContainedUsedInCrossEntityDerivedProperty );
}
@Override
public PropertyAccessor<ContainingEntity, ContainedEntity> containedIndexedEmbeddedWithCast() {
return PropertyAccessor.create( ContainingEntity::setContainedIndexedEmbeddedWithCast );
}
@Override
public PropertyAccessor<ContainingEntity, ContainingEmbeddable> embeddedAssociations() {
return PropertyAccessor.create( ContainingEntity::setEmbeddedAssociations,
ContainingEntity::getEmbeddedAssociations );
}
@Override
public PropertyAccessor<ContainingEntity,
ContainedEntity> containedElementCollectionAssociationsIndexedEmbedded() {
return PropertyAccessor.create(
ContainingEntity::setContainedElementCollectionAssociationsIndexedEmbedded,
ContainingEntity::getContainedElementCollectionAssociationsIndexedEmbedded );
}
@Override
public PropertyAccessor<ContainingEntity,
ContainedEntity> containedElementCollectionAssociationsNonIndexedEmbedded() {
return PropertyAccessor.create(
ContainingEntity::setContainedElementCollectionAssociationsNonIndexedEmbedded,
ContainingEntity::getContainedElementCollectionAssociationsNonIndexedEmbedded );
}
@Override
public PropertyAccessor<ContainingEntity, String> nonIndexedField() {
return PropertyAccessor.create( ContainingEntity::setNonIndexedField );
}
};
}
public static class ContainingEmbeddable {
@OneToOne(mappedBy = "embeddedAssociations.containingAsIndexedEmbedded", fetch = FetchType.LAZY)
@LazyGroup("embeddable_containedIndexedEmbedded")
@IndexedEmbedded(includePaths = { "indexedField", "indexedElementCollectionField", "containedDerivedField" },
name = "containedIndexedEmbedded")
private ContainedEntity containedIndexedEmbedded;
@OneToOne(mappedBy = "embeddedAssociations.containingAsNonIndexedEmbedded", fetch = FetchType.LAZY)
@LazyGroup("embeddable_containedNonIndexedEmbedded")
private ContainedEntity containedNonIndexedEmbedded;
public ContainedEntity getContainedIndexedEmbedded() {
return containedIndexedEmbedded;
}
public void setContainedIndexedEmbedded(ContainedEntity containedIndexedEmbedded) {
this.containedIndexedEmbedded = containedIndexedEmbedded;
}
public ContainedEntity getContainedNonIndexedEmbedded() {
return containedNonIndexedEmbedded;
}
public void setContainedNonIndexedEmbedded(ContainedEntity containedNonIndexedEmbedded) {
this.containedNonIndexedEmbedded = containedNonIndexedEmbedded;
}
static final ContainingEmbeddablePrimitives<ContainingEmbeddable, ContainedEntity> PRIMITIVES =
new ContainingEmbeddablePrimitives<ContainingEmbeddable, ContainedEntity>() {
@Override
public ContainingEmbeddable newInstance() {
return new ContainingEmbeddable();
}
@Override
public PropertyAccessor<ContainingEmbeddable, ContainedEntity> containedIndexedEmbedded() {
return PropertyAccessor.create( ContainingEmbeddable::setContainedIndexedEmbedded,
ContainingEmbeddable::getContainedIndexedEmbedded
);
}
@Override
public PropertyAccessor<ContainingEmbeddable, ContainedEntity> containedNonIndexedEmbedded() {
return PropertyAccessor.create( ContainingEmbeddable::setContainedNonIndexedEmbedded,
ContainingEmbeddable::getContainedNonIndexedEmbedded
);
}
};
}
@Entity(name = "indexed")
@Indexed(index = IndexedEntity.INDEX)
public static class IndexedEntity extends ContainingEntity {
static final String INDEX = "IndexedEntity";
static final IndexedEntityPrimitives<IndexedEntity> PRIMITIVES = new IndexedEntityPrimitives<IndexedEntity>() {
@Override
public Class<IndexedEntity> entityClass() {
return IndexedEntity.class;
}
@Override
public String indexName() {
return IndexedEntity.INDEX;
}
@Override
public IndexedEntity newInstance(int id) {
IndexedEntity entity = new IndexedEntity();
entity.setId( id );
return entity;
}
};
}
@Entity(name = "contained")
public static class ContainedEntity {
@Id
private Integer id;
@OneToOne
@JoinColumn(name = "CIndexedEmbedded")
private ContainingEntity containingAsIndexedEmbedded;
@OneToOne
@JoinColumn(name = "CNonIndexedEmbedded")
private ContainingEntity containingAsNonIndexedEmbedded;
@OneToOne
@JoinColumn(name = "CIndexedEmbeddedSROU")
private ContainingEntity containingAsIndexedEmbeddedShallowReindexOnUpdate;
@OneToOne
@JoinColumn(name = "CIndexedEmbeddedNROU")
private ContainingEntity containingAsIndexedEmbeddedNoReindexOnUpdate;
@OneToOne
@JoinColumn(name = "CCrossEntityDerived")
private ContainingEntity containingAsUsedInCrossEntityDerivedProperty;
@OneToOne(targetEntity = ContainingEntity.class)
@JoinColumn(name = "CIndexedEmbeddedCast")
private Object containingAsIndexedEmbeddedWithCast;
@Embedded
private ContainedEmbeddable embeddedAssociations;
@ElementCollection
@Embedded
@OrderColumn(name = "idx")
@CollectionTable(name = "c_ECAssoc")
private List<ContainedEmbeddable> elementCollectionAssociations = new ArrayList<>();
@Basic
@GenericField
private String indexedField;
@ElementCollection
@OrderColumn(name = "idx")
@CollectionTable(name = "indexedECF")
@GenericField
private List<String> indexedElementCollectionField = new ArrayList<>();
@Basic
@GenericField
// Keep this annotation, it should be ignored because the field is not included in the @IndexedEmbedded
private String nonIndexedField;
@ElementCollection
@OrderColumn(name = "idx")
@CollectionTable(name = "nonIndexedECF")
@Column(name = "nonIndexedECF")
@GenericField
// Keep this annotation, it should be ignored because the field is not included in the @IndexedEmbedded
private List<String> nonIndexedElementCollectionField = new ArrayList<>();
@Basic // Do not annotate with @GenericField, this would make the test pointless
@Column(name = "FUIContainedDF1")
private String fieldUsedInContainedDerivedField1;
@Basic // Do not annotate with @GenericField, this would make the test pointless
@Column(name = "FUIContainedDF2")
private String fieldUsedInContainedDerivedField2;
@Basic // Do not annotate with @GenericField, this would make the test pointless
@Column(name = "FUICrossEntityDF1")
private String fieldUsedInCrossEntityDerivedField1;
@Basic // Do not annotate with @GenericField, this would make the test pointless
@Column(name = "FUICrossEntityDF2")
private String fieldUsedInCrossEntityDerivedField2;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public ContainingEntity getContainingAsIndexedEmbedded() {
return containingAsIndexedEmbedded;
}
public void setContainingAsIndexedEmbedded(ContainingEntity containingAsIndexedEmbedded) {
this.containingAsIndexedEmbedded = containingAsIndexedEmbedded;
}
public ContainingEntity getContainingAsNonIndexedEmbedded() {
return containingAsNonIndexedEmbedded;
}
public void setContainingAsNonIndexedEmbedded(ContainingEntity containingAsNonIndexedEmbedded) {
this.containingAsNonIndexedEmbedded = containingAsNonIndexedEmbedded;
}
public ContainingEntity getContainingAsIndexedEmbeddedShallowReindexOnUpdate() {
return containingAsIndexedEmbeddedShallowReindexOnUpdate;
}
public void setContainingAsIndexedEmbeddedShallowReindexOnUpdate(
ContainingEntity containingAsIndexedEmbeddedShallowReindexOnUpdate) {
this.containingAsIndexedEmbeddedShallowReindexOnUpdate = containingAsIndexedEmbeddedShallowReindexOnUpdate;
}
public ContainingEntity getContainingAsIndexedEmbeddedNoReindexOnUpdate() {
return containingAsIndexedEmbeddedNoReindexOnUpdate;
}
public void setContainingAsIndexedEmbeddedNoReindexOnUpdate(
ContainingEntity containingAsIndexedEmbeddedNoReindexOnUpdate) {
this.containingAsIndexedEmbeddedNoReindexOnUpdate = containingAsIndexedEmbeddedNoReindexOnUpdate;
}
public ContainingEntity getContainingAsUsedInCrossEntityDerivedProperty() {
return containingAsUsedInCrossEntityDerivedProperty;
}
public void setContainingAsUsedInCrossEntityDerivedProperty(
ContainingEntity containingAsUsedInCrossEntityDerivedProperty) {
this.containingAsUsedInCrossEntityDerivedProperty = containingAsUsedInCrossEntityDerivedProperty;
}
public Object getContainingAsIndexedEmbeddedWithCast() {
return containingAsIndexedEmbeddedWithCast;
}
public void setContainingAsIndexedEmbeddedWithCast(Object containingAsIndexedEmbeddedWithCast) {
this.containingAsIndexedEmbeddedWithCast = containingAsIndexedEmbeddedWithCast;
}
public ContainedEmbeddable getEmbeddedAssociations() {
return embeddedAssociations;
}
public void setEmbeddedAssociations(ContainedEmbeddable embeddedAssociations) {
this.embeddedAssociations = embeddedAssociations;
}
public List<ContainedEmbeddable> getElementCollectionAssociations() {
return elementCollectionAssociations;
}
public String getIndexedField() {
return indexedField;
}
public void setIndexedField(String indexedField) {
this.indexedField = indexedField;
}
public List<String> getIndexedElementCollectionField() {
return indexedElementCollectionField;
}
public void setIndexedElementCollectionField(List<String> indexedElementCollectionField) {
this.indexedElementCollectionField = indexedElementCollectionField;
}
public String getNonIndexedField() {
return nonIndexedField;
}
public void setNonIndexedField(String nonIndexedField) {
this.nonIndexedField = nonIndexedField;
}
public List<String> getNonIndexedElementCollectionField() {
return nonIndexedElementCollectionField;
}
public void setNonIndexedElementCollectionField(List<String> nonIndexedElementCollectionField) {
this.nonIndexedElementCollectionField = nonIndexedElementCollectionField;
}
public String getFieldUsedInContainedDerivedField1() {
return fieldUsedInContainedDerivedField1;
}
public void setFieldUsedInContainedDerivedField1(String fieldUsedInContainedDerivedField1) {
this.fieldUsedInContainedDerivedField1 = fieldUsedInContainedDerivedField1;
}
public String getFieldUsedInContainedDerivedField2() {
return fieldUsedInContainedDerivedField2;
}
public void setFieldUsedInContainedDerivedField2(String fieldUsedInContainedDerivedField2) {
this.fieldUsedInContainedDerivedField2 = fieldUsedInContainedDerivedField2;
}
public String getFieldUsedInCrossEntityDerivedField1() {
return fieldUsedInCrossEntityDerivedField1;
}
public void setFieldUsedInCrossEntityDerivedField1(String fieldUsedInCrossEntityDerivedField1) {
this.fieldUsedInCrossEntityDerivedField1 = fieldUsedInCrossEntityDerivedField1;
}
public String getFieldUsedInCrossEntityDerivedField2() {
return fieldUsedInCrossEntityDerivedField2;
}
public void setFieldUsedInCrossEntityDerivedField2(String fieldUsedInCrossEntityDerivedField2) {
this.fieldUsedInCrossEntityDerivedField2 = fieldUsedInCrossEntityDerivedField2;
}
@Transient
@GenericField
@IndexingDependency(derivedFrom = {
@ObjectPath(@PropertyValue(propertyName = "fieldUsedInContainedDerivedField1")),
@ObjectPath(@PropertyValue(propertyName = "fieldUsedInContainedDerivedField2"))
})
public Optional<String> getContainedDerivedField() {
return computeDerived( Stream.of( fieldUsedInContainedDerivedField1, fieldUsedInContainedDerivedField2 ) );
}
static ContainedEntityPrimitives<ContainedEntity, ContainedEmbeddable, ContainingEntity> PRIMITIVES =
new ContainedEntityPrimitives<ContainedEntity, ContainedEmbeddable, ContainingEntity>() {
@Override
public Class<ContainedEntity> entityClass() {
return ContainedEntity.class;
}
@Override
public ContainedEntity newInstance(int id) {
ContainedEntity entity = new ContainedEntity();
entity.setId( id );
return entity;
}
@Override
public PropertyAccessor<ContainedEntity, ContainingEntity> containingAsIndexedEmbedded() {
return PropertyAccessor.create( ContainedEntity::setContainingAsIndexedEmbedded,
ContainedEntity::getContainingAsIndexedEmbedded );
}
@Override
public PropertyAccessor<ContainedEntity, ContainingEntity> containingAsNonIndexedEmbedded() {
return PropertyAccessor.create( ContainedEntity::setContainingAsNonIndexedEmbedded,
ContainedEntity::getContainingAsNonIndexedEmbedded );
}
@Override
public PropertyAccessor<ContainedEntity,
ContainingEntity> containingAsIndexedEmbeddedShallowReindexOnUpdate() {
return PropertyAccessor.create( ContainedEntity::setContainingAsIndexedEmbeddedShallowReindexOnUpdate,
ContainedEntity::getContainingAsIndexedEmbeddedShallowReindexOnUpdate );
}
@Override
public PropertyAccessor<ContainedEntity, ContainingEntity> containingAsIndexedEmbeddedNoReindexOnUpdate() {
return PropertyAccessor.create( ContainedEntity::setContainingAsIndexedEmbeddedNoReindexOnUpdate,
ContainedEntity::getContainingAsIndexedEmbeddedNoReindexOnUpdate );
}
@Override
public PropertyAccessor<ContainedEntity, ContainingEntity> containingAsUsedInCrossEntityDerivedProperty() {
return PropertyAccessor.create( ContainedEntity::setContainingAsUsedInCrossEntityDerivedProperty,
ContainedEntity::getContainingAsUsedInCrossEntityDerivedProperty );
}
@Override
public PropertyAccessor<ContainedEntity, ContainingEntity> containingAsIndexedEmbeddedWithCast() {
return PropertyAccessor.create( ContainedEntity::setContainingAsIndexedEmbeddedWithCast );
}
@Override
public PropertyAccessor<ContainedEntity, ContainedEmbeddable> embeddedAssociations() {
return PropertyAccessor.create( ContainedEntity::setEmbeddedAssociations,
ContainedEntity::getEmbeddedAssociations );
}
@Override
public MultiValuedPropertyAccessor<ContainedEntity,
ContainedEmbeddable,
List<ContainedEmbeddable>> elementCollectionAssociations() {
return MultiValuedPropertyAccessor.create( ContainerPrimitives.collection(),
ContainedEntity::getElementCollectionAssociations );
}
@Override
public PropertyAccessor<ContainedEntity, String> indexedField() {
return PropertyAccessor.create( ContainedEntity::setIndexedField );
}
@Override
public PropertyAccessor<ContainedEntity, String> nonIndexedField() {
return PropertyAccessor.create( ContainedEntity::setNonIndexedField );
}
@Override
public MultiValuedPropertyAccessor<ContainedEntity, String, List<String>> indexedElementCollectionField() {
return MultiValuedPropertyAccessor.create( ContainerPrimitives.collection(),
ContainedEntity::getIndexedElementCollectionField,
ContainedEntity::setIndexedElementCollectionField );
}
@Override
public MultiValuedPropertyAccessor<ContainedEntity,
String,
List<String>> nonIndexedElementCollectionField() {
return MultiValuedPropertyAccessor.create( ContainerPrimitives.collection(),
ContainedEntity::getNonIndexedElementCollectionField,
ContainedEntity::setNonIndexedElementCollectionField );
}
@Override
public PropertyAccessor<ContainedEntity, String> fieldUsedInContainedDerivedField1() {
return PropertyAccessor.create( ContainedEntity::setFieldUsedInContainedDerivedField1 );
}
@Override
public PropertyAccessor<ContainedEntity, String> fieldUsedInContainedDerivedField2() {
return PropertyAccessor.create( ContainedEntity::setFieldUsedInContainedDerivedField2 );
}
@Override
public PropertyAccessor<ContainedEntity, String> fieldUsedInCrossEntityDerivedField1() {
return PropertyAccessor.create( ContainedEntity::setFieldUsedInCrossEntityDerivedField1 );
}
@Override
public PropertyAccessor<ContainedEntity, String> fieldUsedInCrossEntityDerivedField2() {
return PropertyAccessor.create( ContainedEntity::setFieldUsedInCrossEntityDerivedField2 );
}
};
}
public static class ContainedEmbeddable {
@OneToOne
@JoinColumn(name = "CEmbIdxEmbedded")
private ContainingEntity containingAsIndexedEmbedded;
@OneToOne
@JoinColumn(name = "CEmbNonIdxEmbedded")
private ContainingEntity containingAsNonIndexedEmbedded;
public ContainingEntity getContainingAsIndexedEmbedded() {
return containingAsIndexedEmbedded;
}
public void setContainingAsIndexedEmbedded(ContainingEntity containingAsIndexedEmbedded) {
this.containingAsIndexedEmbedded = containingAsIndexedEmbedded;
}
public ContainingEntity getContainingAsNonIndexedEmbedded() {
return containingAsNonIndexedEmbedded;
}
public void setContainingAsNonIndexedEmbedded(ContainingEntity containingAsNonIndexedEmbedded) {
this.containingAsNonIndexedEmbedded = containingAsNonIndexedEmbedded;
}
static ContainedEmbeddablePrimitives<ContainedEmbeddable, ContainingEntity> PRIMITIVES =
new ContainedEmbeddablePrimitives<ContainedEmbeddable, ContainingEntity>() {
@Override
public ContainedEmbeddable newInstance() {
return new ContainedEmbeddable();
}
@Override
public PropertyAccessor<ContainedEmbeddable, ContainingEntity> containingAsIndexedEmbedded() {
return PropertyAccessor.create( ContainedEmbeddable::setContainingAsIndexedEmbedded,
ContainedEmbeddable::getContainingAsIndexedEmbedded
);
}
@Override
public PropertyAccessor<ContainedEmbeddable, ContainingEntity> containingAsNonIndexedEmbedded() {
return PropertyAccessor.create( ContainedEmbeddable::setContainingAsNonIndexedEmbedded,
ContainedEmbeddable::getContainingAsNonIndexedEmbedded
);
}
};
}
}
|
googleapis/google-api-java-client-services | 36,687 | clients/google-api-services-cloudtrace/v1/1.31.0/com/google/api/services/cloudtrace/v1/CloudTrace.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.cloudtrace.v1;
/**
* Service definition for CloudTrace (v1).
*
* <p>
* Sends application trace data to Cloud Trace for viewing. Trace data is collected for all App Engine applications by default. Trace data from other applications can be provided using this API. This library is used to interact with the Cloud Trace API directly. If you are looking to instrument your application for Cloud Trace, we recommend using OpenTelemetry.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://cloud.google.com/trace" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link CloudTraceRequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class CloudTrace extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient {
// Note: Leave this static initializer at the top of the file.
static {
com.google.api.client.util.Preconditions.checkState(
com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 &&
(com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 32 ||
(com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION == 31 &&
com.google.api.client.googleapis.GoogleUtils.BUGFIX_VERSION >= 1)),
"You are currently running with version %s of google-api-client. " +
"You need at least version 1.31.1 of google-api-client to run version " +
"1.32.1 of the Cloud Trace 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://cloudtrace.googleapis.com/";
/**
* The default encoded mTLS root URL of the service. This is determined when the library is generated
* and normally should not be changed.
*
* @since 1.31
*/
public static final String DEFAULT_MTLS_ROOT_URL = "https://cloudtrace.mtls.googleapis.com/";
/**
* The default encoded service path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_SERVICE_PATH = "";
/**
* The default encoded batch path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.23
*/
public static final String DEFAULT_BATCH_PATH = "batch";
/**
* The default encoded base URL of the service. This is determined when the library is generated
* and normally should not be changed.
*/
public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH;
/**
* Constructor.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public CloudTrace(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
*/
CloudTrace(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 CloudTrace cloudtrace = new CloudTrace(...);}
* {@code CloudTrace.Projects.List request = cloudtrace.projects().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Projects projects() {
return new Projects();
}
/**
* The "projects" collection of methods.
*/
public class Projects {
/**
* Sends new traces to Cloud Trace or updates existing traces. If the ID of a trace that you send
* matches that of an existing trace, any fields in the existing trace and its spans are overwritten
* by the provided values, and any new fields provided are merged with the existing trace data. If
* the ID does not match, a new trace is created.
*
* Create a request for the method "projects.patchTraces".
*
* This request holds the parameters needed by the cloudtrace server. After setting any optional
* parameters, call the {@link PatchTraces#execute()} method to invoke the remote operation.
*
* @param projectId Required. ID of the Cloud project where the trace data is stored.
* @param content the {@link com.google.api.services.cloudtrace.v1.model.Traces}
* @return the request
*/
public PatchTraces patchTraces(java.lang.String projectId, com.google.api.services.cloudtrace.v1.model.Traces content) throws java.io.IOException {
PatchTraces result = new PatchTraces(projectId, content);
initialize(result);
return result;
}
public class PatchTraces extends CloudTraceRequest<com.google.api.services.cloudtrace.v1.model.Empty> {
private static final String REST_PATH = "v1/projects/{projectId}/traces";
/**
* Sends new traces to Cloud Trace or updates existing traces. If the ID of a trace that you send
* matches that of an existing trace, any fields in the existing trace and its spans are
* overwritten by the provided values, and any new fields provided are merged with the existing
* trace data. If the ID does not match, a new trace is created.
*
* Create a request for the method "projects.patchTraces".
*
* This request holds the parameters needed by the the cloudtrace server. After setting any
* optional parameters, call the {@link PatchTraces#execute()} method to invoke the remote
* operation. <p> {@link
* PatchTraces#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param projectId Required. ID of the Cloud project where the trace data is stored.
* @param content the {@link com.google.api.services.cloudtrace.v1.model.Traces}
* @since 1.13
*/
protected PatchTraces(java.lang.String projectId, com.google.api.services.cloudtrace.v1.model.Traces content) {
super(CloudTrace.this, "PATCH", REST_PATH, content, com.google.api.services.cloudtrace.v1.model.Empty.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
}
@Override
public PatchTraces set$Xgafv(java.lang.String $Xgafv) {
return (PatchTraces) super.set$Xgafv($Xgafv);
}
@Override
public PatchTraces setAccessToken(java.lang.String accessToken) {
return (PatchTraces) super.setAccessToken(accessToken);
}
@Override
public PatchTraces setAlt(java.lang.String alt) {
return (PatchTraces) super.setAlt(alt);
}
@Override
public PatchTraces setCallback(java.lang.String callback) {
return (PatchTraces) super.setCallback(callback);
}
@Override
public PatchTraces setFields(java.lang.String fields) {
return (PatchTraces) super.setFields(fields);
}
@Override
public PatchTraces setKey(java.lang.String key) {
return (PatchTraces) super.setKey(key);
}
@Override
public PatchTraces setOauthToken(java.lang.String oauthToken) {
return (PatchTraces) super.setOauthToken(oauthToken);
}
@Override
public PatchTraces setPrettyPrint(java.lang.Boolean prettyPrint) {
return (PatchTraces) super.setPrettyPrint(prettyPrint);
}
@Override
public PatchTraces setQuotaUser(java.lang.String quotaUser) {
return (PatchTraces) super.setQuotaUser(quotaUser);
}
@Override
public PatchTraces setUploadType(java.lang.String uploadType) {
return (PatchTraces) super.setUploadType(uploadType);
}
@Override
public PatchTraces setUploadProtocol(java.lang.String uploadProtocol) {
return (PatchTraces) super.setUploadProtocol(uploadProtocol);
}
/** Required. ID of the Cloud project where the trace data is stored. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. ID of the Cloud project where the trace data is stored.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** Required. ID of the Cloud project where the trace data is stored. */
public PatchTraces setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
@Override
public PatchTraces set(String parameterName, Object value) {
return (PatchTraces) super.set(parameterName, value);
}
}
/**
* An accessor for creating requests from the Traces collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code CloudTrace cloudtrace = new CloudTrace(...);}
* {@code CloudTrace.Traces.List request = cloudtrace.traces().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Traces traces() {
return new Traces();
}
/**
* The "traces" collection of methods.
*/
public class Traces {
/**
* Gets a single trace by its ID.
*
* Create a request for the method "traces.get".
*
* This request holds the parameters needed by the cloudtrace server. After setting any optional
* parameters, call the {@link Get#execute()} method to invoke the remote operation.
*
* @param projectId Required. ID of the Cloud project where the trace data is stored.
* @param traceId Required. ID of the trace to return.
* @return the request
*/
public Get get(java.lang.String projectId, java.lang.String traceId) throws java.io.IOException {
Get result = new Get(projectId, traceId);
initialize(result);
return result;
}
public class Get extends CloudTraceRequest<com.google.api.services.cloudtrace.v1.model.Trace> {
private static final String REST_PATH = "v1/projects/{projectId}/traces/{traceId}";
/**
* Gets a single trace by its ID.
*
* Create a request for the method "traces.get".
*
* This request holds the parameters needed by the the cloudtrace 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 projectId Required. ID of the Cloud project where the trace data is stored.
* @param traceId Required. ID of the trace to return.
* @since 1.13
*/
protected Get(java.lang.String projectId, java.lang.String traceId) {
super(CloudTrace.this, "GET", REST_PATH, null, com.google.api.services.cloudtrace.v1.model.Trace.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
this.traceId = com.google.api.client.util.Preconditions.checkNotNull(traceId, "Required parameter traceId must be specified.");
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public Get set$Xgafv(java.lang.String $Xgafv) {
return (Get) super.set$Xgafv($Xgafv);
}
@Override
public Get setAccessToken(java.lang.String accessToken) {
return (Get) super.setAccessToken(accessToken);
}
@Override
public Get setAlt(java.lang.String alt) {
return (Get) super.setAlt(alt);
}
@Override
public Get setCallback(java.lang.String callback) {
return (Get) super.setCallback(callback);
}
@Override
public Get setFields(java.lang.String fields) {
return (Get) super.setFields(fields);
}
@Override
public Get setKey(java.lang.String key) {
return (Get) super.setKey(key);
}
@Override
public Get setOauthToken(java.lang.String oauthToken) {
return (Get) super.setOauthToken(oauthToken);
}
@Override
public Get setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Get) super.setPrettyPrint(prettyPrint);
}
@Override
public Get setQuotaUser(java.lang.String quotaUser) {
return (Get) super.setQuotaUser(quotaUser);
}
@Override
public Get setUploadType(java.lang.String uploadType) {
return (Get) super.setUploadType(uploadType);
}
@Override
public Get setUploadProtocol(java.lang.String uploadProtocol) {
return (Get) super.setUploadProtocol(uploadProtocol);
}
/** Required. ID of the Cloud project where the trace data is stored. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. ID of the Cloud project where the trace data is stored.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** Required. ID of the Cloud project where the trace data is stored. */
public Get setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/** Required. ID of the trace to return. */
@com.google.api.client.util.Key
private java.lang.String traceId;
/** Required. ID of the trace to return.
*/
public java.lang.String getTraceId() {
return traceId;
}
/** Required. ID of the trace to return. */
public Get setTraceId(java.lang.String traceId) {
this.traceId = traceId;
return this;
}
@Override
public Get set(String parameterName, Object value) {
return (Get) super.set(parameterName, value);
}
}
/**
* Returns a list of traces that match the specified filter conditions.
*
* Create a request for the method "traces.list".
*
* This request holds the parameters needed by the cloudtrace server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @param projectId Required. ID of the Cloud project where the trace data is stored.
* @return the request
*/
public List list(java.lang.String projectId) throws java.io.IOException {
List result = new List(projectId);
initialize(result);
return result;
}
public class List extends CloudTraceRequest<com.google.api.services.cloudtrace.v1.model.ListTracesResponse> {
private static final String REST_PATH = "v1/projects/{projectId}/traces";
/**
* Returns a list of traces that match the specified filter conditions.
*
* Create a request for the method "traces.list".
*
* This request holds the parameters needed by the the cloudtrace 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 projectId Required. ID of the Cloud project where the trace data is stored.
* @since 1.13
*/
protected List(java.lang.String projectId) {
super(CloudTrace.this, "GET", REST_PATH, null, com.google.api.services.cloudtrace.v1.model.ListTracesResponse.class);
this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified.");
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public List set$Xgafv(java.lang.String $Xgafv) {
return (List) super.set$Xgafv($Xgafv);
}
@Override
public List setAccessToken(java.lang.String accessToken) {
return (List) super.setAccessToken(accessToken);
}
@Override
public List setAlt(java.lang.String alt) {
return (List) super.setAlt(alt);
}
@Override
public List 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);
}
/** Required. ID of the Cloud project where the trace data is stored. */
@com.google.api.client.util.Key
private java.lang.String projectId;
/** Required. ID of the Cloud project where the trace data is stored.
*/
public java.lang.String getProjectId() {
return projectId;
}
/** Required. ID of the Cloud project where the trace data is stored. */
public List setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* End of the time interval (inclusive) during which the trace data was collected from the
* application.
*/
@com.google.api.client.util.Key
private String endTime;
/** End of the time interval (inclusive) during which the trace data was collected from the
application.
*/
public String getEndTime() {
return endTime;
}
/**
* End of the time interval (inclusive) during which the trace data was collected from the
* application.
*/
public List setEndTime(String endTime) {
this.endTime = endTime;
return this;
}
/**
* Optional. A filter against labels for the request. By default, searches use prefix
* matching. To specify exact match, prepend a plus symbol (`+`) to the search term.
* Multiple terms are ANDed. Syntax: * `root:NAME_PREFIX` or `NAME_PREFIX`: Return traces
* where any root span starts with `NAME_PREFIX`. * `+root:NAME` or `+NAME`: Return traces
* where any root span's name is exactly `NAME`. * `span:NAME_PREFIX`: Return traces where
* any span starts with `NAME_PREFIX`. * `+span:NAME`: Return traces where any span's name
* is exactly `NAME`. * `latency:DURATION`: Return traces whose overall latency is greater
* or equal to than `DURATION`. Accepted units are nanoseconds (`ns`), milliseconds (`ms`),
* and seconds (`s`). Default is `ms`. For example, `latency:24ms` returns traces whose
* overall latency is greater than or equal to 24 milliseconds. * `label:LABEL_KEY`: Return
* all traces containing the specified label key (exact match, case-sensitive) regardless of
* the key:value pair's value (including empty values). * `LABEL_KEY:VALUE_PREFIX`: Return
* all traces containing the specified label key (exact match, case-sensitive) whose value
* starts with `VALUE_PREFIX`. Both a key and a value must be specified. *
* `+LABEL_KEY:VALUE`: Return all traces containing a key:value pair exactly matching the
* specified text. Both a key and a value must be specified. * `method:VALUE`: Equivalent to
* `/http/method:VALUE`. * `url:VALUE`: Equivalent to `/http/url:VALUE`.
*/
@com.google.api.client.util.Key
private java.lang.String filter;
/** Optional. A filter against labels for the request. By default, searches use prefix matching. To
specify exact match, prepend a plus symbol (`+`) to the search term. Multiple terms are ANDed.
Syntax: * `root:NAME_PREFIX` or `NAME_PREFIX`: Return traces where any root span starts with
`NAME_PREFIX`. * `+root:NAME` or `+NAME`: Return traces where any root span's name is exactly
`NAME`. * `span:NAME_PREFIX`: Return traces where any span starts with `NAME_PREFIX`. *
`+span:NAME`: Return traces where any span's name is exactly `NAME`. * `latency:DURATION`: Return
traces whose overall latency is greater or equal to than `DURATION`. Accepted units are nanoseconds
(`ns`), milliseconds (`ms`), and seconds (`s`). Default is `ms`. For example, `latency:24ms`
returns traces whose overall latency is greater than or equal to 24 milliseconds. *
`label:LABEL_KEY`: Return all traces containing the specified label key (exact match, case-
sensitive) regardless of the key:value pair's value (including empty values). *
`LABEL_KEY:VALUE_PREFIX`: Return all traces containing the specified label key (exact match, case-
sensitive) whose value starts with `VALUE_PREFIX`. Both a key and a value must be specified. *
`+LABEL_KEY:VALUE`: Return all traces containing a key:value pair exactly matching the specified
text. Both a key and a value must be specified. * `method:VALUE`: Equivalent to
`/http/method:VALUE`. * `url:VALUE`: Equivalent to `/http/url:VALUE`.
*/
public java.lang.String getFilter() {
return filter;
}
/**
* Optional. A filter against labels for the request. By default, searches use prefix
* matching. To specify exact match, prepend a plus symbol (`+`) to the search term.
* Multiple terms are ANDed. Syntax: * `root:NAME_PREFIX` or `NAME_PREFIX`: Return traces
* where any root span starts with `NAME_PREFIX`. * `+root:NAME` or `+NAME`: Return traces
* where any root span's name is exactly `NAME`. * `span:NAME_PREFIX`: Return traces where
* any span starts with `NAME_PREFIX`. * `+span:NAME`: Return traces where any span's name
* is exactly `NAME`. * `latency:DURATION`: Return traces whose overall latency is greater
* or equal to than `DURATION`. Accepted units are nanoseconds (`ns`), milliseconds (`ms`),
* and seconds (`s`). Default is `ms`. For example, `latency:24ms` returns traces whose
* overall latency is greater than or equal to 24 milliseconds. * `label:LABEL_KEY`: Return
* all traces containing the specified label key (exact match, case-sensitive) regardless of
* the key:value pair's value (including empty values). * `LABEL_KEY:VALUE_PREFIX`: Return
* all traces containing the specified label key (exact match, case-sensitive) whose value
* starts with `VALUE_PREFIX`. Both a key and a value must be specified. *
* `+LABEL_KEY:VALUE`: Return all traces containing a key:value pair exactly matching the
* specified text. Both a key and a value must be specified. * `method:VALUE`: Equivalent to
* `/http/method:VALUE`. * `url:VALUE`: Equivalent to `/http/url:VALUE`.
*/
public List setFilter(java.lang.String filter) {
this.filter = filter;
return this;
}
/**
* Optional. Field used to sort the returned traces. Can be one of the following: *
* `trace_id` * `name` (`name` field of root span in the trace) * `duration` (difference
* between `end_time` and `start_time` fields of the root span) * `start` (`start_time`
* field of the root span) Descending order can be specified by appending `desc` to the sort
* field (for example, `name desc`). Only one sort field is permitted.
*/
@com.google.api.client.util.Key
private java.lang.String orderBy;
/** Optional. Field used to sort the returned traces. Can be one of the following: * `trace_id` *
`name` (`name` field of root span in the trace) * `duration` (difference between `end_time` and
`start_time` fields of the root span) * `start` (`start_time` field of the root span) Descending
order can be specified by appending `desc` to the sort field (for example, `name desc`). Only one
sort field is permitted.
*/
public java.lang.String getOrderBy() {
return orderBy;
}
/**
* Optional. Field used to sort the returned traces. Can be one of the following: *
* `trace_id` * `name` (`name` field of root span in the trace) * `duration` (difference
* between `end_time` and `start_time` fields of the root span) * `start` (`start_time`
* field of the root span) Descending order can be specified by appending `desc` to the sort
* field (for example, `name desc`). Only one sort field is permitted.
*/
public List setOrderBy(java.lang.String orderBy) {
this.orderBy = orderBy;
return this;
}
/**
* Optional. Maximum number of traces to return. If not specified or <= 0, the
* implementation selects a reasonable value. The implementation may return fewer traces
* than the requested page size.
*/
@com.google.api.client.util.Key
private java.lang.Integer pageSize;
/** Optional. Maximum number of traces to return. If not specified or <= 0, the implementation selects
a reasonable value. The implementation may return fewer traces than the requested page size.
*/
public java.lang.Integer getPageSize() {
return pageSize;
}
/**
* Optional. Maximum number of traces to return. If not specified or <= 0, the
* implementation selects a reasonable value. The implementation may return fewer traces
* than the requested page size.
*/
public List setPageSize(java.lang.Integer pageSize) {
this.pageSize = pageSize;
return this;
}
/**
* Token identifying the page of results to return. If provided, use the value of the
* `next_page_token` field from a previous request.
*/
@com.google.api.client.util.Key
private java.lang.String pageToken;
/** Token identifying the page of results to return. If provided, use the value of the
`next_page_token` field from a previous request.
*/
public java.lang.String getPageToken() {
return pageToken;
}
/**
* Token identifying the page of results to return. If provided, use the value of the
* `next_page_token` field from a previous request.
*/
public List setPageToken(java.lang.String pageToken) {
this.pageToken = pageToken;
return this;
}
/**
* Start of the time interval (inclusive) during which the trace data was collected from the
* application.
*/
@com.google.api.client.util.Key
private String startTime;
/** Start of the time interval (inclusive) during which the trace data was collected from the
application.
*/
public String getStartTime() {
return startTime;
}
/**
* Start of the time interval (inclusive) during which the trace data was collected from the
* application.
*/
public List setStartTime(String startTime) {
this.startTime = startTime;
return this;
}
/** Optional. Type of data returned for traces in the list. Default is `MINIMAL`. */
@com.google.api.client.util.Key
private java.lang.String view;
/** Optional. Type of data returned for traces in the list. Default is `MINIMAL`.
*/
public java.lang.String getView() {
return view;
}
/** Optional. Type of data returned for traces in the list. Default is `MINIMAL`. */
public List setView(java.lang.String view) {
this.view = view;
return this;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
}
}
/**
* Builder for {@link CloudTrace}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.3.0
*/
public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {
private static String chooseEndpoint(com.google.api.client.http.HttpTransport transport) {
// If the GOOGLE_API_USE_MTLS_ENDPOINT environment variable value is "always", use mTLS endpoint.
// If the env variable is "auto", use mTLS endpoint if and only if the transport is mTLS.
// Use the regular endpoint for all other cases.
String useMtlsEndpoint = System.getenv("GOOGLE_API_USE_MTLS_ENDPOINT");
useMtlsEndpoint = useMtlsEndpoint == null ? "auto" : useMtlsEndpoint;
if ("always".equals(useMtlsEndpoint) || ("auto".equals(useMtlsEndpoint) && transport != null && transport.isMtls())) {
return DEFAULT_MTLS_ROOT_URL;
}
return DEFAULT_ROOT_URL;
}
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
super(
transport,
jsonFactory,
Builder.chooseEndpoint(transport),
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
setBatchPath(DEFAULT_BATCH_PATH);
}
/** Builds a new instance of {@link CloudTrace}. */
@Override
public CloudTrace build() {
return new CloudTrace(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 CloudTraceRequestInitializer}.
*
* @since 1.12
*/
public Builder setCloudTraceRequestInitializer(
CloudTraceRequestInitializer cloudtraceRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(cloudtraceRequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
}
}
|
googleapis/google-cloud-java | 36,456 | java-websecurityscanner/proto-google-cloud-websecurityscanner-v1/src/main/java/com/google/cloud/websecurityscanner/v1/ListFindingsResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/websecurityscanner/v1/web_security_scanner.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.websecurityscanner.v1;
/**
*
*
* <pre>
* Response for the `ListFindings` method.
* </pre>
*
* Protobuf type {@code google.cloud.websecurityscanner.v1.ListFindingsResponse}
*/
public final class ListFindingsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.websecurityscanner.v1.ListFindingsResponse)
ListFindingsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListFindingsResponse.newBuilder() to construct.
private ListFindingsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListFindingsResponse() {
findings_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListFindingsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.websecurityscanner.v1.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1_ListFindingsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.websecurityscanner.v1.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1_ListFindingsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.websecurityscanner.v1.ListFindingsResponse.class,
com.google.cloud.websecurityscanner.v1.ListFindingsResponse.Builder.class);
}
public static final int FINDINGS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.websecurityscanner.v1.Finding> findings_;
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.websecurityscanner.v1.Finding> getFindingsList() {
return findings_;
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.websecurityscanner.v1.FindingOrBuilder>
getFindingsOrBuilderList() {
return findings_;
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
@java.lang.Override
public int getFindingsCount() {
return findings_.size();
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
@java.lang.Override
public com.google.cloud.websecurityscanner.v1.Finding getFindings(int index) {
return findings_.get(index);
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
@java.lang.Override
public com.google.cloud.websecurityscanner.v1.FindingOrBuilder getFindingsOrBuilder(int index) {
return findings_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < findings_.size(); i++) {
output.writeMessage(1, findings_.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 < findings_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, findings_.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.websecurityscanner.v1.ListFindingsResponse)) {
return super.equals(obj);
}
com.google.cloud.websecurityscanner.v1.ListFindingsResponse other =
(com.google.cloud.websecurityscanner.v1.ListFindingsResponse) obj;
if (!getFindingsList().equals(other.getFindingsList())) 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 (getFindingsCount() > 0) {
hash = (37 * hash) + FINDINGS_FIELD_NUMBER;
hash = (53 * hash) + getFindingsList().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.websecurityscanner.v1.ListFindingsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.websecurityscanner.v1.ListFindingsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1.ListFindingsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.websecurityscanner.v1.ListFindingsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1.ListFindingsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.websecurityscanner.v1.ListFindingsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1.ListFindingsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.websecurityscanner.v1.ListFindingsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1.ListFindingsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.websecurityscanner.v1.ListFindingsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1.ListFindingsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.websecurityscanner.v1.ListFindingsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.websecurityscanner.v1.ListFindingsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response for the `ListFindings` method.
* </pre>
*
* Protobuf type {@code google.cloud.websecurityscanner.v1.ListFindingsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.websecurityscanner.v1.ListFindingsResponse)
com.google.cloud.websecurityscanner.v1.ListFindingsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.websecurityscanner.v1.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1_ListFindingsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.websecurityscanner.v1.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1_ListFindingsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.websecurityscanner.v1.ListFindingsResponse.class,
com.google.cloud.websecurityscanner.v1.ListFindingsResponse.Builder.class);
}
// Construct using com.google.cloud.websecurityscanner.v1.ListFindingsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (findingsBuilder_ == null) {
findings_ = java.util.Collections.emptyList();
} else {
findings_ = null;
findingsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.websecurityscanner.v1.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1_ListFindingsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1.ListFindingsResponse getDefaultInstanceForType() {
return com.google.cloud.websecurityscanner.v1.ListFindingsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1.ListFindingsResponse build() {
com.google.cloud.websecurityscanner.v1.ListFindingsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1.ListFindingsResponse buildPartial() {
com.google.cloud.websecurityscanner.v1.ListFindingsResponse result =
new com.google.cloud.websecurityscanner.v1.ListFindingsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.websecurityscanner.v1.ListFindingsResponse result) {
if (findingsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
findings_ = java.util.Collections.unmodifiableList(findings_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.findings_ = findings_;
} else {
result.findings_ = findingsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.websecurityscanner.v1.ListFindingsResponse 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.websecurityscanner.v1.ListFindingsResponse) {
return mergeFrom((com.google.cloud.websecurityscanner.v1.ListFindingsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.websecurityscanner.v1.ListFindingsResponse other) {
if (other == com.google.cloud.websecurityscanner.v1.ListFindingsResponse.getDefaultInstance())
return this;
if (findingsBuilder_ == null) {
if (!other.findings_.isEmpty()) {
if (findings_.isEmpty()) {
findings_ = other.findings_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureFindingsIsMutable();
findings_.addAll(other.findings_);
}
onChanged();
}
} else {
if (!other.findings_.isEmpty()) {
if (findingsBuilder_.isEmpty()) {
findingsBuilder_.dispose();
findingsBuilder_ = null;
findings_ = other.findings_;
bitField0_ = (bitField0_ & ~0x00000001);
findingsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getFindingsFieldBuilder()
: null;
} else {
findingsBuilder_.addAllMessages(other.findings_);
}
}
}
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.websecurityscanner.v1.Finding m =
input.readMessage(
com.google.cloud.websecurityscanner.v1.Finding.parser(), extensionRegistry);
if (findingsBuilder_ == null) {
ensureFindingsIsMutable();
findings_.add(m);
} else {
findingsBuilder_.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.websecurityscanner.v1.Finding> findings_ =
java.util.Collections.emptyList();
private void ensureFindingsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
findings_ =
new java.util.ArrayList<com.google.cloud.websecurityscanner.v1.Finding>(findings_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.websecurityscanner.v1.Finding,
com.google.cloud.websecurityscanner.v1.Finding.Builder,
com.google.cloud.websecurityscanner.v1.FindingOrBuilder>
findingsBuilder_;
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public java.util.List<com.google.cloud.websecurityscanner.v1.Finding> getFindingsList() {
if (findingsBuilder_ == null) {
return java.util.Collections.unmodifiableList(findings_);
} else {
return findingsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public int getFindingsCount() {
if (findingsBuilder_ == null) {
return findings_.size();
} else {
return findingsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1.Finding getFindings(int index) {
if (findingsBuilder_ == null) {
return findings_.get(index);
} else {
return findingsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public Builder setFindings(int index, com.google.cloud.websecurityscanner.v1.Finding value) {
if (findingsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureFindingsIsMutable();
findings_.set(index, value);
onChanged();
} else {
findingsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public Builder setFindings(
int index, com.google.cloud.websecurityscanner.v1.Finding.Builder builderForValue) {
if (findingsBuilder_ == null) {
ensureFindingsIsMutable();
findings_.set(index, builderForValue.build());
onChanged();
} else {
findingsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public Builder addFindings(com.google.cloud.websecurityscanner.v1.Finding value) {
if (findingsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureFindingsIsMutable();
findings_.add(value);
onChanged();
} else {
findingsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public Builder addFindings(int index, com.google.cloud.websecurityscanner.v1.Finding value) {
if (findingsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureFindingsIsMutable();
findings_.add(index, value);
onChanged();
} else {
findingsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public Builder addFindings(
com.google.cloud.websecurityscanner.v1.Finding.Builder builderForValue) {
if (findingsBuilder_ == null) {
ensureFindingsIsMutable();
findings_.add(builderForValue.build());
onChanged();
} else {
findingsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public Builder addFindings(
int index, com.google.cloud.websecurityscanner.v1.Finding.Builder builderForValue) {
if (findingsBuilder_ == null) {
ensureFindingsIsMutable();
findings_.add(index, builderForValue.build());
onChanged();
} else {
findingsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public Builder addAllFindings(
java.lang.Iterable<? extends com.google.cloud.websecurityscanner.v1.Finding> values) {
if (findingsBuilder_ == null) {
ensureFindingsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, findings_);
onChanged();
} else {
findingsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public Builder clearFindings() {
if (findingsBuilder_ == null) {
findings_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
findingsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public Builder removeFindings(int index) {
if (findingsBuilder_ == null) {
ensureFindingsIsMutable();
findings_.remove(index);
onChanged();
} else {
findingsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1.Finding.Builder getFindingsBuilder(int index) {
return getFindingsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1.FindingOrBuilder getFindingsOrBuilder(int index) {
if (findingsBuilder_ == null) {
return findings_.get(index);
} else {
return findingsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public java.util.List<? extends com.google.cloud.websecurityscanner.v1.FindingOrBuilder>
getFindingsOrBuilderList() {
if (findingsBuilder_ != null) {
return findingsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(findings_);
}
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1.Finding.Builder addFindingsBuilder() {
return getFindingsFieldBuilder()
.addBuilder(com.google.cloud.websecurityscanner.v1.Finding.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1.Finding.Builder addFindingsBuilder(int index) {
return getFindingsFieldBuilder()
.addBuilder(index, com.google.cloud.websecurityscanner.v1.Finding.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of Findings returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.Finding findings = 1;</code>
*/
public java.util.List<com.google.cloud.websecurityscanner.v1.Finding.Builder>
getFindingsBuilderList() {
return getFindingsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.websecurityscanner.v1.Finding,
com.google.cloud.websecurityscanner.v1.Finding.Builder,
com.google.cloud.websecurityscanner.v1.FindingOrBuilder>
getFindingsFieldBuilder() {
if (findingsBuilder_ == null) {
findingsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.websecurityscanner.v1.Finding,
com.google.cloud.websecurityscanner.v1.Finding.Builder,
com.google.cloud.websecurityscanner.v1.FindingOrBuilder>(
findings_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
findings_ = null;
}
return findingsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.websecurityscanner.v1.ListFindingsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.websecurityscanner.v1.ListFindingsResponse)
private static final com.google.cloud.websecurityscanner.v1.ListFindingsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.websecurityscanner.v1.ListFindingsResponse();
}
public static com.google.cloud.websecurityscanner.v1.ListFindingsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListFindingsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListFindingsResponse>() {
@java.lang.Override
public ListFindingsResponse 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<ListFindingsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListFindingsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1.ListFindingsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,469 | java-analytics-admin/proto-google-analytics-admin-v1alpha/src/main/java/com/google/analytics/admin/v1alpha/ListAccountsResponse.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 ListAccounts RPC.
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1alpha.ListAccountsResponse}
*/
public final class ListAccountsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.analytics.admin.v1alpha.ListAccountsResponse)
ListAccountsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListAccountsResponse.newBuilder() to construct.
private ListAccountsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListAccountsResponse() {
accounts_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListAccountsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_ListAccountsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_ListAccountsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1alpha.ListAccountsResponse.class,
com.google.analytics.admin.v1alpha.ListAccountsResponse.Builder.class);
}
public static final int ACCOUNTS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.analytics.admin.v1alpha.Account> accounts_;
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.analytics.admin.v1alpha.Account> getAccountsList() {
return accounts_;
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.analytics.admin.v1alpha.AccountOrBuilder>
getAccountsOrBuilderList() {
return accounts_;
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
@java.lang.Override
public int getAccountsCount() {
return accounts_.size();
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
@java.lang.Override
public com.google.analytics.admin.v1alpha.Account getAccounts(int index) {
return accounts_.get(index);
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
@java.lang.Override
public com.google.analytics.admin.v1alpha.AccountOrBuilder getAccountsOrBuilder(int index) {
return accounts_.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 < accounts_.size(); i++) {
output.writeMessage(1, accounts_.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 < accounts_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, accounts_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.analytics.admin.v1alpha.ListAccountsResponse)) {
return super.equals(obj);
}
com.google.analytics.admin.v1alpha.ListAccountsResponse other =
(com.google.analytics.admin.v1alpha.ListAccountsResponse) obj;
if (!getAccountsList().equals(other.getAccountsList())) 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 (getAccountsCount() > 0) {
hash = (37 * hash) + ACCOUNTS_FIELD_NUMBER;
hash = (53 * hash) + getAccountsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.analytics.admin.v1alpha.ListAccountsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.ListAccountsResponse 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.ListAccountsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.ListAccountsResponse 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.ListAccountsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.ListAccountsResponse 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.ListAccountsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.ListAccountsResponse 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.ListAccountsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.ListAccountsResponse 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.ListAccountsResponse 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.ListAccountsResponse 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.ListAccountsResponse 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 ListAccounts RPC.
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1alpha.ListAccountsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.analytics.admin.v1alpha.ListAccountsResponse)
com.google.analytics.admin.v1alpha.ListAccountsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_ListAccountsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_ListAccountsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1alpha.ListAccountsResponse.class,
com.google.analytics.admin.v1alpha.ListAccountsResponse.Builder.class);
}
// Construct using com.google.analytics.admin.v1alpha.ListAccountsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (accountsBuilder_ == null) {
accounts_ = java.util.Collections.emptyList();
} else {
accounts_ = null;
accountsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_ListAccountsResponse_descriptor;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.ListAccountsResponse getDefaultInstanceForType() {
return com.google.analytics.admin.v1alpha.ListAccountsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.ListAccountsResponse build() {
com.google.analytics.admin.v1alpha.ListAccountsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.ListAccountsResponse buildPartial() {
com.google.analytics.admin.v1alpha.ListAccountsResponse result =
new com.google.analytics.admin.v1alpha.ListAccountsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.analytics.admin.v1alpha.ListAccountsResponse result) {
if (accountsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
accounts_ = java.util.Collections.unmodifiableList(accounts_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.accounts_ = accounts_;
} else {
result.accounts_ = accountsBuilder_.build();
}
}
private void buildPartial0(com.google.analytics.admin.v1alpha.ListAccountsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.analytics.admin.v1alpha.ListAccountsResponse) {
return mergeFrom((com.google.analytics.admin.v1alpha.ListAccountsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.analytics.admin.v1alpha.ListAccountsResponse other) {
if (other == com.google.analytics.admin.v1alpha.ListAccountsResponse.getDefaultInstance())
return this;
if (accountsBuilder_ == null) {
if (!other.accounts_.isEmpty()) {
if (accounts_.isEmpty()) {
accounts_ = other.accounts_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureAccountsIsMutable();
accounts_.addAll(other.accounts_);
}
onChanged();
}
} else {
if (!other.accounts_.isEmpty()) {
if (accountsBuilder_.isEmpty()) {
accountsBuilder_.dispose();
accountsBuilder_ = null;
accounts_ = other.accounts_;
bitField0_ = (bitField0_ & ~0x00000001);
accountsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getAccountsFieldBuilder()
: null;
} else {
accountsBuilder_.addAllMessages(other.accounts_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.analytics.admin.v1alpha.Account m =
input.readMessage(
com.google.analytics.admin.v1alpha.Account.parser(), extensionRegistry);
if (accountsBuilder_ == null) {
ensureAccountsIsMutable();
accounts_.add(m);
} else {
accountsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.analytics.admin.v1alpha.Account> accounts_ =
java.util.Collections.emptyList();
private void ensureAccountsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
accounts_ = new java.util.ArrayList<com.google.analytics.admin.v1alpha.Account>(accounts_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.analytics.admin.v1alpha.Account,
com.google.analytics.admin.v1alpha.Account.Builder,
com.google.analytics.admin.v1alpha.AccountOrBuilder>
accountsBuilder_;
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public java.util.List<com.google.analytics.admin.v1alpha.Account> getAccountsList() {
if (accountsBuilder_ == null) {
return java.util.Collections.unmodifiableList(accounts_);
} else {
return accountsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public int getAccountsCount() {
if (accountsBuilder_ == null) {
return accounts_.size();
} else {
return accountsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public com.google.analytics.admin.v1alpha.Account getAccounts(int index) {
if (accountsBuilder_ == null) {
return accounts_.get(index);
} else {
return accountsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public Builder setAccounts(int index, com.google.analytics.admin.v1alpha.Account value) {
if (accountsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAccountsIsMutable();
accounts_.set(index, value);
onChanged();
} else {
accountsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public Builder setAccounts(
int index, com.google.analytics.admin.v1alpha.Account.Builder builderForValue) {
if (accountsBuilder_ == null) {
ensureAccountsIsMutable();
accounts_.set(index, builderForValue.build());
onChanged();
} else {
accountsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public Builder addAccounts(com.google.analytics.admin.v1alpha.Account value) {
if (accountsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAccountsIsMutable();
accounts_.add(value);
onChanged();
} else {
accountsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public Builder addAccounts(int index, com.google.analytics.admin.v1alpha.Account value) {
if (accountsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAccountsIsMutable();
accounts_.add(index, value);
onChanged();
} else {
accountsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public Builder addAccounts(com.google.analytics.admin.v1alpha.Account.Builder builderForValue) {
if (accountsBuilder_ == null) {
ensureAccountsIsMutable();
accounts_.add(builderForValue.build());
onChanged();
} else {
accountsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public Builder addAccounts(
int index, com.google.analytics.admin.v1alpha.Account.Builder builderForValue) {
if (accountsBuilder_ == null) {
ensureAccountsIsMutable();
accounts_.add(index, builderForValue.build());
onChanged();
} else {
accountsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public Builder addAllAccounts(
java.lang.Iterable<? extends com.google.analytics.admin.v1alpha.Account> values) {
if (accountsBuilder_ == null) {
ensureAccountsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, accounts_);
onChanged();
} else {
accountsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public Builder clearAccounts() {
if (accountsBuilder_ == null) {
accounts_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
accountsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public Builder removeAccounts(int index) {
if (accountsBuilder_ == null) {
ensureAccountsIsMutable();
accounts_.remove(index);
onChanged();
} else {
accountsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public com.google.analytics.admin.v1alpha.Account.Builder getAccountsBuilder(int index) {
return getAccountsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public com.google.analytics.admin.v1alpha.AccountOrBuilder getAccountsOrBuilder(int index) {
if (accountsBuilder_ == null) {
return accounts_.get(index);
} else {
return accountsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public java.util.List<? extends com.google.analytics.admin.v1alpha.AccountOrBuilder>
getAccountsOrBuilderList() {
if (accountsBuilder_ != null) {
return accountsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(accounts_);
}
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public com.google.analytics.admin.v1alpha.Account.Builder addAccountsBuilder() {
return getAccountsFieldBuilder()
.addBuilder(com.google.analytics.admin.v1alpha.Account.getDefaultInstance());
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public com.google.analytics.admin.v1alpha.Account.Builder addAccountsBuilder(int index) {
return getAccountsFieldBuilder()
.addBuilder(index, com.google.analytics.admin.v1alpha.Account.getDefaultInstance());
}
/**
*
*
* <pre>
* Results that were accessible to the caller.
* </pre>
*
* <code>repeated .google.analytics.admin.v1alpha.Account accounts = 1;</code>
*/
public java.util.List<com.google.analytics.admin.v1alpha.Account.Builder>
getAccountsBuilderList() {
return getAccountsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.analytics.admin.v1alpha.Account,
com.google.analytics.admin.v1alpha.Account.Builder,
com.google.analytics.admin.v1alpha.AccountOrBuilder>
getAccountsFieldBuilder() {
if (accountsBuilder_ == null) {
accountsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.analytics.admin.v1alpha.Account,
com.google.analytics.admin.v1alpha.Account.Builder,
com.google.analytics.admin.v1alpha.AccountOrBuilder>(
accounts_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
accounts_ = null;
}
return accountsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.analytics.admin.v1alpha.ListAccountsResponse)
}
// @@protoc_insertion_point(class_scope:google.analytics.admin.v1alpha.ListAccountsResponse)
private static final com.google.analytics.admin.v1alpha.ListAccountsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.analytics.admin.v1alpha.ListAccountsResponse();
}
public static com.google.analytics.admin.v1alpha.ListAccountsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListAccountsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListAccountsResponse>() {
@java.lang.Override
public ListAccountsResponse 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<ListAccountsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListAccountsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.ListAccountsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,486 | java-recommender/proto-google-cloud-recommender-v1/src/main/java/com/google/cloud/recommender/v1/UpdateInsightTypeConfigRequest.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/recommender/v1/recommender_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.recommender.v1;
/**
*
*
* <pre>
* Request for the `UpdateInsightTypeConfig` method.
* </pre>
*
* Protobuf type {@code google.cloud.recommender.v1.UpdateInsightTypeConfigRequest}
*/
public final class UpdateInsightTypeConfigRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.recommender.v1.UpdateInsightTypeConfigRequest)
UpdateInsightTypeConfigRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateInsightTypeConfigRequest.newBuilder() to construct.
private UpdateInsightTypeConfigRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateInsightTypeConfigRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateInsightTypeConfigRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.recommender.v1.RecommenderProto
.internal_static_google_cloud_recommender_v1_UpdateInsightTypeConfigRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.recommender.v1.RecommenderProto
.internal_static_google_cloud_recommender_v1_UpdateInsightTypeConfigRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest.class,
com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest.Builder.class);
}
private int bitField0_;
public static final int INSIGHT_TYPE_CONFIG_FIELD_NUMBER = 1;
private com.google.cloud.recommender.v1.InsightTypeConfig insightTypeConfig_;
/**
*
*
* <pre>
* Required. The InsightTypeConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.InsightTypeConfig insight_type_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the insightTypeConfig field is set.
*/
@java.lang.Override
public boolean hasInsightTypeConfig() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The InsightTypeConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.InsightTypeConfig insight_type_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The insightTypeConfig.
*/
@java.lang.Override
public com.google.cloud.recommender.v1.InsightTypeConfig getInsightTypeConfig() {
return insightTypeConfig_ == null
? com.google.cloud.recommender.v1.InsightTypeConfig.getDefaultInstance()
: insightTypeConfig_;
}
/**
*
*
* <pre>
* Required. The InsightTypeConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.InsightTypeConfig insight_type_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.recommender.v1.InsightTypeConfigOrBuilder
getInsightTypeConfigOrBuilder() {
return insightTypeConfig_ == null
? com.google.cloud.recommender.v1.InsightTypeConfig.getDefaultInstance()
: insightTypeConfig_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
public static final int VALIDATE_ONLY_FIELD_NUMBER = 3;
private boolean validateOnly_ = false;
/**
*
*
* <pre>
* If true, validate the request and preview the change, but do not actually
* update it.
* </pre>
*
* <code>bool validate_only = 3;</code>
*
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getInsightTypeConfig());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getUpdateMask());
}
if (validateOnly_ != false) {
output.writeBool(3, validateOnly_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getInsightTypeConfig());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask());
}
if (validateOnly_ != false) {
size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, validateOnly_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest)) {
return super.equals(obj);
}
com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest other =
(com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest) obj;
if (hasInsightTypeConfig() != other.hasInsightTypeConfig()) return false;
if (hasInsightTypeConfig()) {
if (!getInsightTypeConfig().equals(other.getInsightTypeConfig())) return false;
}
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask().equals(other.getUpdateMask())) return false;
}
if (getValidateOnly() != other.getValidateOnly()) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasInsightTypeConfig()) {
hash = (37 * hash) + INSIGHT_TYPE_CONFIG_FIELD_NUMBER;
hash = (53 * hash) + getInsightTypeConfig().hashCode();
}
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getValidateOnly());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest 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.recommender.v1.UpdateInsightTypeConfigRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest 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.recommender.v1.UpdateInsightTypeConfigRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest 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.recommender.v1.UpdateInsightTypeConfigRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest 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.recommender.v1.UpdateInsightTypeConfigRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest 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.recommender.v1.UpdateInsightTypeConfigRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request for the `UpdateInsightTypeConfig` method.
* </pre>
*
* Protobuf type {@code google.cloud.recommender.v1.UpdateInsightTypeConfigRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.recommender.v1.UpdateInsightTypeConfigRequest)
com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.recommender.v1.RecommenderProto
.internal_static_google_cloud_recommender_v1_UpdateInsightTypeConfigRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.recommender.v1.RecommenderProto
.internal_static_google_cloud_recommender_v1_UpdateInsightTypeConfigRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest.class,
com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest.Builder.class);
}
// Construct using com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getInsightTypeConfigFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
insightTypeConfig_ = null;
if (insightTypeConfigBuilder_ != null) {
insightTypeConfigBuilder_.dispose();
insightTypeConfigBuilder_ = null;
}
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
validateOnly_ = false;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.recommender.v1.RecommenderProto
.internal_static_google_cloud_recommender_v1_UpdateInsightTypeConfigRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest
getDefaultInstanceForType() {
return com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest build() {
com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest buildPartial() {
com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest result =
new com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.insightTypeConfig_ =
insightTypeConfigBuilder_ == null
? insightTypeConfig_
: insightTypeConfigBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build();
to_bitField0_ |= 0x00000002;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.validateOnly_ = validateOnly_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest) {
return mergeFrom((com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest other) {
if (other
== com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest.getDefaultInstance())
return this;
if (other.hasInsightTypeConfig()) {
mergeInsightTypeConfig(other.getInsightTypeConfig());
}
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
if (other.getValidateOnly() != false) {
setValidateOnly(other.getValidateOnly());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(
getInsightTypeConfigFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 24:
{
validateOnly_ = input.readBool();
bitField0_ |= 0x00000004;
break;
} // case 24
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.cloud.recommender.v1.InsightTypeConfig insightTypeConfig_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.recommender.v1.InsightTypeConfig,
com.google.cloud.recommender.v1.InsightTypeConfig.Builder,
com.google.cloud.recommender.v1.InsightTypeConfigOrBuilder>
insightTypeConfigBuilder_;
/**
*
*
* <pre>
* Required. The InsightTypeConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.InsightTypeConfig insight_type_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the insightTypeConfig field is set.
*/
public boolean hasInsightTypeConfig() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The InsightTypeConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.InsightTypeConfig insight_type_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The insightTypeConfig.
*/
public com.google.cloud.recommender.v1.InsightTypeConfig getInsightTypeConfig() {
if (insightTypeConfigBuilder_ == null) {
return insightTypeConfig_ == null
? com.google.cloud.recommender.v1.InsightTypeConfig.getDefaultInstance()
: insightTypeConfig_;
} else {
return insightTypeConfigBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The InsightTypeConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.InsightTypeConfig insight_type_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInsightTypeConfig(com.google.cloud.recommender.v1.InsightTypeConfig value) {
if (insightTypeConfigBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
insightTypeConfig_ = value;
} else {
insightTypeConfigBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The InsightTypeConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.InsightTypeConfig insight_type_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInsightTypeConfig(
com.google.cloud.recommender.v1.InsightTypeConfig.Builder builderForValue) {
if (insightTypeConfigBuilder_ == null) {
insightTypeConfig_ = builderForValue.build();
} else {
insightTypeConfigBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The InsightTypeConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.InsightTypeConfig insight_type_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeInsightTypeConfig(com.google.cloud.recommender.v1.InsightTypeConfig value) {
if (insightTypeConfigBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& insightTypeConfig_ != null
&& insightTypeConfig_
!= com.google.cloud.recommender.v1.InsightTypeConfig.getDefaultInstance()) {
getInsightTypeConfigBuilder().mergeFrom(value);
} else {
insightTypeConfig_ = value;
}
} else {
insightTypeConfigBuilder_.mergeFrom(value);
}
if (insightTypeConfig_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The InsightTypeConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.InsightTypeConfig insight_type_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearInsightTypeConfig() {
bitField0_ = (bitField0_ & ~0x00000001);
insightTypeConfig_ = null;
if (insightTypeConfigBuilder_ != null) {
insightTypeConfigBuilder_.dispose();
insightTypeConfigBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The InsightTypeConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.InsightTypeConfig insight_type_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.recommender.v1.InsightTypeConfig.Builder getInsightTypeConfigBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getInsightTypeConfigFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The InsightTypeConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.InsightTypeConfig insight_type_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.recommender.v1.InsightTypeConfigOrBuilder
getInsightTypeConfigOrBuilder() {
if (insightTypeConfigBuilder_ != null) {
return insightTypeConfigBuilder_.getMessageOrBuilder();
} else {
return insightTypeConfig_ == null
? com.google.cloud.recommender.v1.InsightTypeConfig.getDefaultInstance()
: insightTypeConfig_;
}
}
/**
*
*
* <pre>
* Required. The InsightTypeConfig to update.
* </pre>
*
* <code>
* .google.cloud.recommender.v1.InsightTypeConfig insight_type_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.recommender.v1.InsightTypeConfig,
com.google.cloud.recommender.v1.InsightTypeConfig.Builder,
com.google.cloud.recommender.v1.InsightTypeConfigOrBuilder>
getInsightTypeConfigFieldBuilder() {
if (insightTypeConfigBuilder_ == null) {
insightTypeConfigBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.recommender.v1.InsightTypeConfig,
com.google.cloud.recommender.v1.InsightTypeConfig.Builder,
com.google.cloud.recommender.v1.InsightTypeConfigOrBuilder>(
getInsightTypeConfig(), getParentForChildren(), isClean());
insightTypeConfig_ = null;
}
return insightTypeConfigBuilder_;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
updateMaskBuilder_;
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
} else {
updateMaskBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& updateMask_ != null
&& updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) {
getUpdateMaskBuilder().mergeFrom(value);
} else {
updateMask_ = value;
}
} else {
updateMaskBuilder_.mergeFrom(value);
}
if (updateMask_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000002);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* The list of fields to be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
private boolean validateOnly_;
/**
*
*
* <pre>
* If true, validate the request and preview the change, but do not actually
* update it.
* </pre>
*
* <code>bool validate_only = 3;</code>
*
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
/**
*
*
* <pre>
* If true, validate the request and preview the change, but do not actually
* update it.
* </pre>
*
* <code>bool validate_only = 3;</code>
*
* @param value The validateOnly to set.
* @return This builder for chaining.
*/
public Builder setValidateOnly(boolean value) {
validateOnly_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* If true, validate the request and preview the change, but do not actually
* update it.
* </pre>
*
* <code>bool validate_only = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearValidateOnly() {
bitField0_ = (bitField0_ & ~0x00000004);
validateOnly_ = false;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.recommender.v1.UpdateInsightTypeConfigRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.recommender.v1.UpdateInsightTypeConfigRequest)
private static final com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest();
}
public static com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateInsightTypeConfigRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateInsightTypeConfigRequest>() {
@java.lang.Override
public UpdateInsightTypeConfigRequest 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<UpdateInsightTypeConfigRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateInsightTypeConfigRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.recommender.v1.UpdateInsightTypeConfigRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-api-java-client-services | 36,603 | clients/google-api-services-drive/v3/1.26.0/com/google/api/services/drive/model/TeamDrive.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.drive.model;
/**
* Deprecated: use the drive collection instead.
*
* <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 Drive 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 TeamDrive extends com.google.api.client.json.GenericJson {
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't
* set themeId. When specified, all fields of the backgroundImageFile must be set.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private BackgroundImageFile backgroundImageFile;
/**
* A short-lived link to this Team Drive's background image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String backgroundImageLink;
/**
* Capabilities the current user has on this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Capabilities capabilities;
/**
* The color of this Team Drive as an RGB hex string. It can only be set on a
* drive.teamdrives.update request that does not set themeId.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String colorRgb;
/**
* The time at which the Team Drive was created (RFC 3339 date-time).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime createdTime;
/**
* The ID of this Team Drive which is also the ID of the top level folder of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String id;
/**
* Identifies what kind of resource this is. Value: the fixed string "drive#teamDrive".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* The name of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Restrictions restrictions;
/**
* The ID of the theme from which the background image and color will be set. The set of possible
* teamDriveThemes can be retrieved from a drive.about.get response. When not specified on a
* drive.teamdrives.create request, a random theme is chosen from which the background image and
* color are set. This is a write-only field; it can only be set on requests that don't set
* colorRgb or backgroundImageFile.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String themeId;
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't
* set themeId. When specified, all fields of the backgroundImageFile must be set.
* @return value or {@code null} for none
*/
public BackgroundImageFile getBackgroundImageFile() {
return backgroundImageFile;
}
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't
* set themeId. When specified, all fields of the backgroundImageFile must be set.
* @param backgroundImageFile backgroundImageFile or {@code null} for none
*/
public TeamDrive setBackgroundImageFile(BackgroundImageFile backgroundImageFile) {
this.backgroundImageFile = backgroundImageFile;
return this;
}
/**
* A short-lived link to this Team Drive's background image.
* @return value or {@code null} for none
*/
public java.lang.String getBackgroundImageLink() {
return backgroundImageLink;
}
/**
* A short-lived link to this Team Drive's background image.
* @param backgroundImageLink backgroundImageLink or {@code null} for none
*/
public TeamDrive setBackgroundImageLink(java.lang.String backgroundImageLink) {
this.backgroundImageLink = backgroundImageLink;
return this;
}
/**
* Capabilities the current user has on this Team Drive.
* @return value or {@code null} for none
*/
public Capabilities getCapabilities() {
return capabilities;
}
/**
* Capabilities the current user has on this Team Drive.
* @param capabilities capabilities or {@code null} for none
*/
public TeamDrive setCapabilities(Capabilities capabilities) {
this.capabilities = capabilities;
return this;
}
/**
* The color of this Team Drive as an RGB hex string. It can only be set on a
* drive.teamdrives.update request that does not set themeId.
* @return value or {@code null} for none
*/
public java.lang.String getColorRgb() {
return colorRgb;
}
/**
* The color of this Team Drive as an RGB hex string. It can only be set on a
* drive.teamdrives.update request that does not set themeId.
* @param colorRgb colorRgb or {@code null} for none
*/
public TeamDrive setColorRgb(java.lang.String colorRgb) {
this.colorRgb = colorRgb;
return this;
}
/**
* The time at which the Team Drive was created (RFC 3339 date-time).
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getCreatedTime() {
return createdTime;
}
/**
* The time at which the Team Drive was created (RFC 3339 date-time).
* @param createdTime createdTime or {@code null} for none
*/
public TeamDrive setCreatedTime(com.google.api.client.util.DateTime createdTime) {
this.createdTime = createdTime;
return this;
}
/**
* The ID of this Team Drive which is also the ID of the top level folder of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.String getId() {
return id;
}
/**
* The ID of this Team Drive which is also the ID of the top level folder of this Team Drive.
* @param id id or {@code null} for none
*/
public TeamDrive setId(java.lang.String id) {
this.id = id;
return this;
}
/**
* Identifies what kind of resource this is. Value: the fixed string "drive#teamDrive".
* @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 "drive#teamDrive".
* @param kind kind or {@code null} for none
*/
public TeamDrive setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* The name of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* The name of this Team Drive.
* @param name name or {@code null} for none
*/
public TeamDrive setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
* @return value or {@code null} for none
*/
public Restrictions getRestrictions() {
return restrictions;
}
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
* @param restrictions restrictions or {@code null} for none
*/
public TeamDrive setRestrictions(Restrictions restrictions) {
this.restrictions = restrictions;
return this;
}
/**
* The ID of the theme from which the background image and color will be set. The set of possible
* teamDriveThemes can be retrieved from a drive.about.get response. When not specified on a
* drive.teamdrives.create request, a random theme is chosen from which the background image and
* color are set. This is a write-only field; it can only be set on requests that don't set
* colorRgb or backgroundImageFile.
* @return value or {@code null} for none
*/
public java.lang.String getThemeId() {
return themeId;
}
/**
* The ID of the theme from which the background image and color will be set. The set of possible
* teamDriveThemes can be retrieved from a drive.about.get response. When not specified on a
* drive.teamdrives.create request, a random theme is chosen from which the background image and
* color are set. This is a write-only field; it can only be set on requests that don't set
* colorRgb or backgroundImageFile.
* @param themeId themeId or {@code null} for none
*/
public TeamDrive setThemeId(java.lang.String themeId) {
this.themeId = themeId;
return this;
}
@Override
public TeamDrive set(String fieldName, Object value) {
return (TeamDrive) super.set(fieldName, value);
}
@Override
public TeamDrive clone() {
return (TeamDrive) super.clone();
}
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't set
* themeId. When specified, all fields of the backgroundImageFile must be set.
*/
public static final class BackgroundImageFile extends com.google.api.client.json.GenericJson {
/**
* The ID of an image file in Drive to use for the background image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String id;
/**
* The width of the cropped image in the closed range of 0 to 1. This value represents the width
* of the cropped image divided by the width of the entire image. The height is computed by
* applying a width to height aspect ratio of 80 to 9. The resulting image must be at least 1280
* pixels wide and 144 pixels high.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Float width;
/**
* The X coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the horizontal distance from the
* left side of the entire image to the left side of the cropping area divided by the width of the
* entire image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Float xCoordinate;
/**
* The Y coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the vertical distance from the top
* side of the entire image to the top side of the cropping area divided by the height of the
* entire image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Float yCoordinate;
/**
* The ID of an image file in Drive to use for the background image.
* @return value or {@code null} for none
*/
public java.lang.String getId() {
return id;
}
/**
* The ID of an image file in Drive to use for the background image.
* @param id id or {@code null} for none
*/
public BackgroundImageFile setId(java.lang.String id) {
this.id = id;
return this;
}
/**
* The width of the cropped image in the closed range of 0 to 1. This value represents the width
* of the cropped image divided by the width of the entire image. The height is computed by
* applying a width to height aspect ratio of 80 to 9. The resulting image must be at least 1280
* pixels wide and 144 pixels high.
* @return value or {@code null} for none
*/
public java.lang.Float getWidth() {
return width;
}
/**
* The width of the cropped image in the closed range of 0 to 1. This value represents the width
* of the cropped image divided by the width of the entire image. The height is computed by
* applying a width to height aspect ratio of 80 to 9. The resulting image must be at least 1280
* pixels wide and 144 pixels high.
* @param width width or {@code null} for none
*/
public BackgroundImageFile setWidth(java.lang.Float width) {
this.width = width;
return this;
}
/**
* The X coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the horizontal distance from the
* left side of the entire image to the left side of the cropping area divided by the width of the
* entire image.
* @return value or {@code null} for none
*/
public java.lang.Float getXCoordinate() {
return xCoordinate;
}
/**
* The X coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the horizontal distance from the
* left side of the entire image to the left side of the cropping area divided by the width of the
* entire image.
* @param xCoordinate xCoordinate or {@code null} for none
*/
public BackgroundImageFile setXCoordinate(java.lang.Float xCoordinate) {
this.xCoordinate = xCoordinate;
return this;
}
/**
* The Y coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the vertical distance from the top
* side of the entire image to the top side of the cropping area divided by the height of the
* entire image.
* @return value or {@code null} for none
*/
public java.lang.Float getYCoordinate() {
return yCoordinate;
}
/**
* The Y coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the vertical distance from the top
* side of the entire image to the top side of the cropping area divided by the height of the
* entire image.
* @param yCoordinate yCoordinate or {@code null} for none
*/
public BackgroundImageFile setYCoordinate(java.lang.Float yCoordinate) {
this.yCoordinate = yCoordinate;
return this;
}
@Override
public BackgroundImageFile set(String fieldName, Object value) {
return (BackgroundImageFile) super.set(fieldName, value);
}
@Override
public BackgroundImageFile clone() {
return (BackgroundImageFile) super.clone();
}
}
/**
* Capabilities the current user has on this Team Drive.
*/
public static final class Capabilities extends com.google.api.client.json.GenericJson {
/**
* Whether the current user can add children to folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canAddChildren;
/**
* Whether the current user can change the copyRequiresWriterPermission restriction of this Team
* Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeCopyRequiresWriterPermissionRestriction;
/**
* Whether the current user can change the domainUsersOnly restriction of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeDomainUsersOnlyRestriction;
/**
* Whether the current user can change the background of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeTeamDriveBackground;
/**
* Whether the current user can change the teamMembersOnly restriction of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeTeamMembersOnlyRestriction;
/**
* Whether the current user can comment on files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canComment;
/**
* Whether the current user can copy files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canCopy;
/**
* Whether the current user can delete children from folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canDeleteChildren;
/**
* Whether the current user can delete this Team Drive. Attempting to delete the Team Drive may
* still fail if there are untrashed items inside the Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canDeleteTeamDrive;
/**
* Whether the current user can download files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canDownload;
/**
* Whether the current user can edit files in this Team Drive
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canEdit;
/**
* Whether the current user can list the children of folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canListChildren;
/**
* Whether the current user can add members to this Team Drive or remove them or change their
* role.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canManageMembers;
/**
* Whether the current user can read the revisions resource of files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canReadRevisions;
/**
* Deprecated - use canDeleteChildren or canTrashChildren instead.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canRemoveChildren;
/**
* Whether the current user can rename files or folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canRename;
/**
* Whether the current user can rename this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canRenameTeamDrive;
/**
* Whether the current user can share files or folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canShare;
/**
* Whether the current user can trash children from folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canTrashChildren;
/**
* Whether the current user can add children to folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanAddChildren() {
return canAddChildren;
}
/**
* Whether the current user can add children to folders in this Team Drive.
* @param canAddChildren canAddChildren or {@code null} for none
*/
public Capabilities setCanAddChildren(java.lang.Boolean canAddChildren) {
this.canAddChildren = canAddChildren;
return this;
}
/**
* Whether the current user can change the copyRequiresWriterPermission restriction of this Team
* Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeCopyRequiresWriterPermissionRestriction() {
return canChangeCopyRequiresWriterPermissionRestriction;
}
/**
* Whether the current user can change the copyRequiresWriterPermission restriction of this Team
* Drive.
* @param canChangeCopyRequiresWriterPermissionRestriction canChangeCopyRequiresWriterPermissionRestriction or {@code null} for none
*/
public Capabilities setCanChangeCopyRequiresWriterPermissionRestriction(java.lang.Boolean canChangeCopyRequiresWriterPermissionRestriction) {
this.canChangeCopyRequiresWriterPermissionRestriction = canChangeCopyRequiresWriterPermissionRestriction;
return this;
}
/**
* Whether the current user can change the domainUsersOnly restriction of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeDomainUsersOnlyRestriction() {
return canChangeDomainUsersOnlyRestriction;
}
/**
* Whether the current user can change the domainUsersOnly restriction of this Team Drive.
* @param canChangeDomainUsersOnlyRestriction canChangeDomainUsersOnlyRestriction or {@code null} for none
*/
public Capabilities setCanChangeDomainUsersOnlyRestriction(java.lang.Boolean canChangeDomainUsersOnlyRestriction) {
this.canChangeDomainUsersOnlyRestriction = canChangeDomainUsersOnlyRestriction;
return this;
}
/**
* Whether the current user can change the background of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeTeamDriveBackground() {
return canChangeTeamDriveBackground;
}
/**
* Whether the current user can change the background of this Team Drive.
* @param canChangeTeamDriveBackground canChangeTeamDriveBackground or {@code null} for none
*/
public Capabilities setCanChangeTeamDriveBackground(java.lang.Boolean canChangeTeamDriveBackground) {
this.canChangeTeamDriveBackground = canChangeTeamDriveBackground;
return this;
}
/**
* Whether the current user can change the teamMembersOnly restriction of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeTeamMembersOnlyRestriction() {
return canChangeTeamMembersOnlyRestriction;
}
/**
* Whether the current user can change the teamMembersOnly restriction of this Team Drive.
* @param canChangeTeamMembersOnlyRestriction canChangeTeamMembersOnlyRestriction or {@code null} for none
*/
public Capabilities setCanChangeTeamMembersOnlyRestriction(java.lang.Boolean canChangeTeamMembersOnlyRestriction) {
this.canChangeTeamMembersOnlyRestriction = canChangeTeamMembersOnlyRestriction;
return this;
}
/**
* Whether the current user can comment on files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanComment() {
return canComment;
}
/**
* Whether the current user can comment on files in this Team Drive.
* @param canComment canComment or {@code null} for none
*/
public Capabilities setCanComment(java.lang.Boolean canComment) {
this.canComment = canComment;
return this;
}
/**
* Whether the current user can copy files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanCopy() {
return canCopy;
}
/**
* Whether the current user can copy files in this Team Drive.
* @param canCopy canCopy or {@code null} for none
*/
public Capabilities setCanCopy(java.lang.Boolean canCopy) {
this.canCopy = canCopy;
return this;
}
/**
* Whether the current user can delete children from folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanDeleteChildren() {
return canDeleteChildren;
}
/**
* Whether the current user can delete children from folders in this Team Drive.
* @param canDeleteChildren canDeleteChildren or {@code null} for none
*/
public Capabilities setCanDeleteChildren(java.lang.Boolean canDeleteChildren) {
this.canDeleteChildren = canDeleteChildren;
return this;
}
/**
* Whether the current user can delete this Team Drive. Attempting to delete the Team Drive may
* still fail if there are untrashed items inside the Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanDeleteTeamDrive() {
return canDeleteTeamDrive;
}
/**
* Whether the current user can delete this Team Drive. Attempting to delete the Team Drive may
* still fail if there are untrashed items inside the Team Drive.
* @param canDeleteTeamDrive canDeleteTeamDrive or {@code null} for none
*/
public Capabilities setCanDeleteTeamDrive(java.lang.Boolean canDeleteTeamDrive) {
this.canDeleteTeamDrive = canDeleteTeamDrive;
return this;
}
/**
* Whether the current user can download files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanDownload() {
return canDownload;
}
/**
* Whether the current user can download files in this Team Drive.
* @param canDownload canDownload or {@code null} for none
*/
public Capabilities setCanDownload(java.lang.Boolean canDownload) {
this.canDownload = canDownload;
return this;
}
/**
* Whether the current user can edit files in this Team Drive
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanEdit() {
return canEdit;
}
/**
* Whether the current user can edit files in this Team Drive
* @param canEdit canEdit or {@code null} for none
*/
public Capabilities setCanEdit(java.lang.Boolean canEdit) {
this.canEdit = canEdit;
return this;
}
/**
* Whether the current user can list the children of folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanListChildren() {
return canListChildren;
}
/**
* Whether the current user can list the children of folders in this Team Drive.
* @param canListChildren canListChildren or {@code null} for none
*/
public Capabilities setCanListChildren(java.lang.Boolean canListChildren) {
this.canListChildren = canListChildren;
return this;
}
/**
* Whether the current user can add members to this Team Drive or remove them or change their
* role.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanManageMembers() {
return canManageMembers;
}
/**
* Whether the current user can add members to this Team Drive or remove them or change their
* role.
* @param canManageMembers canManageMembers or {@code null} for none
*/
public Capabilities setCanManageMembers(java.lang.Boolean canManageMembers) {
this.canManageMembers = canManageMembers;
return this;
}
/**
* Whether the current user can read the revisions resource of files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanReadRevisions() {
return canReadRevisions;
}
/**
* Whether the current user can read the revisions resource of files in this Team Drive.
* @param canReadRevisions canReadRevisions or {@code null} for none
*/
public Capabilities setCanReadRevisions(java.lang.Boolean canReadRevisions) {
this.canReadRevisions = canReadRevisions;
return this;
}
/**
* Deprecated - use canDeleteChildren or canTrashChildren instead.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanRemoveChildren() {
return canRemoveChildren;
}
/**
* Deprecated - use canDeleteChildren or canTrashChildren instead.
* @param canRemoveChildren canRemoveChildren or {@code null} for none
*/
public Capabilities setCanRemoveChildren(java.lang.Boolean canRemoveChildren) {
this.canRemoveChildren = canRemoveChildren;
return this;
}
/**
* Whether the current user can rename files or folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanRename() {
return canRename;
}
/**
* Whether the current user can rename files or folders in this Team Drive.
* @param canRename canRename or {@code null} for none
*/
public Capabilities setCanRename(java.lang.Boolean canRename) {
this.canRename = canRename;
return this;
}
/**
* Whether the current user can rename this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanRenameTeamDrive() {
return canRenameTeamDrive;
}
/**
* Whether the current user can rename this Team Drive.
* @param canRenameTeamDrive canRenameTeamDrive or {@code null} for none
*/
public Capabilities setCanRenameTeamDrive(java.lang.Boolean canRenameTeamDrive) {
this.canRenameTeamDrive = canRenameTeamDrive;
return this;
}
/**
* Whether the current user can share files or folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanShare() {
return canShare;
}
/**
* Whether the current user can share files or folders in this Team Drive.
* @param canShare canShare or {@code null} for none
*/
public Capabilities setCanShare(java.lang.Boolean canShare) {
this.canShare = canShare;
return this;
}
/**
* Whether the current user can trash children from folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanTrashChildren() {
return canTrashChildren;
}
/**
* Whether the current user can trash children from folders in this Team Drive.
* @param canTrashChildren canTrashChildren or {@code null} for none
*/
public Capabilities setCanTrashChildren(java.lang.Boolean canTrashChildren) {
this.canTrashChildren = canTrashChildren;
return this;
}
@Override
public Capabilities set(String fieldName, Object value) {
return (Capabilities) super.set(fieldName, value);
}
@Override
public Capabilities clone() {
return (Capabilities) super.clone();
}
}
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
*/
public static final class Restrictions extends com.google.api.client.json.GenericJson {
/**
* Whether administrative privileges on this Team Drive are required to modify restrictions.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean adminManagedRestrictions;
/**
* Whether the options to copy, print, or download files inside this Team Drive, should be
* disabled for readers and commenters. When this restriction is set to true, it will override the
* similarly named field to true for any file inside this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean copyRequiresWriterPermission;
/**
* Whether access to this Team Drive and items inside this Team Drive is restricted to users of
* the domain to which this Team Drive belongs. This restriction may be overridden by other
* sharing policies controlled outside of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean domainUsersOnly;
/**
* Whether access to items inside this Team Drive is restricted to members of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean teamMembersOnly;
/**
* Whether administrative privileges on this Team Drive are required to modify restrictions.
* @return value or {@code null} for none
*/
public java.lang.Boolean getAdminManagedRestrictions() {
return adminManagedRestrictions;
}
/**
* Whether administrative privileges on this Team Drive are required to modify restrictions.
* @param adminManagedRestrictions adminManagedRestrictions or {@code null} for none
*/
public Restrictions setAdminManagedRestrictions(java.lang.Boolean adminManagedRestrictions) {
this.adminManagedRestrictions = adminManagedRestrictions;
return this;
}
/**
* Whether the options to copy, print, or download files inside this Team Drive, should be
* disabled for readers and commenters. When this restriction is set to true, it will override the
* similarly named field to true for any file inside this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCopyRequiresWriterPermission() {
return copyRequiresWriterPermission;
}
/**
* Whether the options to copy, print, or download files inside this Team Drive, should be
* disabled for readers and commenters. When this restriction is set to true, it will override the
* similarly named field to true for any file inside this Team Drive.
* @param copyRequiresWriterPermission copyRequiresWriterPermission or {@code null} for none
*/
public Restrictions setCopyRequiresWriterPermission(java.lang.Boolean copyRequiresWriterPermission) {
this.copyRequiresWriterPermission = copyRequiresWriterPermission;
return this;
}
/**
* Whether access to this Team Drive and items inside this Team Drive is restricted to users of
* the domain to which this Team Drive belongs. This restriction may be overridden by other
* sharing policies controlled outside of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDomainUsersOnly() {
return domainUsersOnly;
}
/**
* Whether access to this Team Drive and items inside this Team Drive is restricted to users of
* the domain to which this Team Drive belongs. This restriction may be overridden by other
* sharing policies controlled outside of this Team Drive.
* @param domainUsersOnly domainUsersOnly or {@code null} for none
*/
public Restrictions setDomainUsersOnly(java.lang.Boolean domainUsersOnly) {
this.domainUsersOnly = domainUsersOnly;
return this;
}
/**
* Whether access to items inside this Team Drive is restricted to members of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getTeamMembersOnly() {
return teamMembersOnly;
}
/**
* Whether access to items inside this Team Drive is restricted to members of this Team Drive.
* @param teamMembersOnly teamMembersOnly or {@code null} for none
*/
public Restrictions setTeamMembersOnly(java.lang.Boolean teamMembersOnly) {
this.teamMembersOnly = teamMembersOnly;
return this;
}
@Override
public Restrictions set(String fieldName, Object value) {
return (Restrictions) super.set(fieldName, value);
}
@Override
public Restrictions clone() {
return (Restrictions) super.clone();
}
}
}
|
googleapis/google-api-java-client-services | 36,603 | clients/google-api-services-drive/v3/1.27.0/com/google/api/services/drive/model/TeamDrive.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.drive.model;
/**
* Deprecated: use the drive collection instead.
*
* <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 Drive 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 TeamDrive extends com.google.api.client.json.GenericJson {
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't
* set themeId. When specified, all fields of the backgroundImageFile must be set.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private BackgroundImageFile backgroundImageFile;
/**
* A short-lived link to this Team Drive's background image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String backgroundImageLink;
/**
* Capabilities the current user has on this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Capabilities capabilities;
/**
* The color of this Team Drive as an RGB hex string. It can only be set on a
* drive.teamdrives.update request that does not set themeId.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String colorRgb;
/**
* The time at which the Team Drive was created (RFC 3339 date-time).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime createdTime;
/**
* The ID of this Team Drive which is also the ID of the top level folder of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String id;
/**
* Identifies what kind of resource this is. Value: the fixed string "drive#teamDrive".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* The name of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Restrictions restrictions;
/**
* The ID of the theme from which the background image and color will be set. The set of possible
* teamDriveThemes can be retrieved from a drive.about.get response. When not specified on a
* drive.teamdrives.create request, a random theme is chosen from which the background image and
* color are set. This is a write-only field; it can only be set on requests that don't set
* colorRgb or backgroundImageFile.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String themeId;
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't
* set themeId. When specified, all fields of the backgroundImageFile must be set.
* @return value or {@code null} for none
*/
public BackgroundImageFile getBackgroundImageFile() {
return backgroundImageFile;
}
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't
* set themeId. When specified, all fields of the backgroundImageFile must be set.
* @param backgroundImageFile backgroundImageFile or {@code null} for none
*/
public TeamDrive setBackgroundImageFile(BackgroundImageFile backgroundImageFile) {
this.backgroundImageFile = backgroundImageFile;
return this;
}
/**
* A short-lived link to this Team Drive's background image.
* @return value or {@code null} for none
*/
public java.lang.String getBackgroundImageLink() {
return backgroundImageLink;
}
/**
* A short-lived link to this Team Drive's background image.
* @param backgroundImageLink backgroundImageLink or {@code null} for none
*/
public TeamDrive setBackgroundImageLink(java.lang.String backgroundImageLink) {
this.backgroundImageLink = backgroundImageLink;
return this;
}
/**
* Capabilities the current user has on this Team Drive.
* @return value or {@code null} for none
*/
public Capabilities getCapabilities() {
return capabilities;
}
/**
* Capabilities the current user has on this Team Drive.
* @param capabilities capabilities or {@code null} for none
*/
public TeamDrive setCapabilities(Capabilities capabilities) {
this.capabilities = capabilities;
return this;
}
/**
* The color of this Team Drive as an RGB hex string. It can only be set on a
* drive.teamdrives.update request that does not set themeId.
* @return value or {@code null} for none
*/
public java.lang.String getColorRgb() {
return colorRgb;
}
/**
* The color of this Team Drive as an RGB hex string. It can only be set on a
* drive.teamdrives.update request that does not set themeId.
* @param colorRgb colorRgb or {@code null} for none
*/
public TeamDrive setColorRgb(java.lang.String colorRgb) {
this.colorRgb = colorRgb;
return this;
}
/**
* The time at which the Team Drive was created (RFC 3339 date-time).
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getCreatedTime() {
return createdTime;
}
/**
* The time at which the Team Drive was created (RFC 3339 date-time).
* @param createdTime createdTime or {@code null} for none
*/
public TeamDrive setCreatedTime(com.google.api.client.util.DateTime createdTime) {
this.createdTime = createdTime;
return this;
}
/**
* The ID of this Team Drive which is also the ID of the top level folder of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.String getId() {
return id;
}
/**
* The ID of this Team Drive which is also the ID of the top level folder of this Team Drive.
* @param id id or {@code null} for none
*/
public TeamDrive setId(java.lang.String id) {
this.id = id;
return this;
}
/**
* Identifies what kind of resource this is. Value: the fixed string "drive#teamDrive".
* @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 "drive#teamDrive".
* @param kind kind or {@code null} for none
*/
public TeamDrive setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* The name of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* The name of this Team Drive.
* @param name name or {@code null} for none
*/
public TeamDrive setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
* @return value or {@code null} for none
*/
public Restrictions getRestrictions() {
return restrictions;
}
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
* @param restrictions restrictions or {@code null} for none
*/
public TeamDrive setRestrictions(Restrictions restrictions) {
this.restrictions = restrictions;
return this;
}
/**
* The ID of the theme from which the background image and color will be set. The set of possible
* teamDriveThemes can be retrieved from a drive.about.get response. When not specified on a
* drive.teamdrives.create request, a random theme is chosen from which the background image and
* color are set. This is a write-only field; it can only be set on requests that don't set
* colorRgb or backgroundImageFile.
* @return value or {@code null} for none
*/
public java.lang.String getThemeId() {
return themeId;
}
/**
* The ID of the theme from which the background image and color will be set. The set of possible
* teamDriveThemes can be retrieved from a drive.about.get response. When not specified on a
* drive.teamdrives.create request, a random theme is chosen from which the background image and
* color are set. This is a write-only field; it can only be set on requests that don't set
* colorRgb or backgroundImageFile.
* @param themeId themeId or {@code null} for none
*/
public TeamDrive setThemeId(java.lang.String themeId) {
this.themeId = themeId;
return this;
}
@Override
public TeamDrive set(String fieldName, Object value) {
return (TeamDrive) super.set(fieldName, value);
}
@Override
public TeamDrive clone() {
return (TeamDrive) super.clone();
}
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't set
* themeId. When specified, all fields of the backgroundImageFile must be set.
*/
public static final class BackgroundImageFile extends com.google.api.client.json.GenericJson {
/**
* The ID of an image file in Drive to use for the background image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String id;
/**
* The width of the cropped image in the closed range of 0 to 1. This value represents the width
* of the cropped image divided by the width of the entire image. The height is computed by
* applying a width to height aspect ratio of 80 to 9. The resulting image must be at least 1280
* pixels wide and 144 pixels high.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Float width;
/**
* The X coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the horizontal distance from the
* left side of the entire image to the left side of the cropping area divided by the width of the
* entire image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Float xCoordinate;
/**
* The Y coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the vertical distance from the top
* side of the entire image to the top side of the cropping area divided by the height of the
* entire image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Float yCoordinate;
/**
* The ID of an image file in Drive to use for the background image.
* @return value or {@code null} for none
*/
public java.lang.String getId() {
return id;
}
/**
* The ID of an image file in Drive to use for the background image.
* @param id id or {@code null} for none
*/
public BackgroundImageFile setId(java.lang.String id) {
this.id = id;
return this;
}
/**
* The width of the cropped image in the closed range of 0 to 1. This value represents the width
* of the cropped image divided by the width of the entire image. The height is computed by
* applying a width to height aspect ratio of 80 to 9. The resulting image must be at least 1280
* pixels wide and 144 pixels high.
* @return value or {@code null} for none
*/
public java.lang.Float getWidth() {
return width;
}
/**
* The width of the cropped image in the closed range of 0 to 1. This value represents the width
* of the cropped image divided by the width of the entire image. The height is computed by
* applying a width to height aspect ratio of 80 to 9. The resulting image must be at least 1280
* pixels wide and 144 pixels high.
* @param width width or {@code null} for none
*/
public BackgroundImageFile setWidth(java.lang.Float width) {
this.width = width;
return this;
}
/**
* The X coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the horizontal distance from the
* left side of the entire image to the left side of the cropping area divided by the width of the
* entire image.
* @return value or {@code null} for none
*/
public java.lang.Float getXCoordinate() {
return xCoordinate;
}
/**
* The X coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the horizontal distance from the
* left side of the entire image to the left side of the cropping area divided by the width of the
* entire image.
* @param xCoordinate xCoordinate or {@code null} for none
*/
public BackgroundImageFile setXCoordinate(java.lang.Float xCoordinate) {
this.xCoordinate = xCoordinate;
return this;
}
/**
* The Y coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the vertical distance from the top
* side of the entire image to the top side of the cropping area divided by the height of the
* entire image.
* @return value or {@code null} for none
*/
public java.lang.Float getYCoordinate() {
return yCoordinate;
}
/**
* The Y coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the vertical distance from the top
* side of the entire image to the top side of the cropping area divided by the height of the
* entire image.
* @param yCoordinate yCoordinate or {@code null} for none
*/
public BackgroundImageFile setYCoordinate(java.lang.Float yCoordinate) {
this.yCoordinate = yCoordinate;
return this;
}
@Override
public BackgroundImageFile set(String fieldName, Object value) {
return (BackgroundImageFile) super.set(fieldName, value);
}
@Override
public BackgroundImageFile clone() {
return (BackgroundImageFile) super.clone();
}
}
/**
* Capabilities the current user has on this Team Drive.
*/
public static final class Capabilities extends com.google.api.client.json.GenericJson {
/**
* Whether the current user can add children to folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canAddChildren;
/**
* Whether the current user can change the copyRequiresWriterPermission restriction of this Team
* Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeCopyRequiresWriterPermissionRestriction;
/**
* Whether the current user can change the domainUsersOnly restriction of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeDomainUsersOnlyRestriction;
/**
* Whether the current user can change the background of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeTeamDriveBackground;
/**
* Whether the current user can change the teamMembersOnly restriction of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeTeamMembersOnlyRestriction;
/**
* Whether the current user can comment on files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canComment;
/**
* Whether the current user can copy files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canCopy;
/**
* Whether the current user can delete children from folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canDeleteChildren;
/**
* Whether the current user can delete this Team Drive. Attempting to delete the Team Drive may
* still fail if there are untrashed items inside the Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canDeleteTeamDrive;
/**
* Whether the current user can download files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canDownload;
/**
* Whether the current user can edit files in this Team Drive
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canEdit;
/**
* Whether the current user can list the children of folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canListChildren;
/**
* Whether the current user can add members to this Team Drive or remove them or change their
* role.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canManageMembers;
/**
* Whether the current user can read the revisions resource of files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canReadRevisions;
/**
* Deprecated - use canDeleteChildren or canTrashChildren instead.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canRemoveChildren;
/**
* Whether the current user can rename files or folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canRename;
/**
* Whether the current user can rename this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canRenameTeamDrive;
/**
* Whether the current user can share files or folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canShare;
/**
* Whether the current user can trash children from folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canTrashChildren;
/**
* Whether the current user can add children to folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanAddChildren() {
return canAddChildren;
}
/**
* Whether the current user can add children to folders in this Team Drive.
* @param canAddChildren canAddChildren or {@code null} for none
*/
public Capabilities setCanAddChildren(java.lang.Boolean canAddChildren) {
this.canAddChildren = canAddChildren;
return this;
}
/**
* Whether the current user can change the copyRequiresWriterPermission restriction of this Team
* Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeCopyRequiresWriterPermissionRestriction() {
return canChangeCopyRequiresWriterPermissionRestriction;
}
/**
* Whether the current user can change the copyRequiresWriterPermission restriction of this Team
* Drive.
* @param canChangeCopyRequiresWriterPermissionRestriction canChangeCopyRequiresWriterPermissionRestriction or {@code null} for none
*/
public Capabilities setCanChangeCopyRequiresWriterPermissionRestriction(java.lang.Boolean canChangeCopyRequiresWriterPermissionRestriction) {
this.canChangeCopyRequiresWriterPermissionRestriction = canChangeCopyRequiresWriterPermissionRestriction;
return this;
}
/**
* Whether the current user can change the domainUsersOnly restriction of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeDomainUsersOnlyRestriction() {
return canChangeDomainUsersOnlyRestriction;
}
/**
* Whether the current user can change the domainUsersOnly restriction of this Team Drive.
* @param canChangeDomainUsersOnlyRestriction canChangeDomainUsersOnlyRestriction or {@code null} for none
*/
public Capabilities setCanChangeDomainUsersOnlyRestriction(java.lang.Boolean canChangeDomainUsersOnlyRestriction) {
this.canChangeDomainUsersOnlyRestriction = canChangeDomainUsersOnlyRestriction;
return this;
}
/**
* Whether the current user can change the background of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeTeamDriveBackground() {
return canChangeTeamDriveBackground;
}
/**
* Whether the current user can change the background of this Team Drive.
* @param canChangeTeamDriveBackground canChangeTeamDriveBackground or {@code null} for none
*/
public Capabilities setCanChangeTeamDriveBackground(java.lang.Boolean canChangeTeamDriveBackground) {
this.canChangeTeamDriveBackground = canChangeTeamDriveBackground;
return this;
}
/**
* Whether the current user can change the teamMembersOnly restriction of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeTeamMembersOnlyRestriction() {
return canChangeTeamMembersOnlyRestriction;
}
/**
* Whether the current user can change the teamMembersOnly restriction of this Team Drive.
* @param canChangeTeamMembersOnlyRestriction canChangeTeamMembersOnlyRestriction or {@code null} for none
*/
public Capabilities setCanChangeTeamMembersOnlyRestriction(java.lang.Boolean canChangeTeamMembersOnlyRestriction) {
this.canChangeTeamMembersOnlyRestriction = canChangeTeamMembersOnlyRestriction;
return this;
}
/**
* Whether the current user can comment on files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanComment() {
return canComment;
}
/**
* Whether the current user can comment on files in this Team Drive.
* @param canComment canComment or {@code null} for none
*/
public Capabilities setCanComment(java.lang.Boolean canComment) {
this.canComment = canComment;
return this;
}
/**
* Whether the current user can copy files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanCopy() {
return canCopy;
}
/**
* Whether the current user can copy files in this Team Drive.
* @param canCopy canCopy or {@code null} for none
*/
public Capabilities setCanCopy(java.lang.Boolean canCopy) {
this.canCopy = canCopy;
return this;
}
/**
* Whether the current user can delete children from folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanDeleteChildren() {
return canDeleteChildren;
}
/**
* Whether the current user can delete children from folders in this Team Drive.
* @param canDeleteChildren canDeleteChildren or {@code null} for none
*/
public Capabilities setCanDeleteChildren(java.lang.Boolean canDeleteChildren) {
this.canDeleteChildren = canDeleteChildren;
return this;
}
/**
* Whether the current user can delete this Team Drive. Attempting to delete the Team Drive may
* still fail if there are untrashed items inside the Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanDeleteTeamDrive() {
return canDeleteTeamDrive;
}
/**
* Whether the current user can delete this Team Drive. Attempting to delete the Team Drive may
* still fail if there are untrashed items inside the Team Drive.
* @param canDeleteTeamDrive canDeleteTeamDrive or {@code null} for none
*/
public Capabilities setCanDeleteTeamDrive(java.lang.Boolean canDeleteTeamDrive) {
this.canDeleteTeamDrive = canDeleteTeamDrive;
return this;
}
/**
* Whether the current user can download files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanDownload() {
return canDownload;
}
/**
* Whether the current user can download files in this Team Drive.
* @param canDownload canDownload or {@code null} for none
*/
public Capabilities setCanDownload(java.lang.Boolean canDownload) {
this.canDownload = canDownload;
return this;
}
/**
* Whether the current user can edit files in this Team Drive
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanEdit() {
return canEdit;
}
/**
* Whether the current user can edit files in this Team Drive
* @param canEdit canEdit or {@code null} for none
*/
public Capabilities setCanEdit(java.lang.Boolean canEdit) {
this.canEdit = canEdit;
return this;
}
/**
* Whether the current user can list the children of folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanListChildren() {
return canListChildren;
}
/**
* Whether the current user can list the children of folders in this Team Drive.
* @param canListChildren canListChildren or {@code null} for none
*/
public Capabilities setCanListChildren(java.lang.Boolean canListChildren) {
this.canListChildren = canListChildren;
return this;
}
/**
* Whether the current user can add members to this Team Drive or remove them or change their
* role.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanManageMembers() {
return canManageMembers;
}
/**
* Whether the current user can add members to this Team Drive or remove them or change their
* role.
* @param canManageMembers canManageMembers or {@code null} for none
*/
public Capabilities setCanManageMembers(java.lang.Boolean canManageMembers) {
this.canManageMembers = canManageMembers;
return this;
}
/**
* Whether the current user can read the revisions resource of files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanReadRevisions() {
return canReadRevisions;
}
/**
* Whether the current user can read the revisions resource of files in this Team Drive.
* @param canReadRevisions canReadRevisions or {@code null} for none
*/
public Capabilities setCanReadRevisions(java.lang.Boolean canReadRevisions) {
this.canReadRevisions = canReadRevisions;
return this;
}
/**
* Deprecated - use canDeleteChildren or canTrashChildren instead.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanRemoveChildren() {
return canRemoveChildren;
}
/**
* Deprecated - use canDeleteChildren or canTrashChildren instead.
* @param canRemoveChildren canRemoveChildren or {@code null} for none
*/
public Capabilities setCanRemoveChildren(java.lang.Boolean canRemoveChildren) {
this.canRemoveChildren = canRemoveChildren;
return this;
}
/**
* Whether the current user can rename files or folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanRename() {
return canRename;
}
/**
* Whether the current user can rename files or folders in this Team Drive.
* @param canRename canRename or {@code null} for none
*/
public Capabilities setCanRename(java.lang.Boolean canRename) {
this.canRename = canRename;
return this;
}
/**
* Whether the current user can rename this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanRenameTeamDrive() {
return canRenameTeamDrive;
}
/**
* Whether the current user can rename this Team Drive.
* @param canRenameTeamDrive canRenameTeamDrive or {@code null} for none
*/
public Capabilities setCanRenameTeamDrive(java.lang.Boolean canRenameTeamDrive) {
this.canRenameTeamDrive = canRenameTeamDrive;
return this;
}
/**
* Whether the current user can share files or folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanShare() {
return canShare;
}
/**
* Whether the current user can share files or folders in this Team Drive.
* @param canShare canShare or {@code null} for none
*/
public Capabilities setCanShare(java.lang.Boolean canShare) {
this.canShare = canShare;
return this;
}
/**
* Whether the current user can trash children from folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanTrashChildren() {
return canTrashChildren;
}
/**
* Whether the current user can trash children from folders in this Team Drive.
* @param canTrashChildren canTrashChildren or {@code null} for none
*/
public Capabilities setCanTrashChildren(java.lang.Boolean canTrashChildren) {
this.canTrashChildren = canTrashChildren;
return this;
}
@Override
public Capabilities set(String fieldName, Object value) {
return (Capabilities) super.set(fieldName, value);
}
@Override
public Capabilities clone() {
return (Capabilities) super.clone();
}
}
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
*/
public static final class Restrictions extends com.google.api.client.json.GenericJson {
/**
* Whether administrative privileges on this Team Drive are required to modify restrictions.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean adminManagedRestrictions;
/**
* Whether the options to copy, print, or download files inside this Team Drive, should be
* disabled for readers and commenters. When this restriction is set to true, it will override the
* similarly named field to true for any file inside this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean copyRequiresWriterPermission;
/**
* Whether access to this Team Drive and items inside this Team Drive is restricted to users of
* the domain to which this Team Drive belongs. This restriction may be overridden by other
* sharing policies controlled outside of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean domainUsersOnly;
/**
* Whether access to items inside this Team Drive is restricted to members of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean teamMembersOnly;
/**
* Whether administrative privileges on this Team Drive are required to modify restrictions.
* @return value or {@code null} for none
*/
public java.lang.Boolean getAdminManagedRestrictions() {
return adminManagedRestrictions;
}
/**
* Whether administrative privileges on this Team Drive are required to modify restrictions.
* @param adminManagedRestrictions adminManagedRestrictions or {@code null} for none
*/
public Restrictions setAdminManagedRestrictions(java.lang.Boolean adminManagedRestrictions) {
this.adminManagedRestrictions = adminManagedRestrictions;
return this;
}
/**
* Whether the options to copy, print, or download files inside this Team Drive, should be
* disabled for readers and commenters. When this restriction is set to true, it will override the
* similarly named field to true for any file inside this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCopyRequiresWriterPermission() {
return copyRequiresWriterPermission;
}
/**
* Whether the options to copy, print, or download files inside this Team Drive, should be
* disabled for readers and commenters. When this restriction is set to true, it will override the
* similarly named field to true for any file inside this Team Drive.
* @param copyRequiresWriterPermission copyRequiresWriterPermission or {@code null} for none
*/
public Restrictions setCopyRequiresWriterPermission(java.lang.Boolean copyRequiresWriterPermission) {
this.copyRequiresWriterPermission = copyRequiresWriterPermission;
return this;
}
/**
* Whether access to this Team Drive and items inside this Team Drive is restricted to users of
* the domain to which this Team Drive belongs. This restriction may be overridden by other
* sharing policies controlled outside of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDomainUsersOnly() {
return domainUsersOnly;
}
/**
* Whether access to this Team Drive and items inside this Team Drive is restricted to users of
* the domain to which this Team Drive belongs. This restriction may be overridden by other
* sharing policies controlled outside of this Team Drive.
* @param domainUsersOnly domainUsersOnly or {@code null} for none
*/
public Restrictions setDomainUsersOnly(java.lang.Boolean domainUsersOnly) {
this.domainUsersOnly = domainUsersOnly;
return this;
}
/**
* Whether access to items inside this Team Drive is restricted to members of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getTeamMembersOnly() {
return teamMembersOnly;
}
/**
* Whether access to items inside this Team Drive is restricted to members of this Team Drive.
* @param teamMembersOnly teamMembersOnly or {@code null} for none
*/
public Restrictions setTeamMembersOnly(java.lang.Boolean teamMembersOnly) {
this.teamMembersOnly = teamMembersOnly;
return this;
}
@Override
public Restrictions set(String fieldName, Object value) {
return (Restrictions) super.set(fieldName, value);
}
@Override
public Restrictions clone() {
return (Restrictions) super.clone();
}
}
}
|
googleapis/google-api-java-client-services | 36,603 | clients/google-api-services-drive/v3/1.28.0/com/google/api/services/drive/model/TeamDrive.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.drive.model;
/**
* Deprecated: use the drive collection instead.
*
* <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 Drive 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 TeamDrive extends com.google.api.client.json.GenericJson {
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't
* set themeId. When specified, all fields of the backgroundImageFile must be set.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private BackgroundImageFile backgroundImageFile;
/**
* A short-lived link to this Team Drive's background image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String backgroundImageLink;
/**
* Capabilities the current user has on this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Capabilities capabilities;
/**
* The color of this Team Drive as an RGB hex string. It can only be set on a
* drive.teamdrives.update request that does not set themeId.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String colorRgb;
/**
* The time at which the Team Drive was created (RFC 3339 date-time).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime createdTime;
/**
* The ID of this Team Drive which is also the ID of the top level folder of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String id;
/**
* Identifies what kind of resource this is. Value: the fixed string "drive#teamDrive".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* The name of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Restrictions restrictions;
/**
* The ID of the theme from which the background image and color will be set. The set of possible
* teamDriveThemes can be retrieved from a drive.about.get response. When not specified on a
* drive.teamdrives.create request, a random theme is chosen from which the background image and
* color are set. This is a write-only field; it can only be set on requests that don't set
* colorRgb or backgroundImageFile.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String themeId;
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't
* set themeId. When specified, all fields of the backgroundImageFile must be set.
* @return value or {@code null} for none
*/
public BackgroundImageFile getBackgroundImageFile() {
return backgroundImageFile;
}
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't
* set themeId. When specified, all fields of the backgroundImageFile must be set.
* @param backgroundImageFile backgroundImageFile or {@code null} for none
*/
public TeamDrive setBackgroundImageFile(BackgroundImageFile backgroundImageFile) {
this.backgroundImageFile = backgroundImageFile;
return this;
}
/**
* A short-lived link to this Team Drive's background image.
* @return value or {@code null} for none
*/
public java.lang.String getBackgroundImageLink() {
return backgroundImageLink;
}
/**
* A short-lived link to this Team Drive's background image.
* @param backgroundImageLink backgroundImageLink or {@code null} for none
*/
public TeamDrive setBackgroundImageLink(java.lang.String backgroundImageLink) {
this.backgroundImageLink = backgroundImageLink;
return this;
}
/**
* Capabilities the current user has on this Team Drive.
* @return value or {@code null} for none
*/
public Capabilities getCapabilities() {
return capabilities;
}
/**
* Capabilities the current user has on this Team Drive.
* @param capabilities capabilities or {@code null} for none
*/
public TeamDrive setCapabilities(Capabilities capabilities) {
this.capabilities = capabilities;
return this;
}
/**
* The color of this Team Drive as an RGB hex string. It can only be set on a
* drive.teamdrives.update request that does not set themeId.
* @return value or {@code null} for none
*/
public java.lang.String getColorRgb() {
return colorRgb;
}
/**
* The color of this Team Drive as an RGB hex string. It can only be set on a
* drive.teamdrives.update request that does not set themeId.
* @param colorRgb colorRgb or {@code null} for none
*/
public TeamDrive setColorRgb(java.lang.String colorRgb) {
this.colorRgb = colorRgb;
return this;
}
/**
* The time at which the Team Drive was created (RFC 3339 date-time).
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getCreatedTime() {
return createdTime;
}
/**
* The time at which the Team Drive was created (RFC 3339 date-time).
* @param createdTime createdTime or {@code null} for none
*/
public TeamDrive setCreatedTime(com.google.api.client.util.DateTime createdTime) {
this.createdTime = createdTime;
return this;
}
/**
* The ID of this Team Drive which is also the ID of the top level folder of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.String getId() {
return id;
}
/**
* The ID of this Team Drive which is also the ID of the top level folder of this Team Drive.
* @param id id or {@code null} for none
*/
public TeamDrive setId(java.lang.String id) {
this.id = id;
return this;
}
/**
* Identifies what kind of resource this is. Value: the fixed string "drive#teamDrive".
* @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 "drive#teamDrive".
* @param kind kind or {@code null} for none
*/
public TeamDrive setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* The name of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* The name of this Team Drive.
* @param name name or {@code null} for none
*/
public TeamDrive setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
* @return value or {@code null} for none
*/
public Restrictions getRestrictions() {
return restrictions;
}
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
* @param restrictions restrictions or {@code null} for none
*/
public TeamDrive setRestrictions(Restrictions restrictions) {
this.restrictions = restrictions;
return this;
}
/**
* The ID of the theme from which the background image and color will be set. The set of possible
* teamDriveThemes can be retrieved from a drive.about.get response. When not specified on a
* drive.teamdrives.create request, a random theme is chosen from which the background image and
* color are set. This is a write-only field; it can only be set on requests that don't set
* colorRgb or backgroundImageFile.
* @return value or {@code null} for none
*/
public java.lang.String getThemeId() {
return themeId;
}
/**
* The ID of the theme from which the background image and color will be set. The set of possible
* teamDriveThemes can be retrieved from a drive.about.get response. When not specified on a
* drive.teamdrives.create request, a random theme is chosen from which the background image and
* color are set. This is a write-only field; it can only be set on requests that don't set
* colorRgb or backgroundImageFile.
* @param themeId themeId or {@code null} for none
*/
public TeamDrive setThemeId(java.lang.String themeId) {
this.themeId = themeId;
return this;
}
@Override
public TeamDrive set(String fieldName, Object value) {
return (TeamDrive) super.set(fieldName, value);
}
@Override
public TeamDrive clone() {
return (TeamDrive) super.clone();
}
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't set
* themeId. When specified, all fields of the backgroundImageFile must be set.
*/
public static final class BackgroundImageFile extends com.google.api.client.json.GenericJson {
/**
* The ID of an image file in Drive to use for the background image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String id;
/**
* The width of the cropped image in the closed range of 0 to 1. This value represents the width
* of the cropped image divided by the width of the entire image. The height is computed by
* applying a width to height aspect ratio of 80 to 9. The resulting image must be at least 1280
* pixels wide and 144 pixels high.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Float width;
/**
* The X coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the horizontal distance from the
* left side of the entire image to the left side of the cropping area divided by the width of the
* entire image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Float xCoordinate;
/**
* The Y coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the vertical distance from the top
* side of the entire image to the top side of the cropping area divided by the height of the
* entire image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Float yCoordinate;
/**
* The ID of an image file in Drive to use for the background image.
* @return value or {@code null} for none
*/
public java.lang.String getId() {
return id;
}
/**
* The ID of an image file in Drive to use for the background image.
* @param id id or {@code null} for none
*/
public BackgroundImageFile setId(java.lang.String id) {
this.id = id;
return this;
}
/**
* The width of the cropped image in the closed range of 0 to 1. This value represents the width
* of the cropped image divided by the width of the entire image. The height is computed by
* applying a width to height aspect ratio of 80 to 9. The resulting image must be at least 1280
* pixels wide and 144 pixels high.
* @return value or {@code null} for none
*/
public java.lang.Float getWidth() {
return width;
}
/**
* The width of the cropped image in the closed range of 0 to 1. This value represents the width
* of the cropped image divided by the width of the entire image. The height is computed by
* applying a width to height aspect ratio of 80 to 9. The resulting image must be at least 1280
* pixels wide and 144 pixels high.
* @param width width or {@code null} for none
*/
public BackgroundImageFile setWidth(java.lang.Float width) {
this.width = width;
return this;
}
/**
* The X coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the horizontal distance from the
* left side of the entire image to the left side of the cropping area divided by the width of the
* entire image.
* @return value or {@code null} for none
*/
public java.lang.Float getXCoordinate() {
return xCoordinate;
}
/**
* The X coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the horizontal distance from the
* left side of the entire image to the left side of the cropping area divided by the width of the
* entire image.
* @param xCoordinate xCoordinate or {@code null} for none
*/
public BackgroundImageFile setXCoordinate(java.lang.Float xCoordinate) {
this.xCoordinate = xCoordinate;
return this;
}
/**
* The Y coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the vertical distance from the top
* side of the entire image to the top side of the cropping area divided by the height of the
* entire image.
* @return value or {@code null} for none
*/
public java.lang.Float getYCoordinate() {
return yCoordinate;
}
/**
* The Y coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the vertical distance from the top
* side of the entire image to the top side of the cropping area divided by the height of the
* entire image.
* @param yCoordinate yCoordinate or {@code null} for none
*/
public BackgroundImageFile setYCoordinate(java.lang.Float yCoordinate) {
this.yCoordinate = yCoordinate;
return this;
}
@Override
public BackgroundImageFile set(String fieldName, Object value) {
return (BackgroundImageFile) super.set(fieldName, value);
}
@Override
public BackgroundImageFile clone() {
return (BackgroundImageFile) super.clone();
}
}
/**
* Capabilities the current user has on this Team Drive.
*/
public static final class Capabilities extends com.google.api.client.json.GenericJson {
/**
* Whether the current user can add children to folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canAddChildren;
/**
* Whether the current user can change the copyRequiresWriterPermission restriction of this Team
* Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeCopyRequiresWriterPermissionRestriction;
/**
* Whether the current user can change the domainUsersOnly restriction of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeDomainUsersOnlyRestriction;
/**
* Whether the current user can change the background of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeTeamDriveBackground;
/**
* Whether the current user can change the teamMembersOnly restriction of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeTeamMembersOnlyRestriction;
/**
* Whether the current user can comment on files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canComment;
/**
* Whether the current user can copy files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canCopy;
/**
* Whether the current user can delete children from folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canDeleteChildren;
/**
* Whether the current user can delete this Team Drive. Attempting to delete the Team Drive may
* still fail if there are untrashed items inside the Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canDeleteTeamDrive;
/**
* Whether the current user can download files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canDownload;
/**
* Whether the current user can edit files in this Team Drive
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canEdit;
/**
* Whether the current user can list the children of folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canListChildren;
/**
* Whether the current user can add members to this Team Drive or remove them or change their
* role.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canManageMembers;
/**
* Whether the current user can read the revisions resource of files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canReadRevisions;
/**
* Deprecated - use canDeleteChildren or canTrashChildren instead.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canRemoveChildren;
/**
* Whether the current user can rename files or folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canRename;
/**
* Whether the current user can rename this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canRenameTeamDrive;
/**
* Whether the current user can share files or folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canShare;
/**
* Whether the current user can trash children from folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canTrashChildren;
/**
* Whether the current user can add children to folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanAddChildren() {
return canAddChildren;
}
/**
* Whether the current user can add children to folders in this Team Drive.
* @param canAddChildren canAddChildren or {@code null} for none
*/
public Capabilities setCanAddChildren(java.lang.Boolean canAddChildren) {
this.canAddChildren = canAddChildren;
return this;
}
/**
* Whether the current user can change the copyRequiresWriterPermission restriction of this Team
* Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeCopyRequiresWriterPermissionRestriction() {
return canChangeCopyRequiresWriterPermissionRestriction;
}
/**
* Whether the current user can change the copyRequiresWriterPermission restriction of this Team
* Drive.
* @param canChangeCopyRequiresWriterPermissionRestriction canChangeCopyRequiresWriterPermissionRestriction or {@code null} for none
*/
public Capabilities setCanChangeCopyRequiresWriterPermissionRestriction(java.lang.Boolean canChangeCopyRequiresWriterPermissionRestriction) {
this.canChangeCopyRequiresWriterPermissionRestriction = canChangeCopyRequiresWriterPermissionRestriction;
return this;
}
/**
* Whether the current user can change the domainUsersOnly restriction of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeDomainUsersOnlyRestriction() {
return canChangeDomainUsersOnlyRestriction;
}
/**
* Whether the current user can change the domainUsersOnly restriction of this Team Drive.
* @param canChangeDomainUsersOnlyRestriction canChangeDomainUsersOnlyRestriction or {@code null} for none
*/
public Capabilities setCanChangeDomainUsersOnlyRestriction(java.lang.Boolean canChangeDomainUsersOnlyRestriction) {
this.canChangeDomainUsersOnlyRestriction = canChangeDomainUsersOnlyRestriction;
return this;
}
/**
* Whether the current user can change the background of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeTeamDriveBackground() {
return canChangeTeamDriveBackground;
}
/**
* Whether the current user can change the background of this Team Drive.
* @param canChangeTeamDriveBackground canChangeTeamDriveBackground or {@code null} for none
*/
public Capabilities setCanChangeTeamDriveBackground(java.lang.Boolean canChangeTeamDriveBackground) {
this.canChangeTeamDriveBackground = canChangeTeamDriveBackground;
return this;
}
/**
* Whether the current user can change the teamMembersOnly restriction of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeTeamMembersOnlyRestriction() {
return canChangeTeamMembersOnlyRestriction;
}
/**
* Whether the current user can change the teamMembersOnly restriction of this Team Drive.
* @param canChangeTeamMembersOnlyRestriction canChangeTeamMembersOnlyRestriction or {@code null} for none
*/
public Capabilities setCanChangeTeamMembersOnlyRestriction(java.lang.Boolean canChangeTeamMembersOnlyRestriction) {
this.canChangeTeamMembersOnlyRestriction = canChangeTeamMembersOnlyRestriction;
return this;
}
/**
* Whether the current user can comment on files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanComment() {
return canComment;
}
/**
* Whether the current user can comment on files in this Team Drive.
* @param canComment canComment or {@code null} for none
*/
public Capabilities setCanComment(java.lang.Boolean canComment) {
this.canComment = canComment;
return this;
}
/**
* Whether the current user can copy files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanCopy() {
return canCopy;
}
/**
* Whether the current user can copy files in this Team Drive.
* @param canCopy canCopy or {@code null} for none
*/
public Capabilities setCanCopy(java.lang.Boolean canCopy) {
this.canCopy = canCopy;
return this;
}
/**
* Whether the current user can delete children from folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanDeleteChildren() {
return canDeleteChildren;
}
/**
* Whether the current user can delete children from folders in this Team Drive.
* @param canDeleteChildren canDeleteChildren or {@code null} for none
*/
public Capabilities setCanDeleteChildren(java.lang.Boolean canDeleteChildren) {
this.canDeleteChildren = canDeleteChildren;
return this;
}
/**
* Whether the current user can delete this Team Drive. Attempting to delete the Team Drive may
* still fail if there are untrashed items inside the Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanDeleteTeamDrive() {
return canDeleteTeamDrive;
}
/**
* Whether the current user can delete this Team Drive. Attempting to delete the Team Drive may
* still fail if there are untrashed items inside the Team Drive.
* @param canDeleteTeamDrive canDeleteTeamDrive or {@code null} for none
*/
public Capabilities setCanDeleteTeamDrive(java.lang.Boolean canDeleteTeamDrive) {
this.canDeleteTeamDrive = canDeleteTeamDrive;
return this;
}
/**
* Whether the current user can download files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanDownload() {
return canDownload;
}
/**
* Whether the current user can download files in this Team Drive.
* @param canDownload canDownload or {@code null} for none
*/
public Capabilities setCanDownload(java.lang.Boolean canDownload) {
this.canDownload = canDownload;
return this;
}
/**
* Whether the current user can edit files in this Team Drive
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanEdit() {
return canEdit;
}
/**
* Whether the current user can edit files in this Team Drive
* @param canEdit canEdit or {@code null} for none
*/
public Capabilities setCanEdit(java.lang.Boolean canEdit) {
this.canEdit = canEdit;
return this;
}
/**
* Whether the current user can list the children of folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanListChildren() {
return canListChildren;
}
/**
* Whether the current user can list the children of folders in this Team Drive.
* @param canListChildren canListChildren or {@code null} for none
*/
public Capabilities setCanListChildren(java.lang.Boolean canListChildren) {
this.canListChildren = canListChildren;
return this;
}
/**
* Whether the current user can add members to this Team Drive or remove them or change their
* role.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanManageMembers() {
return canManageMembers;
}
/**
* Whether the current user can add members to this Team Drive or remove them or change their
* role.
* @param canManageMembers canManageMembers or {@code null} for none
*/
public Capabilities setCanManageMembers(java.lang.Boolean canManageMembers) {
this.canManageMembers = canManageMembers;
return this;
}
/**
* Whether the current user can read the revisions resource of files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanReadRevisions() {
return canReadRevisions;
}
/**
* Whether the current user can read the revisions resource of files in this Team Drive.
* @param canReadRevisions canReadRevisions or {@code null} for none
*/
public Capabilities setCanReadRevisions(java.lang.Boolean canReadRevisions) {
this.canReadRevisions = canReadRevisions;
return this;
}
/**
* Deprecated - use canDeleteChildren or canTrashChildren instead.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanRemoveChildren() {
return canRemoveChildren;
}
/**
* Deprecated - use canDeleteChildren or canTrashChildren instead.
* @param canRemoveChildren canRemoveChildren or {@code null} for none
*/
public Capabilities setCanRemoveChildren(java.lang.Boolean canRemoveChildren) {
this.canRemoveChildren = canRemoveChildren;
return this;
}
/**
* Whether the current user can rename files or folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanRename() {
return canRename;
}
/**
* Whether the current user can rename files or folders in this Team Drive.
* @param canRename canRename or {@code null} for none
*/
public Capabilities setCanRename(java.lang.Boolean canRename) {
this.canRename = canRename;
return this;
}
/**
* Whether the current user can rename this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanRenameTeamDrive() {
return canRenameTeamDrive;
}
/**
* Whether the current user can rename this Team Drive.
* @param canRenameTeamDrive canRenameTeamDrive or {@code null} for none
*/
public Capabilities setCanRenameTeamDrive(java.lang.Boolean canRenameTeamDrive) {
this.canRenameTeamDrive = canRenameTeamDrive;
return this;
}
/**
* Whether the current user can share files or folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanShare() {
return canShare;
}
/**
* Whether the current user can share files or folders in this Team Drive.
* @param canShare canShare or {@code null} for none
*/
public Capabilities setCanShare(java.lang.Boolean canShare) {
this.canShare = canShare;
return this;
}
/**
* Whether the current user can trash children from folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanTrashChildren() {
return canTrashChildren;
}
/**
* Whether the current user can trash children from folders in this Team Drive.
* @param canTrashChildren canTrashChildren or {@code null} for none
*/
public Capabilities setCanTrashChildren(java.lang.Boolean canTrashChildren) {
this.canTrashChildren = canTrashChildren;
return this;
}
@Override
public Capabilities set(String fieldName, Object value) {
return (Capabilities) super.set(fieldName, value);
}
@Override
public Capabilities clone() {
return (Capabilities) super.clone();
}
}
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
*/
public static final class Restrictions extends com.google.api.client.json.GenericJson {
/**
* Whether administrative privileges on this Team Drive are required to modify restrictions.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean adminManagedRestrictions;
/**
* Whether the options to copy, print, or download files inside this Team Drive, should be
* disabled for readers and commenters. When this restriction is set to true, it will override the
* similarly named field to true for any file inside this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean copyRequiresWriterPermission;
/**
* Whether access to this Team Drive and items inside this Team Drive is restricted to users of
* the domain to which this Team Drive belongs. This restriction may be overridden by other
* sharing policies controlled outside of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean domainUsersOnly;
/**
* Whether access to items inside this Team Drive is restricted to members of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean teamMembersOnly;
/**
* Whether administrative privileges on this Team Drive are required to modify restrictions.
* @return value or {@code null} for none
*/
public java.lang.Boolean getAdminManagedRestrictions() {
return adminManagedRestrictions;
}
/**
* Whether administrative privileges on this Team Drive are required to modify restrictions.
* @param adminManagedRestrictions adminManagedRestrictions or {@code null} for none
*/
public Restrictions setAdminManagedRestrictions(java.lang.Boolean adminManagedRestrictions) {
this.adminManagedRestrictions = adminManagedRestrictions;
return this;
}
/**
* Whether the options to copy, print, or download files inside this Team Drive, should be
* disabled for readers and commenters. When this restriction is set to true, it will override the
* similarly named field to true for any file inside this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCopyRequiresWriterPermission() {
return copyRequiresWriterPermission;
}
/**
* Whether the options to copy, print, or download files inside this Team Drive, should be
* disabled for readers and commenters. When this restriction is set to true, it will override the
* similarly named field to true for any file inside this Team Drive.
* @param copyRequiresWriterPermission copyRequiresWriterPermission or {@code null} for none
*/
public Restrictions setCopyRequiresWriterPermission(java.lang.Boolean copyRequiresWriterPermission) {
this.copyRequiresWriterPermission = copyRequiresWriterPermission;
return this;
}
/**
* Whether access to this Team Drive and items inside this Team Drive is restricted to users of
* the domain to which this Team Drive belongs. This restriction may be overridden by other
* sharing policies controlled outside of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDomainUsersOnly() {
return domainUsersOnly;
}
/**
* Whether access to this Team Drive and items inside this Team Drive is restricted to users of
* the domain to which this Team Drive belongs. This restriction may be overridden by other
* sharing policies controlled outside of this Team Drive.
* @param domainUsersOnly domainUsersOnly or {@code null} for none
*/
public Restrictions setDomainUsersOnly(java.lang.Boolean domainUsersOnly) {
this.domainUsersOnly = domainUsersOnly;
return this;
}
/**
* Whether access to items inside this Team Drive is restricted to members of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getTeamMembersOnly() {
return teamMembersOnly;
}
/**
* Whether access to items inside this Team Drive is restricted to members of this Team Drive.
* @param teamMembersOnly teamMembersOnly or {@code null} for none
*/
public Restrictions setTeamMembersOnly(java.lang.Boolean teamMembersOnly) {
this.teamMembersOnly = teamMembersOnly;
return this;
}
@Override
public Restrictions set(String fieldName, Object value) {
return (Restrictions) super.set(fieldName, value);
}
@Override
public Restrictions clone() {
return (Restrictions) super.clone();
}
}
}
|
googleapis/google-api-java-client-services | 36,603 | clients/google-api-services-drive/v3/1.29.2/com/google/api/services/drive/model/TeamDrive.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.drive.model;
/**
* Deprecated: use the drive collection instead.
*
* <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 Drive 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 TeamDrive extends com.google.api.client.json.GenericJson {
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't
* set themeId. When specified, all fields of the backgroundImageFile must be set.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private BackgroundImageFile backgroundImageFile;
/**
* A short-lived link to this Team Drive's background image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String backgroundImageLink;
/**
* Capabilities the current user has on this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Capabilities capabilities;
/**
* The color of this Team Drive as an RGB hex string. It can only be set on a
* drive.teamdrives.update request that does not set themeId.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String colorRgb;
/**
* The time at which the Team Drive was created (RFC 3339 date-time).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime createdTime;
/**
* The ID of this Team Drive which is also the ID of the top level folder of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String id;
/**
* Identifies what kind of resource this is. Value: the fixed string "drive#teamDrive".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* The name of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Restrictions restrictions;
/**
* The ID of the theme from which the background image and color will be set. The set of possible
* teamDriveThemes can be retrieved from a drive.about.get response. When not specified on a
* drive.teamdrives.create request, a random theme is chosen from which the background image and
* color are set. This is a write-only field; it can only be set on requests that don't set
* colorRgb or backgroundImageFile.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String themeId;
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't
* set themeId. When specified, all fields of the backgroundImageFile must be set.
* @return value or {@code null} for none
*/
public BackgroundImageFile getBackgroundImageFile() {
return backgroundImageFile;
}
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't
* set themeId. When specified, all fields of the backgroundImageFile must be set.
* @param backgroundImageFile backgroundImageFile or {@code null} for none
*/
public TeamDrive setBackgroundImageFile(BackgroundImageFile backgroundImageFile) {
this.backgroundImageFile = backgroundImageFile;
return this;
}
/**
* A short-lived link to this Team Drive's background image.
* @return value or {@code null} for none
*/
public java.lang.String getBackgroundImageLink() {
return backgroundImageLink;
}
/**
* A short-lived link to this Team Drive's background image.
* @param backgroundImageLink backgroundImageLink or {@code null} for none
*/
public TeamDrive setBackgroundImageLink(java.lang.String backgroundImageLink) {
this.backgroundImageLink = backgroundImageLink;
return this;
}
/**
* Capabilities the current user has on this Team Drive.
* @return value or {@code null} for none
*/
public Capabilities getCapabilities() {
return capabilities;
}
/**
* Capabilities the current user has on this Team Drive.
* @param capabilities capabilities or {@code null} for none
*/
public TeamDrive setCapabilities(Capabilities capabilities) {
this.capabilities = capabilities;
return this;
}
/**
* The color of this Team Drive as an RGB hex string. It can only be set on a
* drive.teamdrives.update request that does not set themeId.
* @return value or {@code null} for none
*/
public java.lang.String getColorRgb() {
return colorRgb;
}
/**
* The color of this Team Drive as an RGB hex string. It can only be set on a
* drive.teamdrives.update request that does not set themeId.
* @param colorRgb colorRgb or {@code null} for none
*/
public TeamDrive setColorRgb(java.lang.String colorRgb) {
this.colorRgb = colorRgb;
return this;
}
/**
* The time at which the Team Drive was created (RFC 3339 date-time).
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getCreatedTime() {
return createdTime;
}
/**
* The time at which the Team Drive was created (RFC 3339 date-time).
* @param createdTime createdTime or {@code null} for none
*/
public TeamDrive setCreatedTime(com.google.api.client.util.DateTime createdTime) {
this.createdTime = createdTime;
return this;
}
/**
* The ID of this Team Drive which is also the ID of the top level folder of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.String getId() {
return id;
}
/**
* The ID of this Team Drive which is also the ID of the top level folder of this Team Drive.
* @param id id or {@code null} for none
*/
public TeamDrive setId(java.lang.String id) {
this.id = id;
return this;
}
/**
* Identifies what kind of resource this is. Value: the fixed string "drive#teamDrive".
* @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 "drive#teamDrive".
* @param kind kind or {@code null} for none
*/
public TeamDrive setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* The name of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* The name of this Team Drive.
* @param name name or {@code null} for none
*/
public TeamDrive setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
* @return value or {@code null} for none
*/
public Restrictions getRestrictions() {
return restrictions;
}
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
* @param restrictions restrictions or {@code null} for none
*/
public TeamDrive setRestrictions(Restrictions restrictions) {
this.restrictions = restrictions;
return this;
}
/**
* The ID of the theme from which the background image and color will be set. The set of possible
* teamDriveThemes can be retrieved from a drive.about.get response. When not specified on a
* drive.teamdrives.create request, a random theme is chosen from which the background image and
* color are set. This is a write-only field; it can only be set on requests that don't set
* colorRgb or backgroundImageFile.
* @return value or {@code null} for none
*/
public java.lang.String getThemeId() {
return themeId;
}
/**
* The ID of the theme from which the background image and color will be set. The set of possible
* teamDriveThemes can be retrieved from a drive.about.get response. When not specified on a
* drive.teamdrives.create request, a random theme is chosen from which the background image and
* color are set. This is a write-only field; it can only be set on requests that don't set
* colorRgb or backgroundImageFile.
* @param themeId themeId or {@code null} for none
*/
public TeamDrive setThemeId(java.lang.String themeId) {
this.themeId = themeId;
return this;
}
@Override
public TeamDrive set(String fieldName, Object value) {
return (TeamDrive) super.set(fieldName, value);
}
@Override
public TeamDrive clone() {
return (TeamDrive) super.clone();
}
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't set
* themeId. When specified, all fields of the backgroundImageFile must be set.
*/
public static final class BackgroundImageFile extends com.google.api.client.json.GenericJson {
/**
* The ID of an image file in Drive to use for the background image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String id;
/**
* The width of the cropped image in the closed range of 0 to 1. This value represents the width
* of the cropped image divided by the width of the entire image. The height is computed by
* applying a width to height aspect ratio of 80 to 9. The resulting image must be at least 1280
* pixels wide and 144 pixels high.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Float width;
/**
* The X coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the horizontal distance from the
* left side of the entire image to the left side of the cropping area divided by the width of the
* entire image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Float xCoordinate;
/**
* The Y coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the vertical distance from the top
* side of the entire image to the top side of the cropping area divided by the height of the
* entire image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Float yCoordinate;
/**
* The ID of an image file in Drive to use for the background image.
* @return value or {@code null} for none
*/
public java.lang.String getId() {
return id;
}
/**
* The ID of an image file in Drive to use for the background image.
* @param id id or {@code null} for none
*/
public BackgroundImageFile setId(java.lang.String id) {
this.id = id;
return this;
}
/**
* The width of the cropped image in the closed range of 0 to 1. This value represents the width
* of the cropped image divided by the width of the entire image. The height is computed by
* applying a width to height aspect ratio of 80 to 9. The resulting image must be at least 1280
* pixels wide and 144 pixels high.
* @return value or {@code null} for none
*/
public java.lang.Float getWidth() {
return width;
}
/**
* The width of the cropped image in the closed range of 0 to 1. This value represents the width
* of the cropped image divided by the width of the entire image. The height is computed by
* applying a width to height aspect ratio of 80 to 9. The resulting image must be at least 1280
* pixels wide and 144 pixels high.
* @param width width or {@code null} for none
*/
public BackgroundImageFile setWidth(java.lang.Float width) {
this.width = width;
return this;
}
/**
* The X coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the horizontal distance from the
* left side of the entire image to the left side of the cropping area divided by the width of the
* entire image.
* @return value or {@code null} for none
*/
public java.lang.Float getXCoordinate() {
return xCoordinate;
}
/**
* The X coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the horizontal distance from the
* left side of the entire image to the left side of the cropping area divided by the width of the
* entire image.
* @param xCoordinate xCoordinate or {@code null} for none
*/
public BackgroundImageFile setXCoordinate(java.lang.Float xCoordinate) {
this.xCoordinate = xCoordinate;
return this;
}
/**
* The Y coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the vertical distance from the top
* side of the entire image to the top side of the cropping area divided by the height of the
* entire image.
* @return value or {@code null} for none
*/
public java.lang.Float getYCoordinate() {
return yCoordinate;
}
/**
* The Y coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the vertical distance from the top
* side of the entire image to the top side of the cropping area divided by the height of the
* entire image.
* @param yCoordinate yCoordinate or {@code null} for none
*/
public BackgroundImageFile setYCoordinate(java.lang.Float yCoordinate) {
this.yCoordinate = yCoordinate;
return this;
}
@Override
public BackgroundImageFile set(String fieldName, Object value) {
return (BackgroundImageFile) super.set(fieldName, value);
}
@Override
public BackgroundImageFile clone() {
return (BackgroundImageFile) super.clone();
}
}
/**
* Capabilities the current user has on this Team Drive.
*/
public static final class Capabilities extends com.google.api.client.json.GenericJson {
/**
* Whether the current user can add children to folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canAddChildren;
/**
* Whether the current user can change the copyRequiresWriterPermission restriction of this Team
* Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeCopyRequiresWriterPermissionRestriction;
/**
* Whether the current user can change the domainUsersOnly restriction of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeDomainUsersOnlyRestriction;
/**
* Whether the current user can change the background of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeTeamDriveBackground;
/**
* Whether the current user can change the teamMembersOnly restriction of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeTeamMembersOnlyRestriction;
/**
* Whether the current user can comment on files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canComment;
/**
* Whether the current user can copy files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canCopy;
/**
* Whether the current user can delete children from folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canDeleteChildren;
/**
* Whether the current user can delete this Team Drive. Attempting to delete the Team Drive may
* still fail if there are untrashed items inside the Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canDeleteTeamDrive;
/**
* Whether the current user can download files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canDownload;
/**
* Whether the current user can edit files in this Team Drive
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canEdit;
/**
* Whether the current user can list the children of folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canListChildren;
/**
* Whether the current user can add members to this Team Drive or remove them or change their
* role.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canManageMembers;
/**
* Whether the current user can read the revisions resource of files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canReadRevisions;
/**
* Deprecated - use canDeleteChildren or canTrashChildren instead.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canRemoveChildren;
/**
* Whether the current user can rename files or folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canRename;
/**
* Whether the current user can rename this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canRenameTeamDrive;
/**
* Whether the current user can share files or folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canShare;
/**
* Whether the current user can trash children from folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canTrashChildren;
/**
* Whether the current user can add children to folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanAddChildren() {
return canAddChildren;
}
/**
* Whether the current user can add children to folders in this Team Drive.
* @param canAddChildren canAddChildren or {@code null} for none
*/
public Capabilities setCanAddChildren(java.lang.Boolean canAddChildren) {
this.canAddChildren = canAddChildren;
return this;
}
/**
* Whether the current user can change the copyRequiresWriterPermission restriction of this Team
* Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeCopyRequiresWriterPermissionRestriction() {
return canChangeCopyRequiresWriterPermissionRestriction;
}
/**
* Whether the current user can change the copyRequiresWriterPermission restriction of this Team
* Drive.
* @param canChangeCopyRequiresWriterPermissionRestriction canChangeCopyRequiresWriterPermissionRestriction or {@code null} for none
*/
public Capabilities setCanChangeCopyRequiresWriterPermissionRestriction(java.lang.Boolean canChangeCopyRequiresWriterPermissionRestriction) {
this.canChangeCopyRequiresWriterPermissionRestriction = canChangeCopyRequiresWriterPermissionRestriction;
return this;
}
/**
* Whether the current user can change the domainUsersOnly restriction of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeDomainUsersOnlyRestriction() {
return canChangeDomainUsersOnlyRestriction;
}
/**
* Whether the current user can change the domainUsersOnly restriction of this Team Drive.
* @param canChangeDomainUsersOnlyRestriction canChangeDomainUsersOnlyRestriction or {@code null} for none
*/
public Capabilities setCanChangeDomainUsersOnlyRestriction(java.lang.Boolean canChangeDomainUsersOnlyRestriction) {
this.canChangeDomainUsersOnlyRestriction = canChangeDomainUsersOnlyRestriction;
return this;
}
/**
* Whether the current user can change the background of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeTeamDriveBackground() {
return canChangeTeamDriveBackground;
}
/**
* Whether the current user can change the background of this Team Drive.
* @param canChangeTeamDriveBackground canChangeTeamDriveBackground or {@code null} for none
*/
public Capabilities setCanChangeTeamDriveBackground(java.lang.Boolean canChangeTeamDriveBackground) {
this.canChangeTeamDriveBackground = canChangeTeamDriveBackground;
return this;
}
/**
* Whether the current user can change the teamMembersOnly restriction of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeTeamMembersOnlyRestriction() {
return canChangeTeamMembersOnlyRestriction;
}
/**
* Whether the current user can change the teamMembersOnly restriction of this Team Drive.
* @param canChangeTeamMembersOnlyRestriction canChangeTeamMembersOnlyRestriction or {@code null} for none
*/
public Capabilities setCanChangeTeamMembersOnlyRestriction(java.lang.Boolean canChangeTeamMembersOnlyRestriction) {
this.canChangeTeamMembersOnlyRestriction = canChangeTeamMembersOnlyRestriction;
return this;
}
/**
* Whether the current user can comment on files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanComment() {
return canComment;
}
/**
* Whether the current user can comment on files in this Team Drive.
* @param canComment canComment or {@code null} for none
*/
public Capabilities setCanComment(java.lang.Boolean canComment) {
this.canComment = canComment;
return this;
}
/**
* Whether the current user can copy files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanCopy() {
return canCopy;
}
/**
* Whether the current user can copy files in this Team Drive.
* @param canCopy canCopy or {@code null} for none
*/
public Capabilities setCanCopy(java.lang.Boolean canCopy) {
this.canCopy = canCopy;
return this;
}
/**
* Whether the current user can delete children from folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanDeleteChildren() {
return canDeleteChildren;
}
/**
* Whether the current user can delete children from folders in this Team Drive.
* @param canDeleteChildren canDeleteChildren or {@code null} for none
*/
public Capabilities setCanDeleteChildren(java.lang.Boolean canDeleteChildren) {
this.canDeleteChildren = canDeleteChildren;
return this;
}
/**
* Whether the current user can delete this Team Drive. Attempting to delete the Team Drive may
* still fail if there are untrashed items inside the Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanDeleteTeamDrive() {
return canDeleteTeamDrive;
}
/**
* Whether the current user can delete this Team Drive. Attempting to delete the Team Drive may
* still fail if there are untrashed items inside the Team Drive.
* @param canDeleteTeamDrive canDeleteTeamDrive or {@code null} for none
*/
public Capabilities setCanDeleteTeamDrive(java.lang.Boolean canDeleteTeamDrive) {
this.canDeleteTeamDrive = canDeleteTeamDrive;
return this;
}
/**
* Whether the current user can download files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanDownload() {
return canDownload;
}
/**
* Whether the current user can download files in this Team Drive.
* @param canDownload canDownload or {@code null} for none
*/
public Capabilities setCanDownload(java.lang.Boolean canDownload) {
this.canDownload = canDownload;
return this;
}
/**
* Whether the current user can edit files in this Team Drive
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanEdit() {
return canEdit;
}
/**
* Whether the current user can edit files in this Team Drive
* @param canEdit canEdit or {@code null} for none
*/
public Capabilities setCanEdit(java.lang.Boolean canEdit) {
this.canEdit = canEdit;
return this;
}
/**
* Whether the current user can list the children of folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanListChildren() {
return canListChildren;
}
/**
* Whether the current user can list the children of folders in this Team Drive.
* @param canListChildren canListChildren or {@code null} for none
*/
public Capabilities setCanListChildren(java.lang.Boolean canListChildren) {
this.canListChildren = canListChildren;
return this;
}
/**
* Whether the current user can add members to this Team Drive or remove them or change their
* role.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanManageMembers() {
return canManageMembers;
}
/**
* Whether the current user can add members to this Team Drive or remove them or change their
* role.
* @param canManageMembers canManageMembers or {@code null} for none
*/
public Capabilities setCanManageMembers(java.lang.Boolean canManageMembers) {
this.canManageMembers = canManageMembers;
return this;
}
/**
* Whether the current user can read the revisions resource of files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanReadRevisions() {
return canReadRevisions;
}
/**
* Whether the current user can read the revisions resource of files in this Team Drive.
* @param canReadRevisions canReadRevisions or {@code null} for none
*/
public Capabilities setCanReadRevisions(java.lang.Boolean canReadRevisions) {
this.canReadRevisions = canReadRevisions;
return this;
}
/**
* Deprecated - use canDeleteChildren or canTrashChildren instead.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanRemoveChildren() {
return canRemoveChildren;
}
/**
* Deprecated - use canDeleteChildren or canTrashChildren instead.
* @param canRemoveChildren canRemoveChildren or {@code null} for none
*/
public Capabilities setCanRemoveChildren(java.lang.Boolean canRemoveChildren) {
this.canRemoveChildren = canRemoveChildren;
return this;
}
/**
* Whether the current user can rename files or folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanRename() {
return canRename;
}
/**
* Whether the current user can rename files or folders in this Team Drive.
* @param canRename canRename or {@code null} for none
*/
public Capabilities setCanRename(java.lang.Boolean canRename) {
this.canRename = canRename;
return this;
}
/**
* Whether the current user can rename this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanRenameTeamDrive() {
return canRenameTeamDrive;
}
/**
* Whether the current user can rename this Team Drive.
* @param canRenameTeamDrive canRenameTeamDrive or {@code null} for none
*/
public Capabilities setCanRenameTeamDrive(java.lang.Boolean canRenameTeamDrive) {
this.canRenameTeamDrive = canRenameTeamDrive;
return this;
}
/**
* Whether the current user can share files or folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanShare() {
return canShare;
}
/**
* Whether the current user can share files or folders in this Team Drive.
* @param canShare canShare or {@code null} for none
*/
public Capabilities setCanShare(java.lang.Boolean canShare) {
this.canShare = canShare;
return this;
}
/**
* Whether the current user can trash children from folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanTrashChildren() {
return canTrashChildren;
}
/**
* Whether the current user can trash children from folders in this Team Drive.
* @param canTrashChildren canTrashChildren or {@code null} for none
*/
public Capabilities setCanTrashChildren(java.lang.Boolean canTrashChildren) {
this.canTrashChildren = canTrashChildren;
return this;
}
@Override
public Capabilities set(String fieldName, Object value) {
return (Capabilities) super.set(fieldName, value);
}
@Override
public Capabilities clone() {
return (Capabilities) super.clone();
}
}
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
*/
public static final class Restrictions extends com.google.api.client.json.GenericJson {
/**
* Whether administrative privileges on this Team Drive are required to modify restrictions.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean adminManagedRestrictions;
/**
* Whether the options to copy, print, or download files inside this Team Drive, should be
* disabled for readers and commenters. When this restriction is set to true, it will override the
* similarly named field to true for any file inside this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean copyRequiresWriterPermission;
/**
* Whether access to this Team Drive and items inside this Team Drive is restricted to users of
* the domain to which this Team Drive belongs. This restriction may be overridden by other
* sharing policies controlled outside of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean domainUsersOnly;
/**
* Whether access to items inside this Team Drive is restricted to members of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean teamMembersOnly;
/**
* Whether administrative privileges on this Team Drive are required to modify restrictions.
* @return value or {@code null} for none
*/
public java.lang.Boolean getAdminManagedRestrictions() {
return adminManagedRestrictions;
}
/**
* Whether administrative privileges on this Team Drive are required to modify restrictions.
* @param adminManagedRestrictions adminManagedRestrictions or {@code null} for none
*/
public Restrictions setAdminManagedRestrictions(java.lang.Boolean adminManagedRestrictions) {
this.adminManagedRestrictions = adminManagedRestrictions;
return this;
}
/**
* Whether the options to copy, print, or download files inside this Team Drive, should be
* disabled for readers and commenters. When this restriction is set to true, it will override the
* similarly named field to true for any file inside this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCopyRequiresWriterPermission() {
return copyRequiresWriterPermission;
}
/**
* Whether the options to copy, print, or download files inside this Team Drive, should be
* disabled for readers and commenters. When this restriction is set to true, it will override the
* similarly named field to true for any file inside this Team Drive.
* @param copyRequiresWriterPermission copyRequiresWriterPermission or {@code null} for none
*/
public Restrictions setCopyRequiresWriterPermission(java.lang.Boolean copyRequiresWriterPermission) {
this.copyRequiresWriterPermission = copyRequiresWriterPermission;
return this;
}
/**
* Whether access to this Team Drive and items inside this Team Drive is restricted to users of
* the domain to which this Team Drive belongs. This restriction may be overridden by other
* sharing policies controlled outside of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDomainUsersOnly() {
return domainUsersOnly;
}
/**
* Whether access to this Team Drive and items inside this Team Drive is restricted to users of
* the domain to which this Team Drive belongs. This restriction may be overridden by other
* sharing policies controlled outside of this Team Drive.
* @param domainUsersOnly domainUsersOnly or {@code null} for none
*/
public Restrictions setDomainUsersOnly(java.lang.Boolean domainUsersOnly) {
this.domainUsersOnly = domainUsersOnly;
return this;
}
/**
* Whether access to items inside this Team Drive is restricted to members of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getTeamMembersOnly() {
return teamMembersOnly;
}
/**
* Whether access to items inside this Team Drive is restricted to members of this Team Drive.
* @param teamMembersOnly teamMembersOnly or {@code null} for none
*/
public Restrictions setTeamMembersOnly(java.lang.Boolean teamMembersOnly) {
this.teamMembersOnly = teamMembersOnly;
return this;
}
@Override
public Restrictions set(String fieldName, Object value) {
return (Restrictions) super.set(fieldName, value);
}
@Override
public Restrictions clone() {
return (Restrictions) super.clone();
}
}
}
|
googleapis/google-api-java-client-services | 36,603 | clients/google-api-services-drive/v3/1.30.1/com/google/api/services/drive/model/TeamDrive.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.drive.model;
/**
* Deprecated: use the drive collection instead.
*
* <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 Drive 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 TeamDrive extends com.google.api.client.json.GenericJson {
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't
* set themeId. When specified, all fields of the backgroundImageFile must be set.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private BackgroundImageFile backgroundImageFile;
/**
* A short-lived link to this Team Drive's background image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String backgroundImageLink;
/**
* Capabilities the current user has on this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Capabilities capabilities;
/**
* The color of this Team Drive as an RGB hex string. It can only be set on a
* drive.teamdrives.update request that does not set themeId.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String colorRgb;
/**
* The time at which the Team Drive was created (RFC 3339 date-time).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private com.google.api.client.util.DateTime createdTime;
/**
* The ID of this Team Drive which is also the ID of the top level folder of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String id;
/**
* Identifies what kind of resource this is. Value: the fixed string "drive#teamDrive".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* The name of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Restrictions restrictions;
/**
* The ID of the theme from which the background image and color will be set. The set of possible
* teamDriveThemes can be retrieved from a drive.about.get response. When not specified on a
* drive.teamdrives.create request, a random theme is chosen from which the background image and
* color are set. This is a write-only field; it can only be set on requests that don't set
* colorRgb or backgroundImageFile.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String themeId;
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't
* set themeId. When specified, all fields of the backgroundImageFile must be set.
* @return value or {@code null} for none
*/
public BackgroundImageFile getBackgroundImageFile() {
return backgroundImageFile;
}
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't
* set themeId. When specified, all fields of the backgroundImageFile must be set.
* @param backgroundImageFile backgroundImageFile or {@code null} for none
*/
public TeamDrive setBackgroundImageFile(BackgroundImageFile backgroundImageFile) {
this.backgroundImageFile = backgroundImageFile;
return this;
}
/**
* A short-lived link to this Team Drive's background image.
* @return value or {@code null} for none
*/
public java.lang.String getBackgroundImageLink() {
return backgroundImageLink;
}
/**
* A short-lived link to this Team Drive's background image.
* @param backgroundImageLink backgroundImageLink or {@code null} for none
*/
public TeamDrive setBackgroundImageLink(java.lang.String backgroundImageLink) {
this.backgroundImageLink = backgroundImageLink;
return this;
}
/**
* Capabilities the current user has on this Team Drive.
* @return value or {@code null} for none
*/
public Capabilities getCapabilities() {
return capabilities;
}
/**
* Capabilities the current user has on this Team Drive.
* @param capabilities capabilities or {@code null} for none
*/
public TeamDrive setCapabilities(Capabilities capabilities) {
this.capabilities = capabilities;
return this;
}
/**
* The color of this Team Drive as an RGB hex string. It can only be set on a
* drive.teamdrives.update request that does not set themeId.
* @return value or {@code null} for none
*/
public java.lang.String getColorRgb() {
return colorRgb;
}
/**
* The color of this Team Drive as an RGB hex string. It can only be set on a
* drive.teamdrives.update request that does not set themeId.
* @param colorRgb colorRgb or {@code null} for none
*/
public TeamDrive setColorRgb(java.lang.String colorRgb) {
this.colorRgb = colorRgb;
return this;
}
/**
* The time at which the Team Drive was created (RFC 3339 date-time).
* @return value or {@code null} for none
*/
public com.google.api.client.util.DateTime getCreatedTime() {
return createdTime;
}
/**
* The time at which the Team Drive was created (RFC 3339 date-time).
* @param createdTime createdTime or {@code null} for none
*/
public TeamDrive setCreatedTime(com.google.api.client.util.DateTime createdTime) {
this.createdTime = createdTime;
return this;
}
/**
* The ID of this Team Drive which is also the ID of the top level folder of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.String getId() {
return id;
}
/**
* The ID of this Team Drive which is also the ID of the top level folder of this Team Drive.
* @param id id or {@code null} for none
*/
public TeamDrive setId(java.lang.String id) {
this.id = id;
return this;
}
/**
* Identifies what kind of resource this is. Value: the fixed string "drive#teamDrive".
* @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 "drive#teamDrive".
* @param kind kind or {@code null} for none
*/
public TeamDrive setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* The name of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* The name of this Team Drive.
* @param name name or {@code null} for none
*/
public TeamDrive setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
* @return value or {@code null} for none
*/
public Restrictions getRestrictions() {
return restrictions;
}
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
* @param restrictions restrictions or {@code null} for none
*/
public TeamDrive setRestrictions(Restrictions restrictions) {
this.restrictions = restrictions;
return this;
}
/**
* The ID of the theme from which the background image and color will be set. The set of possible
* teamDriveThemes can be retrieved from a drive.about.get response. When not specified on a
* drive.teamdrives.create request, a random theme is chosen from which the background image and
* color are set. This is a write-only field; it can only be set on requests that don't set
* colorRgb or backgroundImageFile.
* @return value or {@code null} for none
*/
public java.lang.String getThemeId() {
return themeId;
}
/**
* The ID of the theme from which the background image and color will be set. The set of possible
* teamDriveThemes can be retrieved from a drive.about.get response. When not specified on a
* drive.teamdrives.create request, a random theme is chosen from which the background image and
* color are set. This is a write-only field; it can only be set on requests that don't set
* colorRgb or backgroundImageFile.
* @param themeId themeId or {@code null} for none
*/
public TeamDrive setThemeId(java.lang.String themeId) {
this.themeId = themeId;
return this;
}
@Override
public TeamDrive set(String fieldName, Object value) {
return (TeamDrive) super.set(fieldName, value);
}
@Override
public TeamDrive clone() {
return (TeamDrive) super.clone();
}
/**
* An image file and cropping parameters from which a background image for this Team Drive is set.
* This is a write only field; it can only be set on drive.teamdrives.update requests that don't set
* themeId. When specified, all fields of the backgroundImageFile must be set.
*/
public static final class BackgroundImageFile extends com.google.api.client.json.GenericJson {
/**
* The ID of an image file in Drive to use for the background image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String id;
/**
* The width of the cropped image in the closed range of 0 to 1. This value represents the width
* of the cropped image divided by the width of the entire image. The height is computed by
* applying a width to height aspect ratio of 80 to 9. The resulting image must be at least 1280
* pixels wide and 144 pixels high.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Float width;
/**
* The X coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the horizontal distance from the
* left side of the entire image to the left side of the cropping area divided by the width of the
* entire image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Float xCoordinate;
/**
* The Y coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the vertical distance from the top
* side of the entire image to the top side of the cropping area divided by the height of the
* entire image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Float yCoordinate;
/**
* The ID of an image file in Drive to use for the background image.
* @return value or {@code null} for none
*/
public java.lang.String getId() {
return id;
}
/**
* The ID of an image file in Drive to use for the background image.
* @param id id or {@code null} for none
*/
public BackgroundImageFile setId(java.lang.String id) {
this.id = id;
return this;
}
/**
* The width of the cropped image in the closed range of 0 to 1. This value represents the width
* of the cropped image divided by the width of the entire image. The height is computed by
* applying a width to height aspect ratio of 80 to 9. The resulting image must be at least 1280
* pixels wide and 144 pixels high.
* @return value or {@code null} for none
*/
public java.lang.Float getWidth() {
return width;
}
/**
* The width of the cropped image in the closed range of 0 to 1. This value represents the width
* of the cropped image divided by the width of the entire image. The height is computed by
* applying a width to height aspect ratio of 80 to 9. The resulting image must be at least 1280
* pixels wide and 144 pixels high.
* @param width width or {@code null} for none
*/
public BackgroundImageFile setWidth(java.lang.Float width) {
this.width = width;
return this;
}
/**
* The X coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the horizontal distance from the
* left side of the entire image to the left side of the cropping area divided by the width of the
* entire image.
* @return value or {@code null} for none
*/
public java.lang.Float getXCoordinate() {
return xCoordinate;
}
/**
* The X coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the horizontal distance from the
* left side of the entire image to the left side of the cropping area divided by the width of the
* entire image.
* @param xCoordinate xCoordinate or {@code null} for none
*/
public BackgroundImageFile setXCoordinate(java.lang.Float xCoordinate) {
this.xCoordinate = xCoordinate;
return this;
}
/**
* The Y coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the vertical distance from the top
* side of the entire image to the top side of the cropping area divided by the height of the
* entire image.
* @return value or {@code null} for none
*/
public java.lang.Float getYCoordinate() {
return yCoordinate;
}
/**
* The Y coordinate of the upper left corner of the cropping area in the background image. This is
* a value in the closed range of 0 to 1. This value represents the vertical distance from the top
* side of the entire image to the top side of the cropping area divided by the height of the
* entire image.
* @param yCoordinate yCoordinate or {@code null} for none
*/
public BackgroundImageFile setYCoordinate(java.lang.Float yCoordinate) {
this.yCoordinate = yCoordinate;
return this;
}
@Override
public BackgroundImageFile set(String fieldName, Object value) {
return (BackgroundImageFile) super.set(fieldName, value);
}
@Override
public BackgroundImageFile clone() {
return (BackgroundImageFile) super.clone();
}
}
/**
* Capabilities the current user has on this Team Drive.
*/
public static final class Capabilities extends com.google.api.client.json.GenericJson {
/**
* Whether the current user can add children to folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canAddChildren;
/**
* Whether the current user can change the copyRequiresWriterPermission restriction of this Team
* Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeCopyRequiresWriterPermissionRestriction;
/**
* Whether the current user can change the domainUsersOnly restriction of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeDomainUsersOnlyRestriction;
/**
* Whether the current user can change the background of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeTeamDriveBackground;
/**
* Whether the current user can change the teamMembersOnly restriction of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canChangeTeamMembersOnlyRestriction;
/**
* Whether the current user can comment on files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canComment;
/**
* Whether the current user can copy files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canCopy;
/**
* Whether the current user can delete children from folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canDeleteChildren;
/**
* Whether the current user can delete this Team Drive. Attempting to delete the Team Drive may
* still fail if there are untrashed items inside the Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canDeleteTeamDrive;
/**
* Whether the current user can download files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canDownload;
/**
* Whether the current user can edit files in this Team Drive
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canEdit;
/**
* Whether the current user can list the children of folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canListChildren;
/**
* Whether the current user can add members to this Team Drive or remove them or change their
* role.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canManageMembers;
/**
* Whether the current user can read the revisions resource of files in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canReadRevisions;
/**
* Deprecated - use canDeleteChildren or canTrashChildren instead.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canRemoveChildren;
/**
* Whether the current user can rename files or folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canRename;
/**
* Whether the current user can rename this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canRenameTeamDrive;
/**
* Whether the current user can share files or folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canShare;
/**
* Whether the current user can trash children from folders in this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean canTrashChildren;
/**
* Whether the current user can add children to folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanAddChildren() {
return canAddChildren;
}
/**
* Whether the current user can add children to folders in this Team Drive.
* @param canAddChildren canAddChildren or {@code null} for none
*/
public Capabilities setCanAddChildren(java.lang.Boolean canAddChildren) {
this.canAddChildren = canAddChildren;
return this;
}
/**
* Whether the current user can change the copyRequiresWriterPermission restriction of this Team
* Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeCopyRequiresWriterPermissionRestriction() {
return canChangeCopyRequiresWriterPermissionRestriction;
}
/**
* Whether the current user can change the copyRequiresWriterPermission restriction of this Team
* Drive.
* @param canChangeCopyRequiresWriterPermissionRestriction canChangeCopyRequiresWriterPermissionRestriction or {@code null} for none
*/
public Capabilities setCanChangeCopyRequiresWriterPermissionRestriction(java.lang.Boolean canChangeCopyRequiresWriterPermissionRestriction) {
this.canChangeCopyRequiresWriterPermissionRestriction = canChangeCopyRequiresWriterPermissionRestriction;
return this;
}
/**
* Whether the current user can change the domainUsersOnly restriction of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeDomainUsersOnlyRestriction() {
return canChangeDomainUsersOnlyRestriction;
}
/**
* Whether the current user can change the domainUsersOnly restriction of this Team Drive.
* @param canChangeDomainUsersOnlyRestriction canChangeDomainUsersOnlyRestriction or {@code null} for none
*/
public Capabilities setCanChangeDomainUsersOnlyRestriction(java.lang.Boolean canChangeDomainUsersOnlyRestriction) {
this.canChangeDomainUsersOnlyRestriction = canChangeDomainUsersOnlyRestriction;
return this;
}
/**
* Whether the current user can change the background of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeTeamDriveBackground() {
return canChangeTeamDriveBackground;
}
/**
* Whether the current user can change the background of this Team Drive.
* @param canChangeTeamDriveBackground canChangeTeamDriveBackground or {@code null} for none
*/
public Capabilities setCanChangeTeamDriveBackground(java.lang.Boolean canChangeTeamDriveBackground) {
this.canChangeTeamDriveBackground = canChangeTeamDriveBackground;
return this;
}
/**
* Whether the current user can change the teamMembersOnly restriction of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanChangeTeamMembersOnlyRestriction() {
return canChangeTeamMembersOnlyRestriction;
}
/**
* Whether the current user can change the teamMembersOnly restriction of this Team Drive.
* @param canChangeTeamMembersOnlyRestriction canChangeTeamMembersOnlyRestriction or {@code null} for none
*/
public Capabilities setCanChangeTeamMembersOnlyRestriction(java.lang.Boolean canChangeTeamMembersOnlyRestriction) {
this.canChangeTeamMembersOnlyRestriction = canChangeTeamMembersOnlyRestriction;
return this;
}
/**
* Whether the current user can comment on files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanComment() {
return canComment;
}
/**
* Whether the current user can comment on files in this Team Drive.
* @param canComment canComment or {@code null} for none
*/
public Capabilities setCanComment(java.lang.Boolean canComment) {
this.canComment = canComment;
return this;
}
/**
* Whether the current user can copy files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanCopy() {
return canCopy;
}
/**
* Whether the current user can copy files in this Team Drive.
* @param canCopy canCopy or {@code null} for none
*/
public Capabilities setCanCopy(java.lang.Boolean canCopy) {
this.canCopy = canCopy;
return this;
}
/**
* Whether the current user can delete children from folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanDeleteChildren() {
return canDeleteChildren;
}
/**
* Whether the current user can delete children from folders in this Team Drive.
* @param canDeleteChildren canDeleteChildren or {@code null} for none
*/
public Capabilities setCanDeleteChildren(java.lang.Boolean canDeleteChildren) {
this.canDeleteChildren = canDeleteChildren;
return this;
}
/**
* Whether the current user can delete this Team Drive. Attempting to delete the Team Drive may
* still fail if there are untrashed items inside the Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanDeleteTeamDrive() {
return canDeleteTeamDrive;
}
/**
* Whether the current user can delete this Team Drive. Attempting to delete the Team Drive may
* still fail if there are untrashed items inside the Team Drive.
* @param canDeleteTeamDrive canDeleteTeamDrive or {@code null} for none
*/
public Capabilities setCanDeleteTeamDrive(java.lang.Boolean canDeleteTeamDrive) {
this.canDeleteTeamDrive = canDeleteTeamDrive;
return this;
}
/**
* Whether the current user can download files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanDownload() {
return canDownload;
}
/**
* Whether the current user can download files in this Team Drive.
* @param canDownload canDownload or {@code null} for none
*/
public Capabilities setCanDownload(java.lang.Boolean canDownload) {
this.canDownload = canDownload;
return this;
}
/**
* Whether the current user can edit files in this Team Drive
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanEdit() {
return canEdit;
}
/**
* Whether the current user can edit files in this Team Drive
* @param canEdit canEdit or {@code null} for none
*/
public Capabilities setCanEdit(java.lang.Boolean canEdit) {
this.canEdit = canEdit;
return this;
}
/**
* Whether the current user can list the children of folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanListChildren() {
return canListChildren;
}
/**
* Whether the current user can list the children of folders in this Team Drive.
* @param canListChildren canListChildren or {@code null} for none
*/
public Capabilities setCanListChildren(java.lang.Boolean canListChildren) {
this.canListChildren = canListChildren;
return this;
}
/**
* Whether the current user can add members to this Team Drive or remove them or change their
* role.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanManageMembers() {
return canManageMembers;
}
/**
* Whether the current user can add members to this Team Drive or remove them or change their
* role.
* @param canManageMembers canManageMembers or {@code null} for none
*/
public Capabilities setCanManageMembers(java.lang.Boolean canManageMembers) {
this.canManageMembers = canManageMembers;
return this;
}
/**
* Whether the current user can read the revisions resource of files in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanReadRevisions() {
return canReadRevisions;
}
/**
* Whether the current user can read the revisions resource of files in this Team Drive.
* @param canReadRevisions canReadRevisions or {@code null} for none
*/
public Capabilities setCanReadRevisions(java.lang.Boolean canReadRevisions) {
this.canReadRevisions = canReadRevisions;
return this;
}
/**
* Deprecated - use canDeleteChildren or canTrashChildren instead.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanRemoveChildren() {
return canRemoveChildren;
}
/**
* Deprecated - use canDeleteChildren or canTrashChildren instead.
* @param canRemoveChildren canRemoveChildren or {@code null} for none
*/
public Capabilities setCanRemoveChildren(java.lang.Boolean canRemoveChildren) {
this.canRemoveChildren = canRemoveChildren;
return this;
}
/**
* Whether the current user can rename files or folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanRename() {
return canRename;
}
/**
* Whether the current user can rename files or folders in this Team Drive.
* @param canRename canRename or {@code null} for none
*/
public Capabilities setCanRename(java.lang.Boolean canRename) {
this.canRename = canRename;
return this;
}
/**
* Whether the current user can rename this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanRenameTeamDrive() {
return canRenameTeamDrive;
}
/**
* Whether the current user can rename this Team Drive.
* @param canRenameTeamDrive canRenameTeamDrive or {@code null} for none
*/
public Capabilities setCanRenameTeamDrive(java.lang.Boolean canRenameTeamDrive) {
this.canRenameTeamDrive = canRenameTeamDrive;
return this;
}
/**
* Whether the current user can share files or folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanShare() {
return canShare;
}
/**
* Whether the current user can share files or folders in this Team Drive.
* @param canShare canShare or {@code null} for none
*/
public Capabilities setCanShare(java.lang.Boolean canShare) {
this.canShare = canShare;
return this;
}
/**
* Whether the current user can trash children from folders in this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCanTrashChildren() {
return canTrashChildren;
}
/**
* Whether the current user can trash children from folders in this Team Drive.
* @param canTrashChildren canTrashChildren or {@code null} for none
*/
public Capabilities setCanTrashChildren(java.lang.Boolean canTrashChildren) {
this.canTrashChildren = canTrashChildren;
return this;
}
@Override
public Capabilities set(String fieldName, Object value) {
return (Capabilities) super.set(fieldName, value);
}
@Override
public Capabilities clone() {
return (Capabilities) super.clone();
}
}
/**
* A set of restrictions that apply to this Team Drive or items inside this Team Drive.
*/
public static final class Restrictions extends com.google.api.client.json.GenericJson {
/**
* Whether administrative privileges on this Team Drive are required to modify restrictions.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean adminManagedRestrictions;
/**
* Whether the options to copy, print, or download files inside this Team Drive, should be
* disabled for readers and commenters. When this restriction is set to true, it will override the
* similarly named field to true for any file inside this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean copyRequiresWriterPermission;
/**
* Whether access to this Team Drive and items inside this Team Drive is restricted to users of
* the domain to which this Team Drive belongs. This restriction may be overridden by other
* sharing policies controlled outside of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean domainUsersOnly;
/**
* Whether access to items inside this Team Drive is restricted to members of this Team Drive.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean teamMembersOnly;
/**
* Whether administrative privileges on this Team Drive are required to modify restrictions.
* @return value or {@code null} for none
*/
public java.lang.Boolean getAdminManagedRestrictions() {
return adminManagedRestrictions;
}
/**
* Whether administrative privileges on this Team Drive are required to modify restrictions.
* @param adminManagedRestrictions adminManagedRestrictions or {@code null} for none
*/
public Restrictions setAdminManagedRestrictions(java.lang.Boolean adminManagedRestrictions) {
this.adminManagedRestrictions = adminManagedRestrictions;
return this;
}
/**
* Whether the options to copy, print, or download files inside this Team Drive, should be
* disabled for readers and commenters. When this restriction is set to true, it will override the
* similarly named field to true for any file inside this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getCopyRequiresWriterPermission() {
return copyRequiresWriterPermission;
}
/**
* Whether the options to copy, print, or download files inside this Team Drive, should be
* disabled for readers and commenters. When this restriction is set to true, it will override the
* similarly named field to true for any file inside this Team Drive.
* @param copyRequiresWriterPermission copyRequiresWriterPermission or {@code null} for none
*/
public Restrictions setCopyRequiresWriterPermission(java.lang.Boolean copyRequiresWriterPermission) {
this.copyRequiresWriterPermission = copyRequiresWriterPermission;
return this;
}
/**
* Whether access to this Team Drive and items inside this Team Drive is restricted to users of
* the domain to which this Team Drive belongs. This restriction may be overridden by other
* sharing policies controlled outside of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getDomainUsersOnly() {
return domainUsersOnly;
}
/**
* Whether access to this Team Drive and items inside this Team Drive is restricted to users of
* the domain to which this Team Drive belongs. This restriction may be overridden by other
* sharing policies controlled outside of this Team Drive.
* @param domainUsersOnly domainUsersOnly or {@code null} for none
*/
public Restrictions setDomainUsersOnly(java.lang.Boolean domainUsersOnly) {
this.domainUsersOnly = domainUsersOnly;
return this;
}
/**
* Whether access to items inside this Team Drive is restricted to members of this Team Drive.
* @return value or {@code null} for none
*/
public java.lang.Boolean getTeamMembersOnly() {
return teamMembersOnly;
}
/**
* Whether access to items inside this Team Drive is restricted to members of this Team Drive.
* @param teamMembersOnly teamMembersOnly or {@code null} for none
*/
public Restrictions setTeamMembersOnly(java.lang.Boolean teamMembersOnly) {
this.teamMembersOnly = teamMembersOnly;
return this;
}
@Override
public Restrictions set(String fieldName, Object value) {
return (Restrictions) super.set(fieldName, value);
}
@Override
public Restrictions clone() {
return (Restrictions) super.clone();
}
}
}
|
googleapis/google-cloud-java | 36,195 | java-shopping-merchant-reviews/proto-google-shopping-merchant-reviews-v1beta/src/main/java/com/google/shopping/merchant/reviews/v1beta/ProductReviewAttributesOrBuilder.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/shopping/merchant/reviews/v1beta/productreviews_common.proto
// Protobuf Java Version: 3.25.8
package com.google.shopping.merchant.reviews.v1beta;
public interface ProductReviewAttributesOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.shopping.merchant.reviews.v1beta.ProductReviewAttributes)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Optional. The name of the aggregator of the product reviews.
*
* A publisher may use a reviews aggregator to manage reviews and provide
* the feeds. This element indicates the use of an aggregator and contains
* information about the aggregator.
* </pre>
*
* <code>optional string aggregator_name = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the aggregatorName field is set.
*/
boolean hasAggregatorName();
/**
*
*
* <pre>
* Optional. The name of the aggregator of the product reviews.
*
* A publisher may use a reviews aggregator to manage reviews and provide
* the feeds. This element indicates the use of an aggregator and contains
* information about the aggregator.
* </pre>
*
* <code>optional string aggregator_name = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The aggregatorName.
*/
java.lang.String getAggregatorName();
/**
*
*
* <pre>
* Optional. The name of the aggregator of the product reviews.
*
* A publisher may use a reviews aggregator to manage reviews and provide
* the feeds. This element indicates the use of an aggregator and contains
* information about the aggregator.
* </pre>
*
* <code>optional string aggregator_name = 1 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for aggregatorName.
*/
com.google.protobuf.ByteString getAggregatorNameBytes();
/**
*
*
* <pre>
* Optional. The name of the subclient of the product reviews.
*
* The subclient is an identifier of the product review source.
* It should be equivalent to the directory provided in the file data source
* path.
* </pre>
*
* <code>optional string subclient_name = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the subclientName field is set.
*/
boolean hasSubclientName();
/**
*
*
* <pre>
* Optional. The name of the subclient of the product reviews.
*
* The subclient is an identifier of the product review source.
* It should be equivalent to the directory provided in the file data source
* path.
* </pre>
*
* <code>optional string subclient_name = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The subclientName.
*/
java.lang.String getSubclientName();
/**
*
*
* <pre>
* Optional. The name of the subclient of the product reviews.
*
* The subclient is an identifier of the product review source.
* It should be equivalent to the directory provided in the file data source
* path.
* </pre>
*
* <code>optional string subclient_name = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for subclientName.
*/
com.google.protobuf.ByteString getSubclientNameBytes();
/**
*
*
* <pre>
* Optional. The name of the publisher of the product reviews.
*
* The information about the publisher, which may be a retailer,
* manufacturer, reviews service company, or any entity that publishes
* product reviews.
* </pre>
*
* <code>optional string publisher_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the publisherName field is set.
*/
boolean hasPublisherName();
/**
*
*
* <pre>
* Optional. The name of the publisher of the product reviews.
*
* The information about the publisher, which may be a retailer,
* manufacturer, reviews service company, or any entity that publishes
* product reviews.
* </pre>
*
* <code>optional string publisher_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The publisherName.
*/
java.lang.String getPublisherName();
/**
*
*
* <pre>
* Optional. The name of the publisher of the product reviews.
*
* The information about the publisher, which may be a retailer,
* manufacturer, reviews service company, or any entity that publishes
* product reviews.
* </pre>
*
* <code>optional string publisher_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for publisherName.
*/
com.google.protobuf.ByteString getPublisherNameBytes();
/**
*
*
* <pre>
* Optional. A link to the company favicon of the publisher. The image
* dimensions should be favicon size: 16x16 pixels. The image format should be
* GIF, JPG or PNG.
* </pre>
*
* <code>optional string publisher_favicon = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the publisherFavicon field is set.
*/
boolean hasPublisherFavicon();
/**
*
*
* <pre>
* Optional. A link to the company favicon of the publisher. The image
* dimensions should be favicon size: 16x16 pixels. The image format should be
* GIF, JPG or PNG.
* </pre>
*
* <code>optional string publisher_favicon = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The publisherFavicon.
*/
java.lang.String getPublisherFavicon();
/**
*
*
* <pre>
* Optional. A link to the company favicon of the publisher. The image
* dimensions should be favicon size: 16x16 pixels. The image format should be
* GIF, JPG or PNG.
* </pre>
*
* <code>optional string publisher_favicon = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for publisherFavicon.
*/
com.google.protobuf.ByteString getPublisherFaviconBytes();
/**
*
*
* <pre>
* Optional. The author of the product review.
*
* A permanent, unique identifier for the author of the review in the
* publisher's system.
* </pre>
*
* <code>optional string reviewer_id = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the reviewerId field is set.
*/
boolean hasReviewerId();
/**
*
*
* <pre>
* Optional. The author of the product review.
*
* A permanent, unique identifier for the author of the review in the
* publisher's system.
* </pre>
*
* <code>optional string reviewer_id = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The reviewerId.
*/
java.lang.String getReviewerId();
/**
*
*
* <pre>
* Optional. The author of the product review.
*
* A permanent, unique identifier for the author of the review in the
* publisher's system.
* </pre>
*
* <code>optional string reviewer_id = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for reviewerId.
*/
com.google.protobuf.ByteString getReviewerIdBytes();
/**
*
*
* <pre>
* Optional. Set to true if the reviewer should remain anonymous.
* </pre>
*
* <code>optional bool reviewer_is_anonymous = 6 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the reviewerIsAnonymous field is set.
*/
boolean hasReviewerIsAnonymous();
/**
*
*
* <pre>
* Optional. Set to true if the reviewer should remain anonymous.
* </pre>
*
* <code>optional bool reviewer_is_anonymous = 6 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The reviewerIsAnonymous.
*/
boolean getReviewerIsAnonymous();
/**
*
*
* <pre>
* Optional. The name of the reviewer of the product review.
* </pre>
*
* <code>optional string reviewer_username = 7 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the reviewerUsername field is set.
*/
boolean hasReviewerUsername();
/**
*
*
* <pre>
* Optional. The name of the reviewer of the product review.
* </pre>
*
* <code>optional string reviewer_username = 7 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The reviewerUsername.
*/
java.lang.String getReviewerUsername();
/**
*
*
* <pre>
* Optional. The name of the reviewer of the product review.
* </pre>
*
* <code>optional string reviewer_username = 7 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for reviewerUsername.
*/
com.google.protobuf.ByteString getReviewerUsernameBytes();
/**
*
*
* <pre>
* Optional. The language of the review defined by BCP-47 language code.
* </pre>
*
* <code>optional string review_language = 8 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the reviewLanguage field is set.
*/
boolean hasReviewLanguage();
/**
*
*
* <pre>
* Optional. The language of the review defined by BCP-47 language code.
* </pre>
*
* <code>optional string review_language = 8 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The reviewLanguage.
*/
java.lang.String getReviewLanguage();
/**
*
*
* <pre>
* Optional. The language of the review defined by BCP-47 language code.
* </pre>
*
* <code>optional string review_language = 8 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for reviewLanguage.
*/
com.google.protobuf.ByteString getReviewLanguageBytes();
/**
*
*
* <pre>
* Optional. The country of the review defined by ISO 3166-1 Alpha-2 Country
* Code.
* </pre>
*
* <code>optional string review_country = 9 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the reviewCountry field is set.
*/
boolean hasReviewCountry();
/**
*
*
* <pre>
* Optional. The country of the review defined by ISO 3166-1 Alpha-2 Country
* Code.
* </pre>
*
* <code>optional string review_country = 9 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The reviewCountry.
*/
java.lang.String getReviewCountry();
/**
*
*
* <pre>
* Optional. The country of the review defined by ISO 3166-1 Alpha-2 Country
* Code.
* </pre>
*
* <code>optional string review_country = 9 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for reviewCountry.
*/
com.google.protobuf.ByteString getReviewCountryBytes();
/**
*
*
* <pre>
* Required. The timestamp indicating when the review was written.
* </pre>
*
* <code>.google.protobuf.Timestamp review_time = 10 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the reviewTime field is set.
*/
boolean hasReviewTime();
/**
*
*
* <pre>
* Required. The timestamp indicating when the review was written.
* </pre>
*
* <code>.google.protobuf.Timestamp review_time = 10 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The reviewTime.
*/
com.google.protobuf.Timestamp getReviewTime();
/**
*
*
* <pre>
* Required. The timestamp indicating when the review was written.
* </pre>
*
* <code>.google.protobuf.Timestamp review_time = 10 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
com.google.protobuf.TimestampOrBuilder getReviewTimeOrBuilder();
/**
*
*
* <pre>
* Optional. The title of the review.
* </pre>
*
* <code>optional string title = 11 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the title field is set.
*/
boolean hasTitle();
/**
*
*
* <pre>
* Optional. The title of the review.
* </pre>
*
* <code>optional string title = 11 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The title.
*/
java.lang.String getTitle();
/**
*
*
* <pre>
* Optional. The title of the review.
* </pre>
*
* <code>optional string title = 11 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for title.
*/
com.google.protobuf.ByteString getTitleBytes();
/**
*
*
* <pre>
* Optional. The content of the review. If empty, the content might still get
* populated from pros and cons.
* </pre>
*
* <code>optional string content = 12 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the content field is set.
*/
boolean hasContent();
/**
*
*
* <pre>
* Optional. The content of the review. If empty, the content might still get
* populated from pros and cons.
* </pre>
*
* <code>optional string content = 12 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The content.
*/
java.lang.String getContent();
/**
*
*
* <pre>
* Optional. The content of the review. If empty, the content might still get
* populated from pros and cons.
* </pre>
*
* <code>optional string content = 12 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for content.
*/
com.google.protobuf.ByteString getContentBytes();
/**
*
*
* <pre>
* Optional. Contains the advantages based on the opinion of the reviewer.
* Omit boilerplate text like "pro:" unless it was written by the reviewer.
* </pre>
*
* <code>repeated string pros = 13 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return A list containing the pros.
*/
java.util.List<java.lang.String> getProsList();
/**
*
*
* <pre>
* Optional. Contains the advantages based on the opinion of the reviewer.
* Omit boilerplate text like "pro:" unless it was written by the reviewer.
* </pre>
*
* <code>repeated string pros = 13 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The count of pros.
*/
int getProsCount();
/**
*
*
* <pre>
* Optional. Contains the advantages based on the opinion of the reviewer.
* Omit boilerplate text like "pro:" unless it was written by the reviewer.
* </pre>
*
* <code>repeated string pros = 13 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the element to return.
* @return The pros at the given index.
*/
java.lang.String getPros(int index);
/**
*
*
* <pre>
* Optional. Contains the advantages based on the opinion of the reviewer.
* Omit boilerplate text like "pro:" unless it was written by the reviewer.
* </pre>
*
* <code>repeated string pros = 13 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the value to return.
* @return The bytes of the pros at the given index.
*/
com.google.protobuf.ByteString getProsBytes(int index);
/**
*
*
* <pre>
* Optional. Contains the disadvantages based on the opinion of the reviewer.
* Omit boilerplate text like "con:" unless it was written by the reviewer.
* </pre>
*
* <code>repeated string cons = 14 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return A list containing the cons.
*/
java.util.List<java.lang.String> getConsList();
/**
*
*
* <pre>
* Optional. Contains the disadvantages based on the opinion of the reviewer.
* Omit boilerplate text like "con:" unless it was written by the reviewer.
* </pre>
*
* <code>repeated string cons = 14 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The count of cons.
*/
int getConsCount();
/**
*
*
* <pre>
* Optional. Contains the disadvantages based on the opinion of the reviewer.
* Omit boilerplate text like "con:" unless it was written by the reviewer.
* </pre>
*
* <code>repeated string cons = 14 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the element to return.
* @return The cons at the given index.
*/
java.lang.String getCons(int index);
/**
*
*
* <pre>
* Optional. Contains the disadvantages based on the opinion of the reviewer.
* Omit boilerplate text like "con:" unless it was written by the reviewer.
* </pre>
*
* <code>repeated string cons = 14 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the value to return.
* @return The bytes of the cons at the given index.
*/
com.google.protobuf.ByteString getConsBytes(int index);
/**
*
*
* <pre>
* Optional. The URI of the review landing page.
* </pre>
*
* <code>
* .google.shopping.merchant.reviews.v1beta.ProductReviewAttributes.ReviewLink review_link = 15 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the reviewLink field is set.
*/
boolean hasReviewLink();
/**
*
*
* <pre>
* Optional. The URI of the review landing page.
* </pre>
*
* <code>
* .google.shopping.merchant.reviews.v1beta.ProductReviewAttributes.ReviewLink review_link = 15 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The reviewLink.
*/
com.google.shopping.merchant.reviews.v1beta.ProductReviewAttributes.ReviewLink getReviewLink();
/**
*
*
* <pre>
* Optional. The URI of the review landing page.
* </pre>
*
* <code>
* .google.shopping.merchant.reviews.v1beta.ProductReviewAttributes.ReviewLink review_link = 15 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
com.google.shopping.merchant.reviews.v1beta.ProductReviewAttributes.ReviewLinkOrBuilder
getReviewLinkOrBuilder();
/**
*
*
* <pre>
* Optional. A URI to an image of the reviewed product created by the review
* author. The URI does not have to end with an image file extension.
* </pre>
*
* <code>repeated string reviewer_image_links = 16 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return A list containing the reviewerImageLinks.
*/
java.util.List<java.lang.String> getReviewerImageLinksList();
/**
*
*
* <pre>
* Optional. A URI to an image of the reviewed product created by the review
* author. The URI does not have to end with an image file extension.
* </pre>
*
* <code>repeated string reviewer_image_links = 16 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The count of reviewerImageLinks.
*/
int getReviewerImageLinksCount();
/**
*
*
* <pre>
* Optional. A URI to an image of the reviewed product created by the review
* author. The URI does not have to end with an image file extension.
* </pre>
*
* <code>repeated string reviewer_image_links = 16 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param index The index of the element to return.
* @return The reviewerImageLinks at the given index.
*/
java.lang.String getReviewerImageLinks(int index);
/**
*
*
* <pre>
* Optional. A URI to an image of the reviewed product created by the review
* author. The URI does not have to end with an image file extension.
* </pre>
*
* <code>repeated string reviewer_image_links = 16 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param index The index of the value to return.
* @return The bytes of the reviewerImageLinks at the given index.
*/
com.google.protobuf.ByteString getReviewerImageLinksBytes(int index);
/**
*
*
* <pre>
* Optional. Contains the ratings associated with the review.
* The minimum possible number for the rating. This should be the worst
* possible rating and should not be a value for no rating.
* </pre>
*
* <code>optional int64 min_rating = 17 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the minRating field is set.
*/
boolean hasMinRating();
/**
*
*
* <pre>
* Optional. Contains the ratings associated with the review.
* The minimum possible number for the rating. This should be the worst
* possible rating and should not be a value for no rating.
* </pre>
*
* <code>optional int64 min_rating = 17 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The minRating.
*/
long getMinRating();
/**
*
*
* <pre>
* Optional. The maximum possible number for the rating. The value of the max
* rating must be greater than the value of the min attribute.
* </pre>
*
* <code>optional int64 max_rating = 18 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the maxRating field is set.
*/
boolean hasMaxRating();
/**
*
*
* <pre>
* Optional. The maximum possible number for the rating. The value of the max
* rating must be greater than the value of the min attribute.
* </pre>
*
* <code>optional int64 max_rating = 18 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The maxRating.
*/
long getMaxRating();
/**
*
*
* <pre>
* Optional. The reviewer's overall rating of the product.
* </pre>
*
* <code>optional double rating = 19 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the rating field is set.
*/
boolean hasRating();
/**
*
*
* <pre>
* Optional. The reviewer's overall rating of the product.
* </pre>
*
* <code>optional double rating = 19 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The rating.
*/
double getRating();
/**
*
*
* <pre>
* Optional. Descriptive name of a product.
* </pre>
*
* <code>repeated string product_names = 20 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return A list containing the productNames.
*/
java.util.List<java.lang.String> getProductNamesList();
/**
*
*
* <pre>
* Optional. Descriptive name of a product.
* </pre>
*
* <code>repeated string product_names = 20 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The count of productNames.
*/
int getProductNamesCount();
/**
*
*
* <pre>
* Optional. Descriptive name of a product.
* </pre>
*
* <code>repeated string product_names = 20 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the element to return.
* @return The productNames at the given index.
*/
java.lang.String getProductNames(int index);
/**
*
*
* <pre>
* Optional. Descriptive name of a product.
* </pre>
*
* <code>repeated string product_names = 20 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the value to return.
* @return The bytes of the productNames at the given index.
*/
com.google.protobuf.ByteString getProductNamesBytes(int index);
/**
*
*
* <pre>
* Optional. The URI of the product. This URI can have the same value as the
* `review_link` element, if the review URI and the product URI are the
* same.
* </pre>
*
* <code>repeated string product_links = 21 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return A list containing the productLinks.
*/
java.util.List<java.lang.String> getProductLinksList();
/**
*
*
* <pre>
* Optional. The URI of the product. This URI can have the same value as the
* `review_link` element, if the review URI and the product URI are the
* same.
* </pre>
*
* <code>repeated string product_links = 21 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The count of productLinks.
*/
int getProductLinksCount();
/**
*
*
* <pre>
* Optional. The URI of the product. This URI can have the same value as the
* `review_link` element, if the review URI and the product URI are the
* same.
* </pre>
*
* <code>repeated string product_links = 21 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the element to return.
* @return The productLinks at the given index.
*/
java.lang.String getProductLinks(int index);
/**
*
*
* <pre>
* Optional. The URI of the product. This URI can have the same value as the
* `review_link` element, if the review URI and the product URI are the
* same.
* </pre>
*
* <code>repeated string product_links = 21 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the value to return.
* @return The bytes of the productLinks at the given index.
*/
com.google.protobuf.ByteString getProductLinksBytes(int index);
/**
*
*
* <pre>
* Optional. Contains ASINs (Amazon Standard Identification Numbers)
* associated with a product.
* </pre>
*
* <code>repeated string asins = 22 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return A list containing the asins.
*/
java.util.List<java.lang.String> getAsinsList();
/**
*
*
* <pre>
* Optional. Contains ASINs (Amazon Standard Identification Numbers)
* associated with a product.
* </pre>
*
* <code>repeated string asins = 22 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The count of asins.
*/
int getAsinsCount();
/**
*
*
* <pre>
* Optional. Contains ASINs (Amazon Standard Identification Numbers)
* associated with a product.
* </pre>
*
* <code>repeated string asins = 22 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the element to return.
* @return The asins at the given index.
*/
java.lang.String getAsins(int index);
/**
*
*
* <pre>
* Optional. Contains ASINs (Amazon Standard Identification Numbers)
* associated with a product.
* </pre>
*
* <code>repeated string asins = 22 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the value to return.
* @return The bytes of the asins at the given index.
*/
com.google.protobuf.ByteString getAsinsBytes(int index);
/**
*
*
* <pre>
* Optional. Contains GTINs (global trade item numbers) associated with a
* product. Sub-types of GTINs (e.g. UPC, EAN, ISBN, JAN) are supported.
* </pre>
*
* <code>repeated string gtins = 23 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return A list containing the gtins.
*/
java.util.List<java.lang.String> getGtinsList();
/**
*
*
* <pre>
* Optional. Contains GTINs (global trade item numbers) associated with a
* product. Sub-types of GTINs (e.g. UPC, EAN, ISBN, JAN) are supported.
* </pre>
*
* <code>repeated string gtins = 23 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The count of gtins.
*/
int getGtinsCount();
/**
*
*
* <pre>
* Optional. Contains GTINs (global trade item numbers) associated with a
* product. Sub-types of GTINs (e.g. UPC, EAN, ISBN, JAN) are supported.
* </pre>
*
* <code>repeated string gtins = 23 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the element to return.
* @return The gtins at the given index.
*/
java.lang.String getGtins(int index);
/**
*
*
* <pre>
* Optional. Contains GTINs (global trade item numbers) associated with a
* product. Sub-types of GTINs (e.g. UPC, EAN, ISBN, JAN) are supported.
* </pre>
*
* <code>repeated string gtins = 23 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the value to return.
* @return The bytes of the gtins at the given index.
*/
com.google.protobuf.ByteString getGtinsBytes(int index);
/**
*
*
* <pre>
* Optional. Contains MPNs (manufacturer part numbers) associated with a
* product.
* </pre>
*
* <code>repeated string mpns = 24 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return A list containing the mpns.
*/
java.util.List<java.lang.String> getMpnsList();
/**
*
*
* <pre>
* Optional. Contains MPNs (manufacturer part numbers) associated with a
* product.
* </pre>
*
* <code>repeated string mpns = 24 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The count of mpns.
*/
int getMpnsCount();
/**
*
*
* <pre>
* Optional. Contains MPNs (manufacturer part numbers) associated with a
* product.
* </pre>
*
* <code>repeated string mpns = 24 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the element to return.
* @return The mpns at the given index.
*/
java.lang.String getMpns(int index);
/**
*
*
* <pre>
* Optional. Contains MPNs (manufacturer part numbers) associated with a
* product.
* </pre>
*
* <code>repeated string mpns = 24 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the value to return.
* @return The bytes of the mpns at the given index.
*/
com.google.protobuf.ByteString getMpnsBytes(int index);
/**
*
*
* <pre>
* Optional. Contains SKUs (stock keeping units) associated with a product.
* Often this matches the product Offer Id in the product feed.
* </pre>
*
* <code>repeated string skus = 25 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return A list containing the skus.
*/
java.util.List<java.lang.String> getSkusList();
/**
*
*
* <pre>
* Optional. Contains SKUs (stock keeping units) associated with a product.
* Often this matches the product Offer Id in the product feed.
* </pre>
*
* <code>repeated string skus = 25 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The count of skus.
*/
int getSkusCount();
/**
*
*
* <pre>
* Optional. Contains SKUs (stock keeping units) associated with a product.
* Often this matches the product Offer Id in the product feed.
* </pre>
*
* <code>repeated string skus = 25 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the element to return.
* @return The skus at the given index.
*/
java.lang.String getSkus(int index);
/**
*
*
* <pre>
* Optional. Contains SKUs (stock keeping units) associated with a product.
* Often this matches the product Offer Id in the product feed.
* </pre>
*
* <code>repeated string skus = 25 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the value to return.
* @return The bytes of the skus at the given index.
*/
com.google.protobuf.ByteString getSkusBytes(int index);
/**
*
*
* <pre>
* Optional. Contains brand names associated with a product.
* </pre>
*
* <code>repeated string brands = 26 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return A list containing the brands.
*/
java.util.List<java.lang.String> getBrandsList();
/**
*
*
* <pre>
* Optional. Contains brand names associated with a product.
* </pre>
*
* <code>repeated string brands = 26 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The count of brands.
*/
int getBrandsCount();
/**
*
*
* <pre>
* Optional. Contains brand names associated with a product.
* </pre>
*
* <code>repeated string brands = 26 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the element to return.
* @return The brands at the given index.
*/
java.lang.String getBrands(int index);
/**
*
*
* <pre>
* Optional. Contains brand names associated with a product.
* </pre>
*
* <code>repeated string brands = 26 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param index The index of the value to return.
* @return The bytes of the brands at the given index.
*/
com.google.protobuf.ByteString getBrandsBytes(int index);
/**
*
*
* <pre>
* Optional. Indicates whether the review is marked as spam in the publisher's
* system.
* </pre>
*
* <code>optional bool is_spam = 27 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the isSpam field is set.
*/
boolean hasIsSpam();
/**
*
*
* <pre>
* Optional. Indicates whether the review is marked as spam in the publisher's
* system.
* </pre>
*
* <code>optional bool is_spam = 27 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The isSpam.
*/
boolean getIsSpam();
/**
*
*
* <pre>
* Optional. Indicates whether the reviewer's purchase is verified.
* </pre>
*
* <code>optional bool is_verified_purchase = 30 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return Whether the isVerifiedPurchase field is set.
*/
boolean hasIsVerifiedPurchase();
/**
*
*
* <pre>
* Optional. Indicates whether the reviewer's purchase is verified.
* </pre>
*
* <code>optional bool is_verified_purchase = 30 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The isVerifiedPurchase.
*/
boolean getIsVerifiedPurchase();
/**
*
*
* <pre>
* Optional. Indicates whether the review is incentivized.
* </pre>
*
* <code>optional bool is_incentivized_review = 31 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the isIncentivizedReview field is set.
*/
boolean hasIsIncentivizedReview();
/**
*
*
* <pre>
* Optional. Indicates whether the review is incentivized.
* </pre>
*
* <code>optional bool is_incentivized_review = 31 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The isIncentivizedReview.
*/
boolean getIsIncentivizedReview();
/**
*
*
* <pre>
* Optional. The method used to collect the review.
* </pre>
*
* <code>
* .google.shopping.merchant.reviews.v1beta.ProductReviewAttributes.CollectionMethod collection_method = 28 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The enum numeric value on the wire for collectionMethod.
*/
int getCollectionMethodValue();
/**
*
*
* <pre>
* Optional. The method used to collect the review.
* </pre>
*
* <code>
* .google.shopping.merchant.reviews.v1beta.ProductReviewAttributes.CollectionMethod collection_method = 28 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The collectionMethod.
*/
com.google.shopping.merchant.reviews.v1beta.ProductReviewAttributes.CollectionMethod
getCollectionMethod();
/**
*
*
* <pre>
* Optional. A permanent, unique identifier for the transaction associated
* with the review in the publisher's system. This ID can be used to indicate
* that multiple reviews are associated with the same transaction.
* </pre>
*
* <code>string transaction_id = 29 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The transactionId.
*/
java.lang.String getTransactionId();
/**
*
*
* <pre>
* Optional. A permanent, unique identifier for the transaction associated
* with the review in the publisher's system. This ID can be used to indicate
* that multiple reviews are associated with the same transaction.
* </pre>
*
* <code>string transaction_id = 29 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for transactionId.
*/
com.google.protobuf.ByteString getTransactionIdBytes();
}
|
googleapis/google-cloud-java | 36,535 | java-discoveryengine/proto-google-cloud-discoveryengine-v1alpha/src/main/java/com/google/cloud/discoveryengine/v1alpha/ListEvaluationsRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/discoveryengine/v1alpha/evaluation_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.discoveryengine.v1alpha;
/**
*
*
* <pre>
* Request message for
* [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations]
* method.
* </pre>
*
* Protobuf type {@code google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest}
*/
public final class ListEvaluationsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest)
ListEvaluationsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListEvaluationsRequest.newBuilder() to construct.
private ListEvaluationsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListEvaluationsRequest() {
parent_ = "";
pageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListEvaluationsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.discoveryengine.v1alpha.EvaluationServiceProto
.internal_static_google_cloud_discoveryengine_v1alpha_ListEvaluationsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.discoveryengine.v1alpha.EvaluationServiceProto
.internal_static_google_cloud_discoveryengine_v1alpha_ListEvaluationsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest.class,
com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent location resource name, such as
* `projects/{project}/locations/{location}`.
*
* If the caller does not have permission to list
* [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s under this
* location, regardless of whether or not this location exists, a
* `PERMISSION_DENIED` error is returned.
* </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 location resource name, such as
* `projects/{project}/locations/{location}`.
*
* If the caller does not have permission to list
* [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s under this
* location, regardless of whether or not this location exists, a
* `PERMISSION_DENIED` error is returned.
* </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
* [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s to return.
* If unspecified, defaults to 100. The maximum allowed value is 1000. Values
* above 1000 will be coerced to 1000.
*
* If this field is negative, an `INVALID_ARGUMENT` error is returned.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A page token
* [ListEvaluationsResponse.next_page_token][google.cloud.discoveryengine.v1alpha.ListEvaluationsResponse.next_page_token],
* received from a previous
* [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations]
* call. Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to
* [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations]
* must match the call that provided the page token. Otherwise, an
* `INVALID_ARGUMENT` error is returned.
* </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
* [ListEvaluationsResponse.next_page_token][google.cloud.discoveryengine.v1alpha.ListEvaluationsResponse.next_page_token],
* received from a previous
* [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations]
* call. Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to
* [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations]
* must match the call that provided the page token. Otherwise, an
* `INVALID_ARGUMENT` error is returned.
* </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;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest)) {
return super.equals(obj);
}
com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest other =
(com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest 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
* [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations]
* method.
* </pre>
*
* Protobuf type {@code google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest)
com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.discoveryengine.v1alpha.EvaluationServiceProto
.internal_static_google_cloud_discoveryengine_v1alpha_ListEvaluationsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.discoveryengine.v1alpha.EvaluationServiceProto
.internal_static_google_cloud_discoveryengine_v1alpha_ListEvaluationsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest.class,
com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest.Builder.class);
}
// Construct using com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.discoveryengine.v1alpha.EvaluationServiceProto
.internal_static_google_cloud_discoveryengine_v1alpha_ListEvaluationsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest
getDefaultInstanceForType() {
return com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest build() {
com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest buildPartial() {
com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest result =
new com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest) {
return mergeFrom((com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest other) {
if (other
== com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent location resource name, such as
* `projects/{project}/locations/{location}`.
*
* If the caller does not have permission to list
* [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s under this
* location, regardless of whether or not this location exists, a
* `PERMISSION_DENIED` error is returned.
* </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 location resource name, such as
* `projects/{project}/locations/{location}`.
*
* If the caller does not have permission to list
* [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s under this
* location, regardless of whether or not this location exists, a
* `PERMISSION_DENIED` error is returned.
* </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 location resource name, such as
* `projects/{project}/locations/{location}`.
*
* If the caller does not have permission to list
* [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s under this
* location, regardless of whether or not this location exists, a
* `PERMISSION_DENIED` error is returned.
* </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 location resource name, such as
* `projects/{project}/locations/{location}`.
*
* If the caller does not have permission to list
* [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s under this
* location, regardless of whether or not this location exists, a
* `PERMISSION_DENIED` error is returned.
* </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 location resource name, such as
* `projects/{project}/locations/{location}`.
*
* If the caller does not have permission to list
* [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s under this
* location, regardless of whether or not this location exists, a
* `PERMISSION_DENIED` error is returned.
* </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
* [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s to return.
* If unspecified, defaults to 100. The maximum allowed value is 1000. Values
* above 1000 will be coerced to 1000.
*
* If this field is negative, an `INVALID_ARGUMENT` error is returned.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Maximum number of
* [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s to return.
* If unspecified, defaults to 100. The maximum allowed value is 1000. Values
* above 1000 will be coerced to 1000.
*
* If this field is negative, an `INVALID_ARGUMENT` error is returned.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Maximum number of
* [Evaluation][google.cloud.discoveryengine.v1alpha.Evaluation]s to return.
* If unspecified, defaults to 100. The maximum allowed value is 1000. Values
* above 1000 will be coerced to 1000.
*
* If this field is negative, an `INVALID_ARGUMENT` error is returned.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A page token
* [ListEvaluationsResponse.next_page_token][google.cloud.discoveryengine.v1alpha.ListEvaluationsResponse.next_page_token],
* received from a previous
* [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations]
* call. Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to
* [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations]
* must match the call that provided the page token. Otherwise, an
* `INVALID_ARGUMENT` error is returned.
* </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
* [ListEvaluationsResponse.next_page_token][google.cloud.discoveryengine.v1alpha.ListEvaluationsResponse.next_page_token],
* received from a previous
* [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations]
* call. Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to
* [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations]
* must match the call that provided the page token. Otherwise, an
* `INVALID_ARGUMENT` error is returned.
* </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
* [ListEvaluationsResponse.next_page_token][google.cloud.discoveryengine.v1alpha.ListEvaluationsResponse.next_page_token],
* received from a previous
* [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations]
* call. Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to
* [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations]
* must match the call that provided the page token. Otherwise, an
* `INVALID_ARGUMENT` error is returned.
* </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
* [ListEvaluationsResponse.next_page_token][google.cloud.discoveryengine.v1alpha.ListEvaluationsResponse.next_page_token],
* received from a previous
* [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations]
* call. Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to
* [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations]
* must match the call that provided the page token. Otherwise, an
* `INVALID_ARGUMENT` error is returned.
* </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
* [ListEvaluationsResponse.next_page_token][google.cloud.discoveryengine.v1alpha.ListEvaluationsResponse.next_page_token],
* received from a previous
* [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations]
* call. Provide this to retrieve the subsequent page.
*
* When paginating, all other parameters provided to
* [EvaluationService.ListEvaluations][google.cloud.discoveryengine.v1alpha.EvaluationService.ListEvaluations]
* must match the call that provided the page token. Otherwise, an
* `INVALID_ARGUMENT` error is returned.
* </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;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest)
private static final com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest();
}
public static com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListEvaluationsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListEvaluationsRequest>() {
@java.lang.Override
public ListEvaluationsRequest 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<ListEvaluationsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListEvaluationsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1alpha.ListEvaluationsRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,544 | java-shopping-merchant-inventories/proto-google-shopping-merchant-inventories-v1beta/src/main/java/com/google/shopping/merchant/inventories/v1beta/InsertRegionalInventoryRequest.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/inventories/v1beta/regionalinventory.proto
// Protobuf Java Version: 3.25.8
package com.google.shopping.merchant.inventories.v1beta;
/**
*
*
* <pre>
* Request message for the `InsertRegionalInventory` method.
* </pre>
*
* Protobuf type {@code google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest}
*/
public final class InsertRegionalInventoryRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest)
InsertRegionalInventoryRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use InsertRegionalInventoryRequest.newBuilder() to construct.
private InsertRegionalInventoryRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private InsertRegionalInventoryRequest() {
parent_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new InsertRegionalInventoryRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.shopping.merchant.inventories.v1beta.RegionalInventoryProto
.internal_static_google_shopping_merchant_inventories_v1beta_InsertRegionalInventoryRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.shopping.merchant.inventories.v1beta.RegionalInventoryProto
.internal_static_google_shopping_merchant_inventories_v1beta_InsertRegionalInventoryRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest.class,
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest.Builder
.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The account and product where this inventory will be inserted.
* Format: `accounts/{account}/products/{product}`
* </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 account and product where this inventory will be inserted.
* Format: `accounts/{account}/products/{product}`
* </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 REGIONAL_INVENTORY_FIELD_NUMBER = 2;
private com.google.shopping.merchant.inventories.v1beta.RegionalInventory regionalInventory_;
/**
*
*
* <pre>
* Required. Regional inventory information to add to the product. If the
* product already has a `RegionalInventory` resource for the same `region`,
* full replacement of the `RegionalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.RegionalInventory regional_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the regionalInventory field is set.
*/
@java.lang.Override
public boolean hasRegionalInventory() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. Regional inventory information to add to the product. If the
* product already has a `RegionalInventory` resource for the same `region`,
* full replacement of the `RegionalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.RegionalInventory regional_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The regionalInventory.
*/
@java.lang.Override
public com.google.shopping.merchant.inventories.v1beta.RegionalInventory getRegionalInventory() {
return regionalInventory_ == null
? com.google.shopping.merchant.inventories.v1beta.RegionalInventory.getDefaultInstance()
: regionalInventory_;
}
/**
*
*
* <pre>
* Required. Regional inventory information to add to the product. If the
* product already has a `RegionalInventory` resource for the same `region`,
* full replacement of the `RegionalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.RegionalInventory regional_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.shopping.merchant.inventories.v1beta.RegionalInventoryOrBuilder
getRegionalInventoryOrBuilder() {
return regionalInventory_ == null
? com.google.shopping.merchant.inventories.v1beta.RegionalInventory.getDefaultInstance()
: regionalInventory_;
}
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, getRegionalInventory());
}
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, getRegionalInventory());
}
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.inventories.v1beta.InsertRegionalInventoryRequest)) {
return super.equals(obj);
}
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest other =
(com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (hasRegionalInventory() != other.hasRegionalInventory()) return false;
if (hasRegionalInventory()) {
if (!getRegionalInventory().equals(other.getRegionalInventory())) 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 (hasRegionalInventory()) {
hash = (37 * hash) + REGIONAL_INVENTORY_FIELD_NUMBER;
hash = (53 * hash) + getRegionalInventory().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest
parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest
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.inventories.v1beta.InsertRegionalInventoryRequest
parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest
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.inventories.v1beta.InsertRegionalInventoryRequest
parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest
parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest
parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest
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.inventories.v1beta.InsertRegionalInventoryRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest
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.inventories.v1beta.InsertRegionalInventoryRequest
parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest
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.inventories.v1beta.InsertRegionalInventoryRequest 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 `InsertRegionalInventory` method.
* </pre>
*
* Protobuf type {@code
* google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest)
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.shopping.merchant.inventories.v1beta.RegionalInventoryProto
.internal_static_google_shopping_merchant_inventories_v1beta_InsertRegionalInventoryRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.shopping.merchant.inventories.v1beta.RegionalInventoryProto
.internal_static_google_shopping_merchant_inventories_v1beta_InsertRegionalInventoryRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest.class,
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest.Builder
.class);
}
// Construct using
// com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getRegionalInventoryFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
regionalInventory_ = null;
if (regionalInventoryBuilder_ != null) {
regionalInventoryBuilder_.dispose();
regionalInventoryBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.shopping.merchant.inventories.v1beta.RegionalInventoryProto
.internal_static_google_shopping_merchant_inventories_v1beta_InsertRegionalInventoryRequest_descriptor;
}
@java.lang.Override
public com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest
getDefaultInstanceForType() {
return com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest build() {
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest result =
buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest
buildPartial() {
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest result =
new com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.regionalInventory_ =
regionalInventoryBuilder_ == null
? regionalInventory_
: regionalInventoryBuilder_.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.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest) {
return mergeFrom(
(com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest other) {
if (other
== com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest
.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasRegionalInventory()) {
mergeRegionalInventory(other.getRegionalInventory());
}
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(
getRegionalInventoryFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The account and product where this inventory will be inserted.
* Format: `accounts/{account}/products/{product}`
* </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 account and product where this inventory will be inserted.
* Format: `accounts/{account}/products/{product}`
* </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 account and product where this inventory will be inserted.
* Format: `accounts/{account}/products/{product}`
* </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 account and product where this inventory will be inserted.
* Format: `accounts/{account}/products/{product}`
* </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 account and product where this inventory will be inserted.
* Format: `accounts/{account}/products/{product}`
* </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.shopping.merchant.inventories.v1beta.RegionalInventory regionalInventory_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.shopping.merchant.inventories.v1beta.RegionalInventory,
com.google.shopping.merchant.inventories.v1beta.RegionalInventory.Builder,
com.google.shopping.merchant.inventories.v1beta.RegionalInventoryOrBuilder>
regionalInventoryBuilder_;
/**
*
*
* <pre>
* Required. Regional inventory information to add to the product. If the
* product already has a `RegionalInventory` resource for the same `region`,
* full replacement of the `RegionalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.RegionalInventory regional_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the regionalInventory field is set.
*/
public boolean hasRegionalInventory() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. Regional inventory information to add to the product. If the
* product already has a `RegionalInventory` resource for the same `region`,
* full replacement of the `RegionalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.RegionalInventory regional_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The regionalInventory.
*/
public com.google.shopping.merchant.inventories.v1beta.RegionalInventory
getRegionalInventory() {
if (regionalInventoryBuilder_ == null) {
return regionalInventory_ == null
? com.google.shopping.merchant.inventories.v1beta.RegionalInventory.getDefaultInstance()
: regionalInventory_;
} else {
return regionalInventoryBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Regional inventory information to add to the product. If the
* product already has a `RegionalInventory` resource for the same `region`,
* full replacement of the `RegionalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.RegionalInventory regional_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setRegionalInventory(
com.google.shopping.merchant.inventories.v1beta.RegionalInventory value) {
if (regionalInventoryBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
regionalInventory_ = value;
} else {
regionalInventoryBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Regional inventory information to add to the product. If the
* product already has a `RegionalInventory` resource for the same `region`,
* full replacement of the `RegionalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.RegionalInventory regional_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setRegionalInventory(
com.google.shopping.merchant.inventories.v1beta.RegionalInventory.Builder builderForValue) {
if (regionalInventoryBuilder_ == null) {
regionalInventory_ = builderForValue.build();
} else {
regionalInventoryBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Regional inventory information to add to the product. If the
* product already has a `RegionalInventory` resource for the same `region`,
* full replacement of the `RegionalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.RegionalInventory regional_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeRegionalInventory(
com.google.shopping.merchant.inventories.v1beta.RegionalInventory value) {
if (regionalInventoryBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& regionalInventory_ != null
&& regionalInventory_
!= com.google.shopping.merchant.inventories.v1beta.RegionalInventory
.getDefaultInstance()) {
getRegionalInventoryBuilder().mergeFrom(value);
} else {
regionalInventory_ = value;
}
} else {
regionalInventoryBuilder_.mergeFrom(value);
}
if (regionalInventory_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Regional inventory information to add to the product. If the
* product already has a `RegionalInventory` resource for the same `region`,
* full replacement of the `RegionalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.RegionalInventory regional_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearRegionalInventory() {
bitField0_ = (bitField0_ & ~0x00000002);
regionalInventory_ = null;
if (regionalInventoryBuilder_ != null) {
regionalInventoryBuilder_.dispose();
regionalInventoryBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Regional inventory information to add to the product. If the
* product already has a `RegionalInventory` resource for the same `region`,
* full replacement of the `RegionalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.RegionalInventory regional_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.shopping.merchant.inventories.v1beta.RegionalInventory.Builder
getRegionalInventoryBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getRegionalInventoryFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Regional inventory information to add to the product. If the
* product already has a `RegionalInventory` resource for the same `region`,
* full replacement of the `RegionalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.RegionalInventory regional_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.shopping.merchant.inventories.v1beta.RegionalInventoryOrBuilder
getRegionalInventoryOrBuilder() {
if (regionalInventoryBuilder_ != null) {
return regionalInventoryBuilder_.getMessageOrBuilder();
} else {
return regionalInventory_ == null
? com.google.shopping.merchant.inventories.v1beta.RegionalInventory.getDefaultInstance()
: regionalInventory_;
}
}
/**
*
*
* <pre>
* Required. Regional inventory information to add to the product. If the
* product already has a `RegionalInventory` resource for the same `region`,
* full replacement of the `RegionalInventory` resource is performed.
* </pre>
*
* <code>
* .google.shopping.merchant.inventories.v1beta.RegionalInventory regional_inventory = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.shopping.merchant.inventories.v1beta.RegionalInventory,
com.google.shopping.merchant.inventories.v1beta.RegionalInventory.Builder,
com.google.shopping.merchant.inventories.v1beta.RegionalInventoryOrBuilder>
getRegionalInventoryFieldBuilder() {
if (regionalInventoryBuilder_ == null) {
regionalInventoryBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.shopping.merchant.inventories.v1beta.RegionalInventory,
com.google.shopping.merchant.inventories.v1beta.RegionalInventory.Builder,
com.google.shopping.merchant.inventories.v1beta.RegionalInventoryOrBuilder>(
getRegionalInventory(), getParentForChildren(), isClean());
regionalInventory_ = null;
}
return regionalInventoryBuilder_;
}
@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.inventories.v1beta.InsertRegionalInventoryRequest)
}
// @@protoc_insertion_point(class_scope:google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest)
private static final com.google.shopping.merchant.inventories.v1beta
.InsertRegionalInventoryRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE =
new com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest();
}
public static com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<InsertRegionalInventoryRequest> PARSER =
new com.google.protobuf.AbstractParser<InsertRegionalInventoryRequest>() {
@java.lang.Override
public InsertRegionalInventoryRequest 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<InsertRegionalInventoryRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<InsertRegionalInventoryRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-api-java-client-services | 36,654 | clients/google-api-services-compute/v1/1.28.0/com/google/api/services/compute/model/Image.java | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.compute.model;
/**
* Represents an Image resource.
*
* You can use images to create boot disks for your VM instances. For more information, read Images.
* (== resource_for beta.images ==) (== resource_for v1.images ==)
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class Image extends com.google.api.client.json.GenericJson {
/**
* Size of the image tar.gz archive stored in Google Cloud Storage (in bytes).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long archiveSizeBytes;
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String creationTimestamp;
/**
* The deprecation status associated with this image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DeprecationStatus deprecated;
/**
* An optional description of this resource. Provide this property when you create the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* Size of the image when restored onto a persistent disk (in GB).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long diskSizeGb;
/**
* The name of the image family to which this image belongs. You can create disks by specifying an
* image family instead of a specific image name. The image family always returns its latest image
* that is not deprecated. The name of the image family must comply with RFC1035.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String family;
/**
* A list of features to enable on the guest operating system. Applicable only for bootable
* images. Read Enabling guest operating system features to see a list of available options.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GuestOsFeature> guestOsFeatures;
static {
// hack to force ProGuard to consider GuestOsFeature used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(GuestOsFeature.class);
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.math.BigInteger id;
/**
* Encrypts the image using a customer-supplied encryption key.
*
* After you encrypt an image with a customer-supplied key, you must provide the same key if you
* use the image later (e.g. to create a disk from the image).
*
* Customer-supplied encryption keys do not protect access to metadata of the disk.
*
* If you do not provide an encryption key when creating the image, then the disk will be
* encrypted using an automatically generated key and you do not need to provide a key to use the
* image later.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey imageEncryptionKey;
/**
* [Output Only] Type of the resource. Always compute#image for images.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String labelFingerprint;
/**
* Labels to apply to this image. These can be later modified by the setLabels method.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, java.lang.String> labels;
/**
* Integer license codes indicating which licenses are attached to this image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.util.List<java.lang.Long> licenseCodes;
/**
* Any applicable license URI.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> licenses;
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* The parameters of the raw disk image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private RawDisk rawDisk;
/**
* [Output Only] Server-defined URL for the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String selfLink;
/**
* URL of the source disk used to create this image. This can be a full or valid partial URL. You
* must provide either this property or the rawDisk.source property but not both to create an
* image. For example, the following are valid values: -
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/disks/disk -
* projects/project/zones/zone/disks/disk - zones/zone/disks/disk
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceDisk;
/**
* The customer-supplied encryption key of the source disk. Required if the source disk is
* protected by a customer-supplied encryption key.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey sourceDiskEncryptionKey;
/**
* [Output Only] The ID value of the disk used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given disk
* name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceDiskId;
/**
* URL of the source image used to create this image. This can be a full or valid partial URL. You
* must provide exactly one of: - this property, or - the rawDisk.source property, or - the
* sourceDisk property in order to create an image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceImage;
/**
* The customer-supplied encryption key of the source image. Required if the source image is
* protected by a customer-supplied encryption key.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey sourceImageEncryptionKey;
/**
* [Output Only] The ID value of the image used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given image
* name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceImageId;
/**
* URL of the source snapshot used to create this image. This can be a full or valid partial URL.
* You must provide exactly one of: - this property, or - the sourceImage property, or - the
* rawDisk.source property, or - the sourceDisk property in order to create an image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceSnapshot;
/**
* The customer-supplied encryption key of the source snapshot. Required if the source snapshot is
* protected by a customer-supplied encryption key.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey sourceSnapshotEncryptionKey;
/**
* [Output Only] The ID value of the snapshot used to create this image. This value may be used to
* determine whether the snapshot was taken from the current or a previous instance of a given
* snapshot name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceSnapshotId;
/**
* The type of the image used to create this disk. The default and only value is RAW
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceType;
/**
* [Output Only] The status of the image. An image can be used to create other resources, such as
* instances, only after the image has been successfully created and the status is set to READY.
* Possible values are FAILED, PENDING, or READY.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String status;
/**
* Cloud Storage bucket storage location of the image (regional or multi-regional).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> storageLocations;
/**
* Size of the image tar.gz archive stored in Google Cloud Storage (in bytes).
* @return value or {@code null} for none
*/
public java.lang.Long getArchiveSizeBytes() {
return archiveSizeBytes;
}
/**
* Size of the image tar.gz archive stored in Google Cloud Storage (in bytes).
* @param archiveSizeBytes archiveSizeBytes or {@code null} for none
*/
public Image setArchiveSizeBytes(java.lang.Long archiveSizeBytes) {
this.archiveSizeBytes = archiveSizeBytes;
return this;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @return value or {@code null} for none
*/
public java.lang.String getCreationTimestamp() {
return creationTimestamp;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @param creationTimestamp creationTimestamp or {@code null} for none
*/
public Image setCreationTimestamp(java.lang.String creationTimestamp) {
this.creationTimestamp = creationTimestamp;
return this;
}
/**
* The deprecation status associated with this image.
* @return value or {@code null} for none
*/
public DeprecationStatus getDeprecated() {
return deprecated;
}
/**
* The deprecation status associated with this image.
* @param deprecated deprecated or {@code null} for none
*/
public Image setDeprecated(DeprecationStatus deprecated) {
this.deprecated = deprecated;
return this;
}
/**
* An optional description of this resource. Provide this property when you create the resource.
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* An optional description of this resource. Provide this property when you create the resource.
* @param description description or {@code null} for none
*/
public Image setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* Size of the image when restored onto a persistent disk (in GB).
* @return value or {@code null} for none
*/
public java.lang.Long getDiskSizeGb() {
return diskSizeGb;
}
/**
* Size of the image when restored onto a persistent disk (in GB).
* @param diskSizeGb diskSizeGb or {@code null} for none
*/
public Image setDiskSizeGb(java.lang.Long diskSizeGb) {
this.diskSizeGb = diskSizeGb;
return this;
}
/**
* The name of the image family to which this image belongs. You can create disks by specifying an
* image family instead of a specific image name. The image family always returns its latest image
* that is not deprecated. The name of the image family must comply with RFC1035.
* @return value or {@code null} for none
*/
public java.lang.String getFamily() {
return family;
}
/**
* The name of the image family to which this image belongs. You can create disks by specifying an
* image family instead of a specific image name. The image family always returns its latest image
* that is not deprecated. The name of the image family must comply with RFC1035.
* @param family family or {@code null} for none
*/
public Image setFamily(java.lang.String family) {
this.family = family;
return this;
}
/**
* A list of features to enable on the guest operating system. Applicable only for bootable
* images. Read Enabling guest operating system features to see a list of available options.
* @return value or {@code null} for none
*/
public java.util.List<GuestOsFeature> getGuestOsFeatures() {
return guestOsFeatures;
}
/**
* A list of features to enable on the guest operating system. Applicable only for bootable
* images. Read Enabling guest operating system features to see a list of available options.
* @param guestOsFeatures guestOsFeatures or {@code null} for none
*/
public Image setGuestOsFeatures(java.util.List<GuestOsFeature> guestOsFeatures) {
this.guestOsFeatures = guestOsFeatures;
return this;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @return value or {@code null} for none
*/
public java.math.BigInteger getId() {
return id;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @param id id or {@code null} for none
*/
public Image setId(java.math.BigInteger id) {
this.id = id;
return this;
}
/**
* Encrypts the image using a customer-supplied encryption key.
*
* After you encrypt an image with a customer-supplied key, you must provide the same key if you
* use the image later (e.g. to create a disk from the image).
*
* Customer-supplied encryption keys do not protect access to metadata of the disk.
*
* If you do not provide an encryption key when creating the image, then the disk will be
* encrypted using an automatically generated key and you do not need to provide a key to use the
* image later.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getImageEncryptionKey() {
return imageEncryptionKey;
}
/**
* Encrypts the image using a customer-supplied encryption key.
*
* After you encrypt an image with a customer-supplied key, you must provide the same key if you
* use the image later (e.g. to create a disk from the image).
*
* Customer-supplied encryption keys do not protect access to metadata of the disk.
*
* If you do not provide an encryption key when creating the image, then the disk will be
* encrypted using an automatically generated key and you do not need to provide a key to use the
* image later.
* @param imageEncryptionKey imageEncryptionKey or {@code null} for none
*/
public Image setImageEncryptionKey(CustomerEncryptionKey imageEncryptionKey) {
this.imageEncryptionKey = imageEncryptionKey;
return this;
}
/**
* [Output Only] Type of the resource. Always compute#image for images.
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* [Output Only] Type of the resource. Always compute#image for images.
* @param kind kind or {@code null} for none
*/
public Image setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #decodeLabelFingerprint()
* @return value or {@code null} for none
*/
public java.lang.String getLabelFingerprint() {
return labelFingerprint;
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #getLabelFingerprint()
* @return Base64 decoded value or {@code null} for none
*
* @since 1.14
*/
public byte[] decodeLabelFingerprint() {
return com.google.api.client.util.Base64.decodeBase64(labelFingerprint);
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #encodeLabelFingerprint()
* @param labelFingerprint labelFingerprint or {@code null} for none
*/
public Image setLabelFingerprint(java.lang.String labelFingerprint) {
this.labelFingerprint = labelFingerprint;
return this;
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #setLabelFingerprint()
*
* <p>
* The value is encoded Base64 or {@code null} for none.
* </p>
*
* @since 1.14
*/
public Image encodeLabelFingerprint(byte[] labelFingerprint) {
this.labelFingerprint = com.google.api.client.util.Base64.encodeBase64URLSafeString(labelFingerprint);
return this;
}
/**
* Labels to apply to this image. These can be later modified by the setLabels method.
* @return value or {@code null} for none
*/
public java.util.Map<String, java.lang.String> getLabels() {
return labels;
}
/**
* Labels to apply to this image. These can be later modified by the setLabels method.
* @param labels labels or {@code null} for none
*/
public Image setLabels(java.util.Map<String, java.lang.String> labels) {
this.labels = labels;
return this;
}
/**
* Integer license codes indicating which licenses are attached to this image.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.Long> getLicenseCodes() {
return licenseCodes;
}
/**
* Integer license codes indicating which licenses are attached to this image.
* @param licenseCodes licenseCodes or {@code null} for none
*/
public Image setLicenseCodes(java.util.List<java.lang.Long> licenseCodes) {
this.licenseCodes = licenseCodes;
return this;
}
/**
* Any applicable license URI.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getLicenses() {
return licenses;
}
/**
* Any applicable license URI.
* @param licenses licenses or {@code null} for none
*/
public Image setLicenses(java.util.List<java.lang.String> licenses) {
this.licenses = licenses;
return this;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* @param name name or {@code null} for none
*/
public Image setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* The parameters of the raw disk image.
* @return value or {@code null} for none
*/
public RawDisk getRawDisk() {
return rawDisk;
}
/**
* The parameters of the raw disk image.
* @param rawDisk rawDisk or {@code null} for none
*/
public Image setRawDisk(RawDisk rawDisk) {
this.rawDisk = rawDisk;
return this;
}
/**
* [Output Only] Server-defined URL for the resource.
* @return value or {@code null} for none
*/
public java.lang.String getSelfLink() {
return selfLink;
}
/**
* [Output Only] Server-defined URL for the resource.
* @param selfLink selfLink or {@code null} for none
*/
public Image setSelfLink(java.lang.String selfLink) {
this.selfLink = selfLink;
return this;
}
/**
* URL of the source disk used to create this image. This can be a full or valid partial URL. You
* must provide either this property or the rawDisk.source property but not both to create an
* image. For example, the following are valid values: -
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/disks/disk -
* projects/project/zones/zone/disks/disk - zones/zone/disks/disk
* @return value or {@code null} for none
*/
public java.lang.String getSourceDisk() {
return sourceDisk;
}
/**
* URL of the source disk used to create this image. This can be a full or valid partial URL. You
* must provide either this property or the rawDisk.source property but not both to create an
* image. For example, the following are valid values: -
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/disks/disk -
* projects/project/zones/zone/disks/disk - zones/zone/disks/disk
* @param sourceDisk sourceDisk or {@code null} for none
*/
public Image setSourceDisk(java.lang.String sourceDisk) {
this.sourceDisk = sourceDisk;
return this;
}
/**
* The customer-supplied encryption key of the source disk. Required if the source disk is
* protected by a customer-supplied encryption key.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getSourceDiskEncryptionKey() {
return sourceDiskEncryptionKey;
}
/**
* The customer-supplied encryption key of the source disk. Required if the source disk is
* protected by a customer-supplied encryption key.
* @param sourceDiskEncryptionKey sourceDiskEncryptionKey or {@code null} for none
*/
public Image setSourceDiskEncryptionKey(CustomerEncryptionKey sourceDiskEncryptionKey) {
this.sourceDiskEncryptionKey = sourceDiskEncryptionKey;
return this;
}
/**
* [Output Only] The ID value of the disk used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given disk
* name.
* @return value or {@code null} for none
*/
public java.lang.String getSourceDiskId() {
return sourceDiskId;
}
/**
* [Output Only] The ID value of the disk used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given disk
* name.
* @param sourceDiskId sourceDiskId or {@code null} for none
*/
public Image setSourceDiskId(java.lang.String sourceDiskId) {
this.sourceDiskId = sourceDiskId;
return this;
}
/**
* URL of the source image used to create this image. This can be a full or valid partial URL. You
* must provide exactly one of: - this property, or - the rawDisk.source property, or - the
* sourceDisk property in order to create an image.
* @return value or {@code null} for none
*/
public java.lang.String getSourceImage() {
return sourceImage;
}
/**
* URL of the source image used to create this image. This can be a full or valid partial URL. You
* must provide exactly one of: - this property, or - the rawDisk.source property, or - the
* sourceDisk property in order to create an image.
* @param sourceImage sourceImage or {@code null} for none
*/
public Image setSourceImage(java.lang.String sourceImage) {
this.sourceImage = sourceImage;
return this;
}
/**
* The customer-supplied encryption key of the source image. Required if the source image is
* protected by a customer-supplied encryption key.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getSourceImageEncryptionKey() {
return sourceImageEncryptionKey;
}
/**
* The customer-supplied encryption key of the source image. Required if the source image is
* protected by a customer-supplied encryption key.
* @param sourceImageEncryptionKey sourceImageEncryptionKey or {@code null} for none
*/
public Image setSourceImageEncryptionKey(CustomerEncryptionKey sourceImageEncryptionKey) {
this.sourceImageEncryptionKey = sourceImageEncryptionKey;
return this;
}
/**
* [Output Only] The ID value of the image used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given image
* name.
* @return value or {@code null} for none
*/
public java.lang.String getSourceImageId() {
return sourceImageId;
}
/**
* [Output Only] The ID value of the image used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given image
* name.
* @param sourceImageId sourceImageId or {@code null} for none
*/
public Image setSourceImageId(java.lang.String sourceImageId) {
this.sourceImageId = sourceImageId;
return this;
}
/**
* URL of the source snapshot used to create this image. This can be a full or valid partial URL.
* You must provide exactly one of: - this property, or - the sourceImage property, or - the
* rawDisk.source property, or - the sourceDisk property in order to create an image.
* @return value or {@code null} for none
*/
public java.lang.String getSourceSnapshot() {
return sourceSnapshot;
}
/**
* URL of the source snapshot used to create this image. This can be a full or valid partial URL.
* You must provide exactly one of: - this property, or - the sourceImage property, or - the
* rawDisk.source property, or - the sourceDisk property in order to create an image.
* @param sourceSnapshot sourceSnapshot or {@code null} for none
*/
public Image setSourceSnapshot(java.lang.String sourceSnapshot) {
this.sourceSnapshot = sourceSnapshot;
return this;
}
/**
* The customer-supplied encryption key of the source snapshot. Required if the source snapshot is
* protected by a customer-supplied encryption key.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getSourceSnapshotEncryptionKey() {
return sourceSnapshotEncryptionKey;
}
/**
* The customer-supplied encryption key of the source snapshot. Required if the source snapshot is
* protected by a customer-supplied encryption key.
* @param sourceSnapshotEncryptionKey sourceSnapshotEncryptionKey or {@code null} for none
*/
public Image setSourceSnapshotEncryptionKey(CustomerEncryptionKey sourceSnapshotEncryptionKey) {
this.sourceSnapshotEncryptionKey = sourceSnapshotEncryptionKey;
return this;
}
/**
* [Output Only] The ID value of the snapshot used to create this image. This value may be used to
* determine whether the snapshot was taken from the current or a previous instance of a given
* snapshot name.
* @return value or {@code null} for none
*/
public java.lang.String getSourceSnapshotId() {
return sourceSnapshotId;
}
/**
* [Output Only] The ID value of the snapshot used to create this image. This value may be used to
* determine whether the snapshot was taken from the current or a previous instance of a given
* snapshot name.
* @param sourceSnapshotId sourceSnapshotId or {@code null} for none
*/
public Image setSourceSnapshotId(java.lang.String sourceSnapshotId) {
this.sourceSnapshotId = sourceSnapshotId;
return this;
}
/**
* The type of the image used to create this disk. The default and only value is RAW
* @return value or {@code null} for none
*/
public java.lang.String getSourceType() {
return sourceType;
}
/**
* The type of the image used to create this disk. The default and only value is RAW
* @param sourceType sourceType or {@code null} for none
*/
public Image setSourceType(java.lang.String sourceType) {
this.sourceType = sourceType;
return this;
}
/**
* [Output Only] The status of the image. An image can be used to create other resources, such as
* instances, only after the image has been successfully created and the status is set to READY.
* Possible values are FAILED, PENDING, or READY.
* @return value or {@code null} for none
*/
public java.lang.String getStatus() {
return status;
}
/**
* [Output Only] The status of the image. An image can be used to create other resources, such as
* instances, only after the image has been successfully created and the status is set to READY.
* Possible values are FAILED, PENDING, or READY.
* @param status status or {@code null} for none
*/
public Image setStatus(java.lang.String status) {
this.status = status;
return this;
}
/**
* Cloud Storage bucket storage location of the image (regional or multi-regional).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getStorageLocations() {
return storageLocations;
}
/**
* Cloud Storage bucket storage location of the image (regional or multi-regional).
* @param storageLocations storageLocations or {@code null} for none
*/
public Image setStorageLocations(java.util.List<java.lang.String> storageLocations) {
this.storageLocations = storageLocations;
return this;
}
@Override
public Image set(String fieldName, Object value) {
return (Image) super.set(fieldName, value);
}
@Override
public Image clone() {
return (Image) super.clone();
}
/**
* The parameters of the raw disk image.
*/
public static final class RawDisk extends com.google.api.client.json.GenericJson {
/**
* The format used to encode and transmit the block device, which should be TAR. This is just a
* container and transmission format and not a runtime format. Provided by the client when the
* disk image is created.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String containerType;
/**
* [Deprecated] This field is deprecated. An optional SHA1 checksum of the disk image before
* unpackaging provided by the client when the disk image is created.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sha1Checksum;
/**
* The full Google Cloud Storage URL where the disk image is stored. You must provide either this
* property or the sourceDisk property but not both.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String source;
/**
* The format used to encode and transmit the block device, which should be TAR. This is just a
* container and transmission format and not a runtime format. Provided by the client when the
* disk image is created.
* @return value or {@code null} for none
*/
public java.lang.String getContainerType() {
return containerType;
}
/**
* The format used to encode and transmit the block device, which should be TAR. This is just a
* container and transmission format and not a runtime format. Provided by the client when the
* disk image is created.
* @param containerType containerType or {@code null} for none
*/
public RawDisk setContainerType(java.lang.String containerType) {
this.containerType = containerType;
return this;
}
/**
* [Deprecated] This field is deprecated. An optional SHA1 checksum of the disk image before
* unpackaging provided by the client when the disk image is created.
* @return value or {@code null} for none
*/
public java.lang.String getSha1Checksum() {
return sha1Checksum;
}
/**
* [Deprecated] This field is deprecated. An optional SHA1 checksum of the disk image before
* unpackaging provided by the client when the disk image is created.
* @param sha1Checksum sha1Checksum or {@code null} for none
*/
public RawDisk setSha1Checksum(java.lang.String sha1Checksum) {
this.sha1Checksum = sha1Checksum;
return this;
}
/**
* The full Google Cloud Storage URL where the disk image is stored. You must provide either this
* property or the sourceDisk property but not both.
* @return value or {@code null} for none
*/
public java.lang.String getSource() {
return source;
}
/**
* The full Google Cloud Storage URL where the disk image is stored. You must provide either this
* property or the sourceDisk property but not both.
* @param source source or {@code null} for none
*/
public RawDisk setSource(java.lang.String source) {
this.source = source;
return this;
}
@Override
public RawDisk set(String fieldName, Object value) {
return (RawDisk) super.set(fieldName, value);
}
@Override
public RawDisk clone() {
return (RawDisk) super.clone();
}
}
}
|
googleapis/google-api-java-client-services | 36,654 | clients/google-api-services-compute/v1/1.29.2/com/google/api/services/compute/model/Image.java | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.compute.model;
/**
* Represents an Image resource.
*
* You can use images to create boot disks for your VM instances. For more information, read Images.
* (== resource_for beta.images ==) (== resource_for v1.images ==)
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class Image extends com.google.api.client.json.GenericJson {
/**
* Size of the image tar.gz archive stored in Google Cloud Storage (in bytes).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long archiveSizeBytes;
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String creationTimestamp;
/**
* The deprecation status associated with this image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DeprecationStatus deprecated;
/**
* An optional description of this resource. Provide this property when you create the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* Size of the image when restored onto a persistent disk (in GB).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long diskSizeGb;
/**
* The name of the image family to which this image belongs. You can create disks by specifying an
* image family instead of a specific image name. The image family always returns its latest image
* that is not deprecated. The name of the image family must comply with RFC1035.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String family;
/**
* A list of features to enable on the guest operating system. Applicable only for bootable
* images. Read Enabling guest operating system features to see a list of available options.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GuestOsFeature> guestOsFeatures;
static {
// hack to force ProGuard to consider GuestOsFeature used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(GuestOsFeature.class);
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.math.BigInteger id;
/**
* Encrypts the image using a customer-supplied encryption key.
*
* After you encrypt an image with a customer-supplied key, you must provide the same key if you
* use the image later (e.g. to create a disk from the image).
*
* Customer-supplied encryption keys do not protect access to metadata of the disk.
*
* If you do not provide an encryption key when creating the image, then the disk will be
* encrypted using an automatically generated key and you do not need to provide a key to use the
* image later.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey imageEncryptionKey;
/**
* [Output Only] Type of the resource. Always compute#image for images.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String labelFingerprint;
/**
* Labels to apply to this image. These can be later modified by the setLabels method.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, java.lang.String> labels;
/**
* Integer license codes indicating which licenses are attached to this image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.util.List<java.lang.Long> licenseCodes;
/**
* Any applicable license URI.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> licenses;
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* The parameters of the raw disk image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private RawDisk rawDisk;
/**
* [Output Only] Server-defined URL for the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String selfLink;
/**
* URL of the source disk used to create this image. This can be a full or valid partial URL. You
* must provide either this property or the rawDisk.source property but not both to create an
* image. For example, the following are valid values: -
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/disks/disk -
* projects/project/zones/zone/disks/disk - zones/zone/disks/disk
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceDisk;
/**
* The customer-supplied encryption key of the source disk. Required if the source disk is
* protected by a customer-supplied encryption key.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey sourceDiskEncryptionKey;
/**
* [Output Only] The ID value of the disk used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given disk
* name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceDiskId;
/**
* URL of the source image used to create this image. This can be a full or valid partial URL. You
* must provide exactly one of: - this property, or - the rawDisk.source property, or - the
* sourceDisk property in order to create an image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceImage;
/**
* The customer-supplied encryption key of the source image. Required if the source image is
* protected by a customer-supplied encryption key.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey sourceImageEncryptionKey;
/**
* [Output Only] The ID value of the image used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given image
* name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceImageId;
/**
* URL of the source snapshot used to create this image. This can be a full or valid partial URL.
* You must provide exactly one of: - this property, or - the sourceImage property, or - the
* rawDisk.source property, or - the sourceDisk property in order to create an image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceSnapshot;
/**
* The customer-supplied encryption key of the source snapshot. Required if the source snapshot is
* protected by a customer-supplied encryption key.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey sourceSnapshotEncryptionKey;
/**
* [Output Only] The ID value of the snapshot used to create this image. This value may be used to
* determine whether the snapshot was taken from the current or a previous instance of a given
* snapshot name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceSnapshotId;
/**
* The type of the image used to create this disk. The default and only value is RAW
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceType;
/**
* [Output Only] The status of the image. An image can be used to create other resources, such as
* instances, only after the image has been successfully created and the status is set to READY.
* Possible values are FAILED, PENDING, or READY.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String status;
/**
* Cloud Storage bucket storage location of the image (regional or multi-regional).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> storageLocations;
/**
* Size of the image tar.gz archive stored in Google Cloud Storage (in bytes).
* @return value or {@code null} for none
*/
public java.lang.Long getArchiveSizeBytes() {
return archiveSizeBytes;
}
/**
* Size of the image tar.gz archive stored in Google Cloud Storage (in bytes).
* @param archiveSizeBytes archiveSizeBytes or {@code null} for none
*/
public Image setArchiveSizeBytes(java.lang.Long archiveSizeBytes) {
this.archiveSizeBytes = archiveSizeBytes;
return this;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @return value or {@code null} for none
*/
public java.lang.String getCreationTimestamp() {
return creationTimestamp;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @param creationTimestamp creationTimestamp or {@code null} for none
*/
public Image setCreationTimestamp(java.lang.String creationTimestamp) {
this.creationTimestamp = creationTimestamp;
return this;
}
/**
* The deprecation status associated with this image.
* @return value or {@code null} for none
*/
public DeprecationStatus getDeprecated() {
return deprecated;
}
/**
* The deprecation status associated with this image.
* @param deprecated deprecated or {@code null} for none
*/
public Image setDeprecated(DeprecationStatus deprecated) {
this.deprecated = deprecated;
return this;
}
/**
* An optional description of this resource. Provide this property when you create the resource.
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* An optional description of this resource. Provide this property when you create the resource.
* @param description description or {@code null} for none
*/
public Image setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* Size of the image when restored onto a persistent disk (in GB).
* @return value or {@code null} for none
*/
public java.lang.Long getDiskSizeGb() {
return diskSizeGb;
}
/**
* Size of the image when restored onto a persistent disk (in GB).
* @param diskSizeGb diskSizeGb or {@code null} for none
*/
public Image setDiskSizeGb(java.lang.Long diskSizeGb) {
this.diskSizeGb = diskSizeGb;
return this;
}
/**
* The name of the image family to which this image belongs. You can create disks by specifying an
* image family instead of a specific image name. The image family always returns its latest image
* that is not deprecated. The name of the image family must comply with RFC1035.
* @return value or {@code null} for none
*/
public java.lang.String getFamily() {
return family;
}
/**
* The name of the image family to which this image belongs. You can create disks by specifying an
* image family instead of a specific image name. The image family always returns its latest image
* that is not deprecated. The name of the image family must comply with RFC1035.
* @param family family or {@code null} for none
*/
public Image setFamily(java.lang.String family) {
this.family = family;
return this;
}
/**
* A list of features to enable on the guest operating system. Applicable only for bootable
* images. Read Enabling guest operating system features to see a list of available options.
* @return value or {@code null} for none
*/
public java.util.List<GuestOsFeature> getGuestOsFeatures() {
return guestOsFeatures;
}
/**
* A list of features to enable on the guest operating system. Applicable only for bootable
* images. Read Enabling guest operating system features to see a list of available options.
* @param guestOsFeatures guestOsFeatures or {@code null} for none
*/
public Image setGuestOsFeatures(java.util.List<GuestOsFeature> guestOsFeatures) {
this.guestOsFeatures = guestOsFeatures;
return this;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @return value or {@code null} for none
*/
public java.math.BigInteger getId() {
return id;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @param id id or {@code null} for none
*/
public Image setId(java.math.BigInteger id) {
this.id = id;
return this;
}
/**
* Encrypts the image using a customer-supplied encryption key.
*
* After you encrypt an image with a customer-supplied key, you must provide the same key if you
* use the image later (e.g. to create a disk from the image).
*
* Customer-supplied encryption keys do not protect access to metadata of the disk.
*
* If you do not provide an encryption key when creating the image, then the disk will be
* encrypted using an automatically generated key and you do not need to provide a key to use the
* image later.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getImageEncryptionKey() {
return imageEncryptionKey;
}
/**
* Encrypts the image using a customer-supplied encryption key.
*
* After you encrypt an image with a customer-supplied key, you must provide the same key if you
* use the image later (e.g. to create a disk from the image).
*
* Customer-supplied encryption keys do not protect access to metadata of the disk.
*
* If you do not provide an encryption key when creating the image, then the disk will be
* encrypted using an automatically generated key and you do not need to provide a key to use the
* image later.
* @param imageEncryptionKey imageEncryptionKey or {@code null} for none
*/
public Image setImageEncryptionKey(CustomerEncryptionKey imageEncryptionKey) {
this.imageEncryptionKey = imageEncryptionKey;
return this;
}
/**
* [Output Only] Type of the resource. Always compute#image for images.
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* [Output Only] Type of the resource. Always compute#image for images.
* @param kind kind or {@code null} for none
*/
public Image setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #decodeLabelFingerprint()
* @return value or {@code null} for none
*/
public java.lang.String getLabelFingerprint() {
return labelFingerprint;
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #getLabelFingerprint()
* @return Base64 decoded value or {@code null} for none
*
* @since 1.14
*/
public byte[] decodeLabelFingerprint() {
return com.google.api.client.util.Base64.decodeBase64(labelFingerprint);
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #encodeLabelFingerprint()
* @param labelFingerprint labelFingerprint or {@code null} for none
*/
public Image setLabelFingerprint(java.lang.String labelFingerprint) {
this.labelFingerprint = labelFingerprint;
return this;
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #setLabelFingerprint()
*
* <p>
* The value is encoded Base64 or {@code null} for none.
* </p>
*
* @since 1.14
*/
public Image encodeLabelFingerprint(byte[] labelFingerprint) {
this.labelFingerprint = com.google.api.client.util.Base64.encodeBase64URLSafeString(labelFingerprint);
return this;
}
/**
* Labels to apply to this image. These can be later modified by the setLabels method.
* @return value or {@code null} for none
*/
public java.util.Map<String, java.lang.String> getLabels() {
return labels;
}
/**
* Labels to apply to this image. These can be later modified by the setLabels method.
* @param labels labels or {@code null} for none
*/
public Image setLabels(java.util.Map<String, java.lang.String> labels) {
this.labels = labels;
return this;
}
/**
* Integer license codes indicating which licenses are attached to this image.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.Long> getLicenseCodes() {
return licenseCodes;
}
/**
* Integer license codes indicating which licenses are attached to this image.
* @param licenseCodes licenseCodes or {@code null} for none
*/
public Image setLicenseCodes(java.util.List<java.lang.Long> licenseCodes) {
this.licenseCodes = licenseCodes;
return this;
}
/**
* Any applicable license URI.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getLicenses() {
return licenses;
}
/**
* Any applicable license URI.
* @param licenses licenses or {@code null} for none
*/
public Image setLicenses(java.util.List<java.lang.String> licenses) {
this.licenses = licenses;
return this;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* @param name name or {@code null} for none
*/
public Image setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* The parameters of the raw disk image.
* @return value or {@code null} for none
*/
public RawDisk getRawDisk() {
return rawDisk;
}
/**
* The parameters of the raw disk image.
* @param rawDisk rawDisk or {@code null} for none
*/
public Image setRawDisk(RawDisk rawDisk) {
this.rawDisk = rawDisk;
return this;
}
/**
* [Output Only] Server-defined URL for the resource.
* @return value or {@code null} for none
*/
public java.lang.String getSelfLink() {
return selfLink;
}
/**
* [Output Only] Server-defined URL for the resource.
* @param selfLink selfLink or {@code null} for none
*/
public Image setSelfLink(java.lang.String selfLink) {
this.selfLink = selfLink;
return this;
}
/**
* URL of the source disk used to create this image. This can be a full or valid partial URL. You
* must provide either this property or the rawDisk.source property but not both to create an
* image. For example, the following are valid values: -
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/disks/disk -
* projects/project/zones/zone/disks/disk - zones/zone/disks/disk
* @return value or {@code null} for none
*/
public java.lang.String getSourceDisk() {
return sourceDisk;
}
/**
* URL of the source disk used to create this image. This can be a full or valid partial URL. You
* must provide either this property or the rawDisk.source property but not both to create an
* image. For example, the following are valid values: -
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/disks/disk -
* projects/project/zones/zone/disks/disk - zones/zone/disks/disk
* @param sourceDisk sourceDisk or {@code null} for none
*/
public Image setSourceDisk(java.lang.String sourceDisk) {
this.sourceDisk = sourceDisk;
return this;
}
/**
* The customer-supplied encryption key of the source disk. Required if the source disk is
* protected by a customer-supplied encryption key.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getSourceDiskEncryptionKey() {
return sourceDiskEncryptionKey;
}
/**
* The customer-supplied encryption key of the source disk. Required if the source disk is
* protected by a customer-supplied encryption key.
* @param sourceDiskEncryptionKey sourceDiskEncryptionKey or {@code null} for none
*/
public Image setSourceDiskEncryptionKey(CustomerEncryptionKey sourceDiskEncryptionKey) {
this.sourceDiskEncryptionKey = sourceDiskEncryptionKey;
return this;
}
/**
* [Output Only] The ID value of the disk used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given disk
* name.
* @return value or {@code null} for none
*/
public java.lang.String getSourceDiskId() {
return sourceDiskId;
}
/**
* [Output Only] The ID value of the disk used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given disk
* name.
* @param sourceDiskId sourceDiskId or {@code null} for none
*/
public Image setSourceDiskId(java.lang.String sourceDiskId) {
this.sourceDiskId = sourceDiskId;
return this;
}
/**
* URL of the source image used to create this image. This can be a full or valid partial URL. You
* must provide exactly one of: - this property, or - the rawDisk.source property, or - the
* sourceDisk property in order to create an image.
* @return value or {@code null} for none
*/
public java.lang.String getSourceImage() {
return sourceImage;
}
/**
* URL of the source image used to create this image. This can be a full or valid partial URL. You
* must provide exactly one of: - this property, or - the rawDisk.source property, or - the
* sourceDisk property in order to create an image.
* @param sourceImage sourceImage or {@code null} for none
*/
public Image setSourceImage(java.lang.String sourceImage) {
this.sourceImage = sourceImage;
return this;
}
/**
* The customer-supplied encryption key of the source image. Required if the source image is
* protected by a customer-supplied encryption key.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getSourceImageEncryptionKey() {
return sourceImageEncryptionKey;
}
/**
* The customer-supplied encryption key of the source image. Required if the source image is
* protected by a customer-supplied encryption key.
* @param sourceImageEncryptionKey sourceImageEncryptionKey or {@code null} for none
*/
public Image setSourceImageEncryptionKey(CustomerEncryptionKey sourceImageEncryptionKey) {
this.sourceImageEncryptionKey = sourceImageEncryptionKey;
return this;
}
/**
* [Output Only] The ID value of the image used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given image
* name.
* @return value or {@code null} for none
*/
public java.lang.String getSourceImageId() {
return sourceImageId;
}
/**
* [Output Only] The ID value of the image used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given image
* name.
* @param sourceImageId sourceImageId or {@code null} for none
*/
public Image setSourceImageId(java.lang.String sourceImageId) {
this.sourceImageId = sourceImageId;
return this;
}
/**
* URL of the source snapshot used to create this image. This can be a full or valid partial URL.
* You must provide exactly one of: - this property, or - the sourceImage property, or - the
* rawDisk.source property, or - the sourceDisk property in order to create an image.
* @return value or {@code null} for none
*/
public java.lang.String getSourceSnapshot() {
return sourceSnapshot;
}
/**
* URL of the source snapshot used to create this image. This can be a full or valid partial URL.
* You must provide exactly one of: - this property, or - the sourceImage property, or - the
* rawDisk.source property, or - the sourceDisk property in order to create an image.
* @param sourceSnapshot sourceSnapshot or {@code null} for none
*/
public Image setSourceSnapshot(java.lang.String sourceSnapshot) {
this.sourceSnapshot = sourceSnapshot;
return this;
}
/**
* The customer-supplied encryption key of the source snapshot. Required if the source snapshot is
* protected by a customer-supplied encryption key.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getSourceSnapshotEncryptionKey() {
return sourceSnapshotEncryptionKey;
}
/**
* The customer-supplied encryption key of the source snapshot. Required if the source snapshot is
* protected by a customer-supplied encryption key.
* @param sourceSnapshotEncryptionKey sourceSnapshotEncryptionKey or {@code null} for none
*/
public Image setSourceSnapshotEncryptionKey(CustomerEncryptionKey sourceSnapshotEncryptionKey) {
this.sourceSnapshotEncryptionKey = sourceSnapshotEncryptionKey;
return this;
}
/**
* [Output Only] The ID value of the snapshot used to create this image. This value may be used to
* determine whether the snapshot was taken from the current or a previous instance of a given
* snapshot name.
* @return value or {@code null} for none
*/
public java.lang.String getSourceSnapshotId() {
return sourceSnapshotId;
}
/**
* [Output Only] The ID value of the snapshot used to create this image. This value may be used to
* determine whether the snapshot was taken from the current or a previous instance of a given
* snapshot name.
* @param sourceSnapshotId sourceSnapshotId or {@code null} for none
*/
public Image setSourceSnapshotId(java.lang.String sourceSnapshotId) {
this.sourceSnapshotId = sourceSnapshotId;
return this;
}
/**
* The type of the image used to create this disk. The default and only value is RAW
* @return value or {@code null} for none
*/
public java.lang.String getSourceType() {
return sourceType;
}
/**
* The type of the image used to create this disk. The default and only value is RAW
* @param sourceType sourceType or {@code null} for none
*/
public Image setSourceType(java.lang.String sourceType) {
this.sourceType = sourceType;
return this;
}
/**
* [Output Only] The status of the image. An image can be used to create other resources, such as
* instances, only after the image has been successfully created and the status is set to READY.
* Possible values are FAILED, PENDING, or READY.
* @return value or {@code null} for none
*/
public java.lang.String getStatus() {
return status;
}
/**
* [Output Only] The status of the image. An image can be used to create other resources, such as
* instances, only after the image has been successfully created and the status is set to READY.
* Possible values are FAILED, PENDING, or READY.
* @param status status or {@code null} for none
*/
public Image setStatus(java.lang.String status) {
this.status = status;
return this;
}
/**
* Cloud Storage bucket storage location of the image (regional or multi-regional).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getStorageLocations() {
return storageLocations;
}
/**
* Cloud Storage bucket storage location of the image (regional or multi-regional).
* @param storageLocations storageLocations or {@code null} for none
*/
public Image setStorageLocations(java.util.List<java.lang.String> storageLocations) {
this.storageLocations = storageLocations;
return this;
}
@Override
public Image set(String fieldName, Object value) {
return (Image) super.set(fieldName, value);
}
@Override
public Image clone() {
return (Image) super.clone();
}
/**
* The parameters of the raw disk image.
*/
public static final class RawDisk extends com.google.api.client.json.GenericJson {
/**
* The format used to encode and transmit the block device, which should be TAR. This is just a
* container and transmission format and not a runtime format. Provided by the client when the
* disk image is created.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String containerType;
/**
* [Deprecated] This field is deprecated. An optional SHA1 checksum of the disk image before
* unpackaging provided by the client when the disk image is created.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sha1Checksum;
/**
* The full Google Cloud Storage URL where the disk image is stored. You must provide either this
* property or the sourceDisk property but not both.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String source;
/**
* The format used to encode and transmit the block device, which should be TAR. This is just a
* container and transmission format and not a runtime format. Provided by the client when the
* disk image is created.
* @return value or {@code null} for none
*/
public java.lang.String getContainerType() {
return containerType;
}
/**
* The format used to encode and transmit the block device, which should be TAR. This is just a
* container and transmission format and not a runtime format. Provided by the client when the
* disk image is created.
* @param containerType containerType or {@code null} for none
*/
public RawDisk setContainerType(java.lang.String containerType) {
this.containerType = containerType;
return this;
}
/**
* [Deprecated] This field is deprecated. An optional SHA1 checksum of the disk image before
* unpackaging provided by the client when the disk image is created.
* @return value or {@code null} for none
*/
public java.lang.String getSha1Checksum() {
return sha1Checksum;
}
/**
* [Deprecated] This field is deprecated. An optional SHA1 checksum of the disk image before
* unpackaging provided by the client when the disk image is created.
* @param sha1Checksum sha1Checksum or {@code null} for none
*/
public RawDisk setSha1Checksum(java.lang.String sha1Checksum) {
this.sha1Checksum = sha1Checksum;
return this;
}
/**
* The full Google Cloud Storage URL where the disk image is stored. You must provide either this
* property or the sourceDisk property but not both.
* @return value or {@code null} for none
*/
public java.lang.String getSource() {
return source;
}
/**
* The full Google Cloud Storage URL where the disk image is stored. You must provide either this
* property or the sourceDisk property but not both.
* @param source source or {@code null} for none
*/
public RawDisk setSource(java.lang.String source) {
this.source = source;
return this;
}
@Override
public RawDisk set(String fieldName, Object value) {
return (RawDisk) super.set(fieldName, value);
}
@Override
public RawDisk clone() {
return (RawDisk) super.clone();
}
}
}
|
googleapis/google-cloud-java | 36,453 | java-datacatalog/proto-google-cloud-datacatalog-v1/src/main/java/com/google/cloud/datacatalog/v1/CreateEntryRequest.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/datacatalog.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.datacatalog.v1;
/**
*
*
* <pre>
* Request message for
* [CreateEntry][google.cloud.datacatalog.v1.DataCatalog.CreateEntry].
* </pre>
*
* Protobuf type {@code google.cloud.datacatalog.v1.CreateEntryRequest}
*/
public final class CreateEntryRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.datacatalog.v1.CreateEntryRequest)
CreateEntryRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateEntryRequest.newBuilder() to construct.
private CreateEntryRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateEntryRequest() {
parent_ = "";
entryId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateEntryRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datacatalog.v1.Datacatalog
.internal_static_google_cloud_datacatalog_v1_CreateEntryRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datacatalog.v1.Datacatalog
.internal_static_google_cloud_datacatalog_v1_CreateEntryRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datacatalog.v1.CreateEntryRequest.class,
com.google.cloud.datacatalog.v1.CreateEntryRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The name of the entry group this entry belongs to.
*
* Note: The entry itself and its child resources might not be stored in
* the location specified in its name.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The name of the entry group this entry belongs to.
*
* Note: The entry itself and its child resources might not be stored in
* the location specified in its name.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ENTRY_ID_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object entryId_ = "";
/**
*
*
* <pre>
* Required. The ID of the entry to create.
*
* The ID must contain only letters (a-z, A-Z), numbers (0-9),
* and underscores (_).
* The maximum size is 64 bytes when encoded in UTF-8.
* </pre>
*
* <code>string entry_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The entryId.
*/
@java.lang.Override
public java.lang.String getEntryId() {
java.lang.Object ref = entryId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
entryId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The ID of the entry to create.
*
* The ID must contain only letters (a-z, A-Z), numbers (0-9),
* and underscores (_).
* The maximum size is 64 bytes when encoded in UTF-8.
* </pre>
*
* <code>string entry_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for entryId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getEntryIdBytes() {
java.lang.Object ref = entryId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
entryId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ENTRY_FIELD_NUMBER = 2;
private com.google.cloud.datacatalog.v1.Entry entry_;
/**
*
*
* <pre>
* Required. The entry to create.
* </pre>
*
* <code>.google.cloud.datacatalog.v1.Entry entry = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the entry field is set.
*/
@java.lang.Override
public boolean hasEntry() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The entry to create.
* </pre>
*
* <code>.google.cloud.datacatalog.v1.Entry entry = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The entry.
*/
@java.lang.Override
public com.google.cloud.datacatalog.v1.Entry getEntry() {
return entry_ == null ? com.google.cloud.datacatalog.v1.Entry.getDefaultInstance() : entry_;
}
/**
*
*
* <pre>
* Required. The entry to create.
* </pre>
*
* <code>.google.cloud.datacatalog.v1.Entry entry = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.datacatalog.v1.EntryOrBuilder getEntryOrBuilder() {
return entry_ == null ? com.google.cloud.datacatalog.v1.Entry.getDefaultInstance() : entry_;
}
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, getEntry());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(entryId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, entryId_);
}
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, getEntry());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(entryId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, entryId_);
}
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.CreateEntryRequest)) {
return super.equals(obj);
}
com.google.cloud.datacatalog.v1.CreateEntryRequest other =
(com.google.cloud.datacatalog.v1.CreateEntryRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (!getEntryId().equals(other.getEntryId())) return false;
if (hasEntry() != other.hasEntry()) return false;
if (hasEntry()) {
if (!getEntry().equals(other.getEntry())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + ENTRY_ID_FIELD_NUMBER;
hash = (53 * hash) + getEntryId().hashCode();
if (hasEntry()) {
hash = (37 * hash) + ENTRY_FIELD_NUMBER;
hash = (53 * hash) + getEntry().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.datacatalog.v1.CreateEntryRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1.CreateEntryRequest 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.CreateEntryRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1.CreateEntryRequest 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.CreateEntryRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1.CreateEntryRequest 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.CreateEntryRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.v1.CreateEntryRequest 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.CreateEntryRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.v1.CreateEntryRequest 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.CreateEntryRequest 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.CreateEntryRequest 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.CreateEntryRequest 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
* [CreateEntry][google.cloud.datacatalog.v1.DataCatalog.CreateEntry].
* </pre>
*
* Protobuf type {@code google.cloud.datacatalog.v1.CreateEntryRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.datacatalog.v1.CreateEntryRequest)
com.google.cloud.datacatalog.v1.CreateEntryRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datacatalog.v1.Datacatalog
.internal_static_google_cloud_datacatalog_v1_CreateEntryRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datacatalog.v1.Datacatalog
.internal_static_google_cloud_datacatalog_v1_CreateEntryRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datacatalog.v1.CreateEntryRequest.class,
com.google.cloud.datacatalog.v1.CreateEntryRequest.Builder.class);
}
// Construct using com.google.cloud.datacatalog.v1.CreateEntryRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getEntryFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
entryId_ = "";
entry_ = null;
if (entryBuilder_ != null) {
entryBuilder_.dispose();
entryBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.datacatalog.v1.Datacatalog
.internal_static_google_cloud_datacatalog_v1_CreateEntryRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1.CreateEntryRequest getDefaultInstanceForType() {
return com.google.cloud.datacatalog.v1.CreateEntryRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.datacatalog.v1.CreateEntryRequest build() {
com.google.cloud.datacatalog.v1.CreateEntryRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1.CreateEntryRequest buildPartial() {
com.google.cloud.datacatalog.v1.CreateEntryRequest result =
new com.google.cloud.datacatalog.v1.CreateEntryRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.datacatalog.v1.CreateEntryRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.entryId_ = entryId_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.entry_ = entryBuilder_ == null ? entry_ : entryBuilder_.build();
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.datacatalog.v1.CreateEntryRequest) {
return mergeFrom((com.google.cloud.datacatalog.v1.CreateEntryRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.datacatalog.v1.CreateEntryRequest other) {
if (other == com.google.cloud.datacatalog.v1.CreateEntryRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getEntryId().isEmpty()) {
entryId_ = other.entryId_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasEntry()) {
mergeEntry(other.getEntry());
}
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(getEntryFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000004;
break;
} // case 18
case 26:
{
entryId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The name of the entry group this entry belongs to.
*
* Note: The entry itself and its child resources might not be stored in
* the location specified in its name.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the entry group this entry belongs to.
*
* Note: The entry itself and its child resources might not be stored in
* the location specified in its name.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the entry group this entry belongs to.
*
* Note: The entry itself and its child resources might not be stored in
* the location specified in its name.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the entry group this entry belongs to.
*
* Note: The entry itself and its child resources might not be stored in
* the location specified in its name.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the entry group this entry belongs to.
*
* Note: The entry itself and its child resources might not be stored in
* the location specified in its name.
* </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 entryId_ = "";
/**
*
*
* <pre>
* Required. The ID of the entry to create.
*
* The ID must contain only letters (a-z, A-Z), numbers (0-9),
* and underscores (_).
* The maximum size is 64 bytes when encoded in UTF-8.
* </pre>
*
* <code>string entry_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The entryId.
*/
public java.lang.String getEntryId() {
java.lang.Object ref = entryId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
entryId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The ID of the entry to create.
*
* The ID must contain only letters (a-z, A-Z), numbers (0-9),
* and underscores (_).
* The maximum size is 64 bytes when encoded in UTF-8.
* </pre>
*
* <code>string entry_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for entryId.
*/
public com.google.protobuf.ByteString getEntryIdBytes() {
java.lang.Object ref = entryId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
entryId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The ID of the entry to create.
*
* The ID must contain only letters (a-z, A-Z), numbers (0-9),
* and underscores (_).
* The maximum size is 64 bytes when encoded in UTF-8.
* </pre>
*
* <code>string entry_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The entryId to set.
* @return This builder for chaining.
*/
public Builder setEntryId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
entryId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ID of the entry to create.
*
* The ID must contain only letters (a-z, A-Z), numbers (0-9),
* and underscores (_).
* The maximum size is 64 bytes when encoded in UTF-8.
* </pre>
*
* <code>string entry_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearEntryId() {
entryId_ = getDefaultInstance().getEntryId();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ID of the entry to create.
*
* The ID must contain only letters (a-z, A-Z), numbers (0-9),
* and underscores (_).
* The maximum size is 64 bytes when encoded in UTF-8.
* </pre>
*
* <code>string entry_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for entryId to set.
* @return This builder for chaining.
*/
public Builder setEntryIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
entryId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.cloud.datacatalog.v1.Entry entry_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.datacatalog.v1.Entry,
com.google.cloud.datacatalog.v1.Entry.Builder,
com.google.cloud.datacatalog.v1.EntryOrBuilder>
entryBuilder_;
/**
*
*
* <pre>
* Required. The entry to create.
* </pre>
*
* <code>.google.cloud.datacatalog.v1.Entry entry = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the entry field is set.
*/
public boolean hasEntry() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* Required. The entry to create.
* </pre>
*
* <code>.google.cloud.datacatalog.v1.Entry entry = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The entry.
*/
public com.google.cloud.datacatalog.v1.Entry getEntry() {
if (entryBuilder_ == null) {
return entry_ == null ? com.google.cloud.datacatalog.v1.Entry.getDefaultInstance() : entry_;
} else {
return entryBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The entry to create.
* </pre>
*
* <code>.google.cloud.datacatalog.v1.Entry entry = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setEntry(com.google.cloud.datacatalog.v1.Entry value) {
if (entryBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
entry_ = value;
} else {
entryBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The entry to create.
* </pre>
*
* <code>.google.cloud.datacatalog.v1.Entry entry = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setEntry(com.google.cloud.datacatalog.v1.Entry.Builder builderForValue) {
if (entryBuilder_ == null) {
entry_ = builderForValue.build();
} else {
entryBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The entry to create.
* </pre>
*
* <code>.google.cloud.datacatalog.v1.Entry entry = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeEntry(com.google.cloud.datacatalog.v1.Entry value) {
if (entryBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& entry_ != null
&& entry_ != com.google.cloud.datacatalog.v1.Entry.getDefaultInstance()) {
getEntryBuilder().mergeFrom(value);
} else {
entry_ = value;
}
} else {
entryBuilder_.mergeFrom(value);
}
if (entry_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The entry to create.
* </pre>
*
* <code>.google.cloud.datacatalog.v1.Entry entry = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearEntry() {
bitField0_ = (bitField0_ & ~0x00000004);
entry_ = null;
if (entryBuilder_ != null) {
entryBuilder_.dispose();
entryBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The entry to create.
* </pre>
*
* <code>.google.cloud.datacatalog.v1.Entry entry = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.datacatalog.v1.Entry.Builder getEntryBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getEntryFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The entry to create.
* </pre>
*
* <code>.google.cloud.datacatalog.v1.Entry entry = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.datacatalog.v1.EntryOrBuilder getEntryOrBuilder() {
if (entryBuilder_ != null) {
return entryBuilder_.getMessageOrBuilder();
} else {
return entry_ == null ? com.google.cloud.datacatalog.v1.Entry.getDefaultInstance() : entry_;
}
}
/**
*
*
* <pre>
* Required. The entry to create.
* </pre>
*
* <code>.google.cloud.datacatalog.v1.Entry entry = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.datacatalog.v1.Entry,
com.google.cloud.datacatalog.v1.Entry.Builder,
com.google.cloud.datacatalog.v1.EntryOrBuilder>
getEntryFieldBuilder() {
if (entryBuilder_ == null) {
entryBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.datacatalog.v1.Entry,
com.google.cloud.datacatalog.v1.Entry.Builder,
com.google.cloud.datacatalog.v1.EntryOrBuilder>(
getEntry(), getParentForChildren(), isClean());
entry_ = null;
}
return entryBuilder_;
}
@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.CreateEntryRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.datacatalog.v1.CreateEntryRequest)
private static final com.google.cloud.datacatalog.v1.CreateEntryRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.datacatalog.v1.CreateEntryRequest();
}
public static com.google.cloud.datacatalog.v1.CreateEntryRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateEntryRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateEntryRequest>() {
@java.lang.Override
public CreateEntryRequest 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<CreateEntryRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateEntryRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1.CreateEntryRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,546 | java-networkservices/proto-google-cloud-networkservices-v1/src/main/java/com/google/cloud/networkservices/v1/UpdateGatewayRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/networkservices/v1/gateway.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.networkservices.v1;
/**
*
*
* <pre>
* Request used by the UpdateGateway method.
* </pre>
*
* Protobuf type {@code google.cloud.networkservices.v1.UpdateGatewayRequest}
*/
public final class UpdateGatewayRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.networkservices.v1.UpdateGatewayRequest)
UpdateGatewayRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateGatewayRequest.newBuilder() to construct.
private UpdateGatewayRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateGatewayRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateGatewayRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.networkservices.v1.GatewayProto
.internal_static_google_cloud_networkservices_v1_UpdateGatewayRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.networkservices.v1.GatewayProto
.internal_static_google_cloud_networkservices_v1_UpdateGatewayRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.networkservices.v1.UpdateGatewayRequest.class,
com.google.cloud.networkservices.v1.UpdateGatewayRequest.Builder.class);
}
private int bitField0_;
public static final int UPDATE_MASK_FIELD_NUMBER = 1;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Optional. Field mask is used to specify the fields to be overwritten in the
* Gateway resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Optional. Field mask is used to specify the fields to be overwritten in the
* Gateway resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Optional. Field mask is used to specify the fields to be overwritten in the
* Gateway resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
public static final int GATEWAY_FIELD_NUMBER = 2;
private com.google.cloud.networkservices.v1.Gateway gateway_;
/**
*
*
* <pre>
* Required. Updated Gateway resource.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.Gateway gateway = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the gateway field is set.
*/
@java.lang.Override
public boolean hasGateway() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. Updated Gateway resource.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.Gateway gateway = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The gateway.
*/
@java.lang.Override
public com.google.cloud.networkservices.v1.Gateway getGateway() {
return gateway_ == null
? com.google.cloud.networkservices.v1.Gateway.getDefaultInstance()
: gateway_;
}
/**
*
*
* <pre>
* Required. Updated Gateway resource.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.Gateway gateway = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.networkservices.v1.GatewayOrBuilder getGatewayOrBuilder() {
return gateway_ == null
? com.google.cloud.networkservices.v1.Gateway.getDefaultInstance()
: gateway_;
}
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, getGateway());
}
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, getGateway());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.networkservices.v1.UpdateGatewayRequest)) {
return super.equals(obj);
}
com.google.cloud.networkservices.v1.UpdateGatewayRequest other =
(com.google.cloud.networkservices.v1.UpdateGatewayRequest) obj;
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask().equals(other.getUpdateMask())) return false;
}
if (hasGateway() != other.hasGateway()) return false;
if (hasGateway()) {
if (!getGateway().equals(other.getGateway())) 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 (hasGateway()) {
hash = (37 * hash) + GATEWAY_FIELD_NUMBER;
hash = (53 * hash) + getGateway().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.networkservices.v1.UpdateGatewayRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.networkservices.v1.UpdateGatewayRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.networkservices.v1.UpdateGatewayRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.networkservices.v1.UpdateGatewayRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.networkservices.v1.UpdateGatewayRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.networkservices.v1.UpdateGatewayRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.networkservices.v1.UpdateGatewayRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.networkservices.v1.UpdateGatewayRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.networkservices.v1.UpdateGatewayRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.networkservices.v1.UpdateGatewayRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.networkservices.v1.UpdateGatewayRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.networkservices.v1.UpdateGatewayRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.networkservices.v1.UpdateGatewayRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request used by the UpdateGateway method.
* </pre>
*
* Protobuf type {@code google.cloud.networkservices.v1.UpdateGatewayRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.networkservices.v1.UpdateGatewayRequest)
com.google.cloud.networkservices.v1.UpdateGatewayRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.networkservices.v1.GatewayProto
.internal_static_google_cloud_networkservices_v1_UpdateGatewayRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.networkservices.v1.GatewayProto
.internal_static_google_cloud_networkservices_v1_UpdateGatewayRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.networkservices.v1.UpdateGatewayRequest.class,
com.google.cloud.networkservices.v1.UpdateGatewayRequest.Builder.class);
}
// Construct using com.google.cloud.networkservices.v1.UpdateGatewayRequest.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();
getGatewayFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
gateway_ = null;
if (gatewayBuilder_ != null) {
gatewayBuilder_.dispose();
gatewayBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.networkservices.v1.GatewayProto
.internal_static_google_cloud_networkservices_v1_UpdateGatewayRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.networkservices.v1.UpdateGatewayRequest getDefaultInstanceForType() {
return com.google.cloud.networkservices.v1.UpdateGatewayRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.networkservices.v1.UpdateGatewayRequest build() {
com.google.cloud.networkservices.v1.UpdateGatewayRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.networkservices.v1.UpdateGatewayRequest buildPartial() {
com.google.cloud.networkservices.v1.UpdateGatewayRequest result =
new com.google.cloud.networkservices.v1.UpdateGatewayRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.networkservices.v1.UpdateGatewayRequest 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.gateway_ = gatewayBuilder_ == null ? gateway_ : gatewayBuilder_.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.networkservices.v1.UpdateGatewayRequest) {
return mergeFrom((com.google.cloud.networkservices.v1.UpdateGatewayRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.networkservices.v1.UpdateGatewayRequest other) {
if (other == com.google.cloud.networkservices.v1.UpdateGatewayRequest.getDefaultInstance())
return this;
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
if (other.hasGateway()) {
mergeGateway(other.getGateway());
}
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(getGatewayFieldBuilder().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>
* Optional. Field mask is used to specify the fields to be overwritten in the
* Gateway resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Optional. Field mask is used to specify the fields to be overwritten in the
* Gateway resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Optional. Field mask is used to specify the fields to be overwritten in the
* Gateway resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
} else {
updateMaskBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Field mask is used to specify the fields to be overwritten in the
* Gateway resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Field mask is used to specify the fields to be overwritten in the
* Gateway resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = OPTIONAL];
* </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>
* Optional. Field mask is used to specify the fields to be overwritten in the
* Gateway resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000001);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Field mask is used to specify the fields to be overwritten in the
* Gateway resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Optional. Field mask is used to specify the fields to be overwritten in the
* Gateway resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Optional. Field mask is used to specify the fields to be overwritten in the
* Gateway resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then all fields will be overwritten.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
private com.google.cloud.networkservices.v1.Gateway gateway_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.networkservices.v1.Gateway,
com.google.cloud.networkservices.v1.Gateway.Builder,
com.google.cloud.networkservices.v1.GatewayOrBuilder>
gatewayBuilder_;
/**
*
*
* <pre>
* Required. Updated Gateway resource.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.Gateway gateway = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the gateway field is set.
*/
public boolean hasGateway() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. Updated Gateway resource.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.Gateway gateway = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The gateway.
*/
public com.google.cloud.networkservices.v1.Gateway getGateway() {
if (gatewayBuilder_ == null) {
return gateway_ == null
? com.google.cloud.networkservices.v1.Gateway.getDefaultInstance()
: gateway_;
} else {
return gatewayBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Updated Gateway resource.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.Gateway gateway = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setGateway(com.google.cloud.networkservices.v1.Gateway value) {
if (gatewayBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
gateway_ = value;
} else {
gatewayBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Updated Gateway resource.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.Gateway gateway = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setGateway(com.google.cloud.networkservices.v1.Gateway.Builder builderForValue) {
if (gatewayBuilder_ == null) {
gateway_ = builderForValue.build();
} else {
gatewayBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Updated Gateway resource.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.Gateway gateway = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeGateway(com.google.cloud.networkservices.v1.Gateway value) {
if (gatewayBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& gateway_ != null
&& gateway_ != com.google.cloud.networkservices.v1.Gateway.getDefaultInstance()) {
getGatewayBuilder().mergeFrom(value);
} else {
gateway_ = value;
}
} else {
gatewayBuilder_.mergeFrom(value);
}
if (gateway_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Updated Gateway resource.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.Gateway gateway = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearGateway() {
bitField0_ = (bitField0_ & ~0x00000002);
gateway_ = null;
if (gatewayBuilder_ != null) {
gatewayBuilder_.dispose();
gatewayBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Updated Gateway resource.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.Gateway gateway = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.networkservices.v1.Gateway.Builder getGatewayBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getGatewayFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Updated Gateway resource.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.Gateway gateway = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.networkservices.v1.GatewayOrBuilder getGatewayOrBuilder() {
if (gatewayBuilder_ != null) {
return gatewayBuilder_.getMessageOrBuilder();
} else {
return gateway_ == null
? com.google.cloud.networkservices.v1.Gateway.getDefaultInstance()
: gateway_;
}
}
/**
*
*
* <pre>
* Required. Updated Gateway resource.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.Gateway gateway = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.networkservices.v1.Gateway,
com.google.cloud.networkservices.v1.Gateway.Builder,
com.google.cloud.networkservices.v1.GatewayOrBuilder>
getGatewayFieldBuilder() {
if (gatewayBuilder_ == null) {
gatewayBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.networkservices.v1.Gateway,
com.google.cloud.networkservices.v1.Gateway.Builder,
com.google.cloud.networkservices.v1.GatewayOrBuilder>(
getGateway(), getParentForChildren(), isClean());
gateway_ = null;
}
return gatewayBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.networkservices.v1.UpdateGatewayRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.networkservices.v1.UpdateGatewayRequest)
private static final com.google.cloud.networkservices.v1.UpdateGatewayRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.networkservices.v1.UpdateGatewayRequest();
}
public static com.google.cloud.networkservices.v1.UpdateGatewayRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateGatewayRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateGatewayRequest>() {
@java.lang.Override
public UpdateGatewayRequest 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<UpdateGatewayRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateGatewayRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.networkservices.v1.UpdateGatewayRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-api-java-client-services | 36,654 | clients/google-api-services-compute/beta/1.28.0/com/google/api/services/compute/model/Image.java | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.compute.model;
/**
* Represents an Image resource.
*
* You can use images to create boot disks for your VM instances. For more information, read Images.
* (== resource_for beta.images ==) (== resource_for v1.images ==)
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class Image extends com.google.api.client.json.GenericJson {
/**
* Size of the image tar.gz archive stored in Google Cloud Storage (in bytes).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long archiveSizeBytes;
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String creationTimestamp;
/**
* The deprecation status associated with this image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DeprecationStatus deprecated;
/**
* An optional description of this resource. Provide this property when you create the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* Size of the image when restored onto a persistent disk (in GB).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long diskSizeGb;
/**
* The name of the image family to which this image belongs. You can create disks by specifying an
* image family instead of a specific image name. The image family always returns its latest image
* that is not deprecated. The name of the image family must comply with RFC1035.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String family;
/**
* A list of features to enable on the guest operating system. Applicable only for bootable
* images. Read Enabling guest operating system features to see a list of available options.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GuestOsFeature> guestOsFeatures;
static {
// hack to force ProGuard to consider GuestOsFeature used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(GuestOsFeature.class);
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.math.BigInteger id;
/**
* Encrypts the image using a customer-supplied encryption key.
*
* After you encrypt an image with a customer-supplied key, you must provide the same key if you
* use the image later (e.g. to create a disk from the image).
*
* Customer-supplied encryption keys do not protect access to metadata of the disk.
*
* If you do not provide an encryption key when creating the image, then the disk will be
* encrypted using an automatically generated key and you do not need to provide a key to use the
* image later.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey imageEncryptionKey;
/**
* [Output Only] Type of the resource. Always compute#image for images.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String labelFingerprint;
/**
* Labels to apply to this image. These can be later modified by the setLabels method.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, java.lang.String> labels;
/**
* Integer license codes indicating which licenses are attached to this image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.util.List<java.lang.Long> licenseCodes;
/**
* Any applicable license URI.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> licenses;
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* The parameters of the raw disk image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private RawDisk rawDisk;
/**
* [Output Only] Server-defined URL for the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String selfLink;
/**
* URL of the source disk used to create this image. This can be a full or valid partial URL. You
* must provide either this property or the rawDisk.source property but not both to create an
* image. For example, the following are valid values: -
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/disks/disk -
* projects/project/zones/zone/disks/disk - zones/zone/disks/disk
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceDisk;
/**
* The customer-supplied encryption key of the source disk. Required if the source disk is
* protected by a customer-supplied encryption key.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey sourceDiskEncryptionKey;
/**
* [Output Only] The ID value of the disk used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given disk
* name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceDiskId;
/**
* URL of the source image used to create this image. This can be a full or valid partial URL. You
* must provide exactly one of: - this property, or - the rawDisk.source property, or - the
* sourceDisk property in order to create an image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceImage;
/**
* The customer-supplied encryption key of the source image. Required if the source image is
* protected by a customer-supplied encryption key.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey sourceImageEncryptionKey;
/**
* [Output Only] The ID value of the image used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given image
* name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceImageId;
/**
* URL of the source snapshot used to create this image. This can be a full or valid partial URL.
* You must provide exactly one of: - this property, or - the sourceImage property, or - the
* rawDisk.source property, or - the sourceDisk property in order to create an image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceSnapshot;
/**
* The customer-supplied encryption key of the source snapshot. Required if the source snapshot is
* protected by a customer-supplied encryption key.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey sourceSnapshotEncryptionKey;
/**
* [Output Only] The ID value of the snapshot used to create this image. This value may be used to
* determine whether the snapshot was taken from the current or a previous instance of a given
* snapshot name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceSnapshotId;
/**
* The type of the image used to create this disk. The default and only value is RAW
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceType;
/**
* [Output Only] The status of the image. An image can be used to create other resources, such as
* instances, only after the image has been successfully created and the status is set to READY.
* Possible values are FAILED, PENDING, or READY.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String status;
/**
* Cloud Storage bucket storage location of the image (regional or multi-regional).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> storageLocations;
/**
* Size of the image tar.gz archive stored in Google Cloud Storage (in bytes).
* @return value or {@code null} for none
*/
public java.lang.Long getArchiveSizeBytes() {
return archiveSizeBytes;
}
/**
* Size of the image tar.gz archive stored in Google Cloud Storage (in bytes).
* @param archiveSizeBytes archiveSizeBytes or {@code null} for none
*/
public Image setArchiveSizeBytes(java.lang.Long archiveSizeBytes) {
this.archiveSizeBytes = archiveSizeBytes;
return this;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @return value or {@code null} for none
*/
public java.lang.String getCreationTimestamp() {
return creationTimestamp;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @param creationTimestamp creationTimestamp or {@code null} for none
*/
public Image setCreationTimestamp(java.lang.String creationTimestamp) {
this.creationTimestamp = creationTimestamp;
return this;
}
/**
* The deprecation status associated with this image.
* @return value or {@code null} for none
*/
public DeprecationStatus getDeprecated() {
return deprecated;
}
/**
* The deprecation status associated with this image.
* @param deprecated deprecated or {@code null} for none
*/
public Image setDeprecated(DeprecationStatus deprecated) {
this.deprecated = deprecated;
return this;
}
/**
* An optional description of this resource. Provide this property when you create the resource.
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* An optional description of this resource. Provide this property when you create the resource.
* @param description description or {@code null} for none
*/
public Image setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* Size of the image when restored onto a persistent disk (in GB).
* @return value or {@code null} for none
*/
public java.lang.Long getDiskSizeGb() {
return diskSizeGb;
}
/**
* Size of the image when restored onto a persistent disk (in GB).
* @param diskSizeGb diskSizeGb or {@code null} for none
*/
public Image setDiskSizeGb(java.lang.Long diskSizeGb) {
this.diskSizeGb = diskSizeGb;
return this;
}
/**
* The name of the image family to which this image belongs. You can create disks by specifying an
* image family instead of a specific image name. The image family always returns its latest image
* that is not deprecated. The name of the image family must comply with RFC1035.
* @return value or {@code null} for none
*/
public java.lang.String getFamily() {
return family;
}
/**
* The name of the image family to which this image belongs. You can create disks by specifying an
* image family instead of a specific image name. The image family always returns its latest image
* that is not deprecated. The name of the image family must comply with RFC1035.
* @param family family or {@code null} for none
*/
public Image setFamily(java.lang.String family) {
this.family = family;
return this;
}
/**
* A list of features to enable on the guest operating system. Applicable only for bootable
* images. Read Enabling guest operating system features to see a list of available options.
* @return value or {@code null} for none
*/
public java.util.List<GuestOsFeature> getGuestOsFeatures() {
return guestOsFeatures;
}
/**
* A list of features to enable on the guest operating system. Applicable only for bootable
* images. Read Enabling guest operating system features to see a list of available options.
* @param guestOsFeatures guestOsFeatures or {@code null} for none
*/
public Image setGuestOsFeatures(java.util.List<GuestOsFeature> guestOsFeatures) {
this.guestOsFeatures = guestOsFeatures;
return this;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @return value or {@code null} for none
*/
public java.math.BigInteger getId() {
return id;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @param id id or {@code null} for none
*/
public Image setId(java.math.BigInteger id) {
this.id = id;
return this;
}
/**
* Encrypts the image using a customer-supplied encryption key.
*
* After you encrypt an image with a customer-supplied key, you must provide the same key if you
* use the image later (e.g. to create a disk from the image).
*
* Customer-supplied encryption keys do not protect access to metadata of the disk.
*
* If you do not provide an encryption key when creating the image, then the disk will be
* encrypted using an automatically generated key and you do not need to provide a key to use the
* image later.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getImageEncryptionKey() {
return imageEncryptionKey;
}
/**
* Encrypts the image using a customer-supplied encryption key.
*
* After you encrypt an image with a customer-supplied key, you must provide the same key if you
* use the image later (e.g. to create a disk from the image).
*
* Customer-supplied encryption keys do not protect access to metadata of the disk.
*
* If you do not provide an encryption key when creating the image, then the disk will be
* encrypted using an automatically generated key and you do not need to provide a key to use the
* image later.
* @param imageEncryptionKey imageEncryptionKey or {@code null} for none
*/
public Image setImageEncryptionKey(CustomerEncryptionKey imageEncryptionKey) {
this.imageEncryptionKey = imageEncryptionKey;
return this;
}
/**
* [Output Only] Type of the resource. Always compute#image for images.
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* [Output Only] Type of the resource. Always compute#image for images.
* @param kind kind or {@code null} for none
*/
public Image setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #decodeLabelFingerprint()
* @return value or {@code null} for none
*/
public java.lang.String getLabelFingerprint() {
return labelFingerprint;
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #getLabelFingerprint()
* @return Base64 decoded value or {@code null} for none
*
* @since 1.14
*/
public byte[] decodeLabelFingerprint() {
return com.google.api.client.util.Base64.decodeBase64(labelFingerprint);
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #encodeLabelFingerprint()
* @param labelFingerprint labelFingerprint or {@code null} for none
*/
public Image setLabelFingerprint(java.lang.String labelFingerprint) {
this.labelFingerprint = labelFingerprint;
return this;
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #setLabelFingerprint()
*
* <p>
* The value is encoded Base64 or {@code null} for none.
* </p>
*
* @since 1.14
*/
public Image encodeLabelFingerprint(byte[] labelFingerprint) {
this.labelFingerprint = com.google.api.client.util.Base64.encodeBase64URLSafeString(labelFingerprint);
return this;
}
/**
* Labels to apply to this image. These can be later modified by the setLabels method.
* @return value or {@code null} for none
*/
public java.util.Map<String, java.lang.String> getLabels() {
return labels;
}
/**
* Labels to apply to this image. These can be later modified by the setLabels method.
* @param labels labels or {@code null} for none
*/
public Image setLabels(java.util.Map<String, java.lang.String> labels) {
this.labels = labels;
return this;
}
/**
* Integer license codes indicating which licenses are attached to this image.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.Long> getLicenseCodes() {
return licenseCodes;
}
/**
* Integer license codes indicating which licenses are attached to this image.
* @param licenseCodes licenseCodes or {@code null} for none
*/
public Image setLicenseCodes(java.util.List<java.lang.Long> licenseCodes) {
this.licenseCodes = licenseCodes;
return this;
}
/**
* Any applicable license URI.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getLicenses() {
return licenses;
}
/**
* Any applicable license URI.
* @param licenses licenses or {@code null} for none
*/
public Image setLicenses(java.util.List<java.lang.String> licenses) {
this.licenses = licenses;
return this;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* @param name name or {@code null} for none
*/
public Image setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* The parameters of the raw disk image.
* @return value or {@code null} for none
*/
public RawDisk getRawDisk() {
return rawDisk;
}
/**
* The parameters of the raw disk image.
* @param rawDisk rawDisk or {@code null} for none
*/
public Image setRawDisk(RawDisk rawDisk) {
this.rawDisk = rawDisk;
return this;
}
/**
* [Output Only] Server-defined URL for the resource.
* @return value or {@code null} for none
*/
public java.lang.String getSelfLink() {
return selfLink;
}
/**
* [Output Only] Server-defined URL for the resource.
* @param selfLink selfLink or {@code null} for none
*/
public Image setSelfLink(java.lang.String selfLink) {
this.selfLink = selfLink;
return this;
}
/**
* URL of the source disk used to create this image. This can be a full or valid partial URL. You
* must provide either this property or the rawDisk.source property but not both to create an
* image. For example, the following are valid values: -
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/disks/disk -
* projects/project/zones/zone/disks/disk - zones/zone/disks/disk
* @return value or {@code null} for none
*/
public java.lang.String getSourceDisk() {
return sourceDisk;
}
/**
* URL of the source disk used to create this image. This can be a full or valid partial URL. You
* must provide either this property or the rawDisk.source property but not both to create an
* image. For example, the following are valid values: -
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/disks/disk -
* projects/project/zones/zone/disks/disk - zones/zone/disks/disk
* @param sourceDisk sourceDisk or {@code null} for none
*/
public Image setSourceDisk(java.lang.String sourceDisk) {
this.sourceDisk = sourceDisk;
return this;
}
/**
* The customer-supplied encryption key of the source disk. Required if the source disk is
* protected by a customer-supplied encryption key.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getSourceDiskEncryptionKey() {
return sourceDiskEncryptionKey;
}
/**
* The customer-supplied encryption key of the source disk. Required if the source disk is
* protected by a customer-supplied encryption key.
* @param sourceDiskEncryptionKey sourceDiskEncryptionKey or {@code null} for none
*/
public Image setSourceDiskEncryptionKey(CustomerEncryptionKey sourceDiskEncryptionKey) {
this.sourceDiskEncryptionKey = sourceDiskEncryptionKey;
return this;
}
/**
* [Output Only] The ID value of the disk used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given disk
* name.
* @return value or {@code null} for none
*/
public java.lang.String getSourceDiskId() {
return sourceDiskId;
}
/**
* [Output Only] The ID value of the disk used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given disk
* name.
* @param sourceDiskId sourceDiskId or {@code null} for none
*/
public Image setSourceDiskId(java.lang.String sourceDiskId) {
this.sourceDiskId = sourceDiskId;
return this;
}
/**
* URL of the source image used to create this image. This can be a full or valid partial URL. You
* must provide exactly one of: - this property, or - the rawDisk.source property, or - the
* sourceDisk property in order to create an image.
* @return value or {@code null} for none
*/
public java.lang.String getSourceImage() {
return sourceImage;
}
/**
* URL of the source image used to create this image. This can be a full or valid partial URL. You
* must provide exactly one of: - this property, or - the rawDisk.source property, or - the
* sourceDisk property in order to create an image.
* @param sourceImage sourceImage or {@code null} for none
*/
public Image setSourceImage(java.lang.String sourceImage) {
this.sourceImage = sourceImage;
return this;
}
/**
* The customer-supplied encryption key of the source image. Required if the source image is
* protected by a customer-supplied encryption key.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getSourceImageEncryptionKey() {
return sourceImageEncryptionKey;
}
/**
* The customer-supplied encryption key of the source image. Required if the source image is
* protected by a customer-supplied encryption key.
* @param sourceImageEncryptionKey sourceImageEncryptionKey or {@code null} for none
*/
public Image setSourceImageEncryptionKey(CustomerEncryptionKey sourceImageEncryptionKey) {
this.sourceImageEncryptionKey = sourceImageEncryptionKey;
return this;
}
/**
* [Output Only] The ID value of the image used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given image
* name.
* @return value or {@code null} for none
*/
public java.lang.String getSourceImageId() {
return sourceImageId;
}
/**
* [Output Only] The ID value of the image used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given image
* name.
* @param sourceImageId sourceImageId or {@code null} for none
*/
public Image setSourceImageId(java.lang.String sourceImageId) {
this.sourceImageId = sourceImageId;
return this;
}
/**
* URL of the source snapshot used to create this image. This can be a full or valid partial URL.
* You must provide exactly one of: - this property, or - the sourceImage property, or - the
* rawDisk.source property, or - the sourceDisk property in order to create an image.
* @return value or {@code null} for none
*/
public java.lang.String getSourceSnapshot() {
return sourceSnapshot;
}
/**
* URL of the source snapshot used to create this image. This can be a full or valid partial URL.
* You must provide exactly one of: - this property, or - the sourceImage property, or - the
* rawDisk.source property, or - the sourceDisk property in order to create an image.
* @param sourceSnapshot sourceSnapshot or {@code null} for none
*/
public Image setSourceSnapshot(java.lang.String sourceSnapshot) {
this.sourceSnapshot = sourceSnapshot;
return this;
}
/**
* The customer-supplied encryption key of the source snapshot. Required if the source snapshot is
* protected by a customer-supplied encryption key.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getSourceSnapshotEncryptionKey() {
return sourceSnapshotEncryptionKey;
}
/**
* The customer-supplied encryption key of the source snapshot. Required if the source snapshot is
* protected by a customer-supplied encryption key.
* @param sourceSnapshotEncryptionKey sourceSnapshotEncryptionKey or {@code null} for none
*/
public Image setSourceSnapshotEncryptionKey(CustomerEncryptionKey sourceSnapshotEncryptionKey) {
this.sourceSnapshotEncryptionKey = sourceSnapshotEncryptionKey;
return this;
}
/**
* [Output Only] The ID value of the snapshot used to create this image. This value may be used to
* determine whether the snapshot was taken from the current or a previous instance of a given
* snapshot name.
* @return value or {@code null} for none
*/
public java.lang.String getSourceSnapshotId() {
return sourceSnapshotId;
}
/**
* [Output Only] The ID value of the snapshot used to create this image. This value may be used to
* determine whether the snapshot was taken from the current or a previous instance of a given
* snapshot name.
* @param sourceSnapshotId sourceSnapshotId or {@code null} for none
*/
public Image setSourceSnapshotId(java.lang.String sourceSnapshotId) {
this.sourceSnapshotId = sourceSnapshotId;
return this;
}
/**
* The type of the image used to create this disk. The default and only value is RAW
* @return value or {@code null} for none
*/
public java.lang.String getSourceType() {
return sourceType;
}
/**
* The type of the image used to create this disk. The default and only value is RAW
* @param sourceType sourceType or {@code null} for none
*/
public Image setSourceType(java.lang.String sourceType) {
this.sourceType = sourceType;
return this;
}
/**
* [Output Only] The status of the image. An image can be used to create other resources, such as
* instances, only after the image has been successfully created and the status is set to READY.
* Possible values are FAILED, PENDING, or READY.
* @return value or {@code null} for none
*/
public java.lang.String getStatus() {
return status;
}
/**
* [Output Only] The status of the image. An image can be used to create other resources, such as
* instances, only after the image has been successfully created and the status is set to READY.
* Possible values are FAILED, PENDING, or READY.
* @param status status or {@code null} for none
*/
public Image setStatus(java.lang.String status) {
this.status = status;
return this;
}
/**
* Cloud Storage bucket storage location of the image (regional or multi-regional).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getStorageLocations() {
return storageLocations;
}
/**
* Cloud Storage bucket storage location of the image (regional or multi-regional).
* @param storageLocations storageLocations or {@code null} for none
*/
public Image setStorageLocations(java.util.List<java.lang.String> storageLocations) {
this.storageLocations = storageLocations;
return this;
}
@Override
public Image set(String fieldName, Object value) {
return (Image) super.set(fieldName, value);
}
@Override
public Image clone() {
return (Image) super.clone();
}
/**
* The parameters of the raw disk image.
*/
public static final class RawDisk extends com.google.api.client.json.GenericJson {
/**
* The format used to encode and transmit the block device, which should be TAR. This is just a
* container and transmission format and not a runtime format. Provided by the client when the
* disk image is created.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String containerType;
/**
* [Deprecated] This field is deprecated. An optional SHA1 checksum of the disk image before
* unpackaging provided by the client when the disk image is created.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sha1Checksum;
/**
* The full Google Cloud Storage URL where the disk image is stored. You must provide either this
* property or the sourceDisk property but not both.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String source;
/**
* The format used to encode and transmit the block device, which should be TAR. This is just a
* container and transmission format and not a runtime format. Provided by the client when the
* disk image is created.
* @return value or {@code null} for none
*/
public java.lang.String getContainerType() {
return containerType;
}
/**
* The format used to encode and transmit the block device, which should be TAR. This is just a
* container and transmission format and not a runtime format. Provided by the client when the
* disk image is created.
* @param containerType containerType or {@code null} for none
*/
public RawDisk setContainerType(java.lang.String containerType) {
this.containerType = containerType;
return this;
}
/**
* [Deprecated] This field is deprecated. An optional SHA1 checksum of the disk image before
* unpackaging provided by the client when the disk image is created.
* @return value or {@code null} for none
*/
public java.lang.String getSha1Checksum() {
return sha1Checksum;
}
/**
* [Deprecated] This field is deprecated. An optional SHA1 checksum of the disk image before
* unpackaging provided by the client when the disk image is created.
* @param sha1Checksum sha1Checksum or {@code null} for none
*/
public RawDisk setSha1Checksum(java.lang.String sha1Checksum) {
this.sha1Checksum = sha1Checksum;
return this;
}
/**
* The full Google Cloud Storage URL where the disk image is stored. You must provide either this
* property or the sourceDisk property but not both.
* @return value or {@code null} for none
*/
public java.lang.String getSource() {
return source;
}
/**
* The full Google Cloud Storage URL where the disk image is stored. You must provide either this
* property or the sourceDisk property but not both.
* @param source source or {@code null} for none
*/
public RawDisk setSource(java.lang.String source) {
this.source = source;
return this;
}
@Override
public RawDisk set(String fieldName, Object value) {
return (RawDisk) super.set(fieldName, value);
}
@Override
public RawDisk clone() {
return (RawDisk) super.clone();
}
}
}
|
googleapis/google-api-java-client-services | 36,654 | clients/google-api-services-compute/beta/1.29.2/com/google/api/services/compute/model/Image.java | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.compute.model;
/**
* Represents an Image resource.
*
* You can use images to create boot disks for your VM instances. For more information, read Images.
* (== resource_for beta.images ==) (== resource_for v1.images ==)
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class Image extends com.google.api.client.json.GenericJson {
/**
* Size of the image tar.gz archive stored in Google Cloud Storage (in bytes).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long archiveSizeBytes;
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String creationTimestamp;
/**
* The deprecation status associated with this image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private DeprecationStatus deprecated;
/**
* An optional description of this resource. Provide this property when you create the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* Size of the image when restored onto a persistent disk (in GB).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long diskSizeGb;
/**
* The name of the image family to which this image belongs. You can create disks by specifying an
* image family instead of a specific image name. The image family always returns its latest image
* that is not deprecated. The name of the image family must comply with RFC1035.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String family;
/**
* A list of features to enable on the guest operating system. Applicable only for bootable
* images. Read Enabling guest operating system features to see a list of available options.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GuestOsFeature> guestOsFeatures;
static {
// hack to force ProGuard to consider GuestOsFeature used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(GuestOsFeature.class);
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.math.BigInteger id;
/**
* Encrypts the image using a customer-supplied encryption key.
*
* After you encrypt an image with a customer-supplied key, you must provide the same key if you
* use the image later (e.g. to create a disk from the image).
*
* Customer-supplied encryption keys do not protect access to metadata of the disk.
*
* If you do not provide an encryption key when creating the image, then the disk will be
* encrypted using an automatically generated key and you do not need to provide a key to use the
* image later.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey imageEncryptionKey;
/**
* [Output Only] Type of the resource. Always compute#image for images.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String labelFingerprint;
/**
* Labels to apply to this image. These can be later modified by the setLabels method.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, java.lang.String> labels;
/**
* Integer license codes indicating which licenses are attached to this image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.util.List<java.lang.Long> licenseCodes;
/**
* Any applicable license URI.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> licenses;
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* The parameters of the raw disk image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private RawDisk rawDisk;
/**
* [Output Only] Server-defined URL for the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String selfLink;
/**
* URL of the source disk used to create this image. This can be a full or valid partial URL. You
* must provide either this property or the rawDisk.source property but not both to create an
* image. For example, the following are valid values: -
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/disks/disk -
* projects/project/zones/zone/disks/disk - zones/zone/disks/disk
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceDisk;
/**
* The customer-supplied encryption key of the source disk. Required if the source disk is
* protected by a customer-supplied encryption key.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey sourceDiskEncryptionKey;
/**
* [Output Only] The ID value of the disk used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given disk
* name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceDiskId;
/**
* URL of the source image used to create this image. This can be a full or valid partial URL. You
* must provide exactly one of: - this property, or - the rawDisk.source property, or - the
* sourceDisk property in order to create an image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceImage;
/**
* The customer-supplied encryption key of the source image. Required if the source image is
* protected by a customer-supplied encryption key.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey sourceImageEncryptionKey;
/**
* [Output Only] The ID value of the image used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given image
* name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceImageId;
/**
* URL of the source snapshot used to create this image. This can be a full or valid partial URL.
* You must provide exactly one of: - this property, or - the sourceImage property, or - the
* rawDisk.source property, or - the sourceDisk property in order to create an image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceSnapshot;
/**
* The customer-supplied encryption key of the source snapshot. Required if the source snapshot is
* protected by a customer-supplied encryption key.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomerEncryptionKey sourceSnapshotEncryptionKey;
/**
* [Output Only] The ID value of the snapshot used to create this image. This value may be used to
* determine whether the snapshot was taken from the current or a previous instance of a given
* snapshot name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceSnapshotId;
/**
* The type of the image used to create this disk. The default and only value is RAW
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sourceType;
/**
* [Output Only] The status of the image. An image can be used to create other resources, such as
* instances, only after the image has been successfully created and the status is set to READY.
* Possible values are FAILED, PENDING, or READY.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String status;
/**
* Cloud Storage bucket storage location of the image (regional or multi-regional).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> storageLocations;
/**
* Size of the image tar.gz archive stored in Google Cloud Storage (in bytes).
* @return value or {@code null} for none
*/
public java.lang.Long getArchiveSizeBytes() {
return archiveSizeBytes;
}
/**
* Size of the image tar.gz archive stored in Google Cloud Storage (in bytes).
* @param archiveSizeBytes archiveSizeBytes or {@code null} for none
*/
public Image setArchiveSizeBytes(java.lang.Long archiveSizeBytes) {
this.archiveSizeBytes = archiveSizeBytes;
return this;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @return value or {@code null} for none
*/
public java.lang.String getCreationTimestamp() {
return creationTimestamp;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @param creationTimestamp creationTimestamp or {@code null} for none
*/
public Image setCreationTimestamp(java.lang.String creationTimestamp) {
this.creationTimestamp = creationTimestamp;
return this;
}
/**
* The deprecation status associated with this image.
* @return value or {@code null} for none
*/
public DeprecationStatus getDeprecated() {
return deprecated;
}
/**
* The deprecation status associated with this image.
* @param deprecated deprecated or {@code null} for none
*/
public Image setDeprecated(DeprecationStatus deprecated) {
this.deprecated = deprecated;
return this;
}
/**
* An optional description of this resource. Provide this property when you create the resource.
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* An optional description of this resource. Provide this property when you create the resource.
* @param description description or {@code null} for none
*/
public Image setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* Size of the image when restored onto a persistent disk (in GB).
* @return value or {@code null} for none
*/
public java.lang.Long getDiskSizeGb() {
return diskSizeGb;
}
/**
* Size of the image when restored onto a persistent disk (in GB).
* @param diskSizeGb diskSizeGb or {@code null} for none
*/
public Image setDiskSizeGb(java.lang.Long diskSizeGb) {
this.diskSizeGb = diskSizeGb;
return this;
}
/**
* The name of the image family to which this image belongs. You can create disks by specifying an
* image family instead of a specific image name. The image family always returns its latest image
* that is not deprecated. The name of the image family must comply with RFC1035.
* @return value or {@code null} for none
*/
public java.lang.String getFamily() {
return family;
}
/**
* The name of the image family to which this image belongs. You can create disks by specifying an
* image family instead of a specific image name. The image family always returns its latest image
* that is not deprecated. The name of the image family must comply with RFC1035.
* @param family family or {@code null} for none
*/
public Image setFamily(java.lang.String family) {
this.family = family;
return this;
}
/**
* A list of features to enable on the guest operating system. Applicable only for bootable
* images. Read Enabling guest operating system features to see a list of available options.
* @return value or {@code null} for none
*/
public java.util.List<GuestOsFeature> getGuestOsFeatures() {
return guestOsFeatures;
}
/**
* A list of features to enable on the guest operating system. Applicable only for bootable
* images. Read Enabling guest operating system features to see a list of available options.
* @param guestOsFeatures guestOsFeatures or {@code null} for none
*/
public Image setGuestOsFeatures(java.util.List<GuestOsFeature> guestOsFeatures) {
this.guestOsFeatures = guestOsFeatures;
return this;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @return value or {@code null} for none
*/
public java.math.BigInteger getId() {
return id;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @param id id or {@code null} for none
*/
public Image setId(java.math.BigInteger id) {
this.id = id;
return this;
}
/**
* Encrypts the image using a customer-supplied encryption key.
*
* After you encrypt an image with a customer-supplied key, you must provide the same key if you
* use the image later (e.g. to create a disk from the image).
*
* Customer-supplied encryption keys do not protect access to metadata of the disk.
*
* If you do not provide an encryption key when creating the image, then the disk will be
* encrypted using an automatically generated key and you do not need to provide a key to use the
* image later.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getImageEncryptionKey() {
return imageEncryptionKey;
}
/**
* Encrypts the image using a customer-supplied encryption key.
*
* After you encrypt an image with a customer-supplied key, you must provide the same key if you
* use the image later (e.g. to create a disk from the image).
*
* Customer-supplied encryption keys do not protect access to metadata of the disk.
*
* If you do not provide an encryption key when creating the image, then the disk will be
* encrypted using an automatically generated key and you do not need to provide a key to use the
* image later.
* @param imageEncryptionKey imageEncryptionKey or {@code null} for none
*/
public Image setImageEncryptionKey(CustomerEncryptionKey imageEncryptionKey) {
this.imageEncryptionKey = imageEncryptionKey;
return this;
}
/**
* [Output Only] Type of the resource. Always compute#image for images.
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* [Output Only] Type of the resource. Always compute#image for images.
* @param kind kind or {@code null} for none
*/
public Image setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #decodeLabelFingerprint()
* @return value or {@code null} for none
*/
public java.lang.String getLabelFingerprint() {
return labelFingerprint;
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #getLabelFingerprint()
* @return Base64 decoded value or {@code null} for none
*
* @since 1.14
*/
public byte[] decodeLabelFingerprint() {
return com.google.api.client.util.Base64.decodeBase64(labelFingerprint);
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #encodeLabelFingerprint()
* @param labelFingerprint labelFingerprint or {@code null} for none
*/
public Image setLabelFingerprint(java.lang.String labelFingerprint) {
this.labelFingerprint = labelFingerprint;
return this;
}
/**
* A fingerprint for the labels being applied to this image, which is essentially a hash of the
* labels used for optimistic locking. The fingerprint is initially generated by Compute Engine
* and changes after every request to modify or update labels. You must always provide an up-to-
* date fingerprint hash in order to update or change labels, otherwise the request will fail with
* error 412 conditionNotMet.
*
* To see the latest fingerprint, make a get() request to retrieve an image.
* @see #setLabelFingerprint()
*
* <p>
* The value is encoded Base64 or {@code null} for none.
* </p>
*
* @since 1.14
*/
public Image encodeLabelFingerprint(byte[] labelFingerprint) {
this.labelFingerprint = com.google.api.client.util.Base64.encodeBase64URLSafeString(labelFingerprint);
return this;
}
/**
* Labels to apply to this image. These can be later modified by the setLabels method.
* @return value or {@code null} for none
*/
public java.util.Map<String, java.lang.String> getLabels() {
return labels;
}
/**
* Labels to apply to this image. These can be later modified by the setLabels method.
* @param labels labels or {@code null} for none
*/
public Image setLabels(java.util.Map<String, java.lang.String> labels) {
this.labels = labels;
return this;
}
/**
* Integer license codes indicating which licenses are attached to this image.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.Long> getLicenseCodes() {
return licenseCodes;
}
/**
* Integer license codes indicating which licenses are attached to this image.
* @param licenseCodes licenseCodes or {@code null} for none
*/
public Image setLicenseCodes(java.util.List<java.lang.Long> licenseCodes) {
this.licenseCodes = licenseCodes;
return this;
}
/**
* Any applicable license URI.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getLicenses() {
return licenses;
}
/**
* Any applicable license URI.
* @param licenses licenses or {@code null} for none
*/
public Image setLicenses(java.util.List<java.lang.String> licenses) {
this.licenses = licenses;
return this;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of the resource; provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* @param name name or {@code null} for none
*/
public Image setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* The parameters of the raw disk image.
* @return value or {@code null} for none
*/
public RawDisk getRawDisk() {
return rawDisk;
}
/**
* The parameters of the raw disk image.
* @param rawDisk rawDisk or {@code null} for none
*/
public Image setRawDisk(RawDisk rawDisk) {
this.rawDisk = rawDisk;
return this;
}
/**
* [Output Only] Server-defined URL for the resource.
* @return value or {@code null} for none
*/
public java.lang.String getSelfLink() {
return selfLink;
}
/**
* [Output Only] Server-defined URL for the resource.
* @param selfLink selfLink or {@code null} for none
*/
public Image setSelfLink(java.lang.String selfLink) {
this.selfLink = selfLink;
return this;
}
/**
* URL of the source disk used to create this image. This can be a full or valid partial URL. You
* must provide either this property or the rawDisk.source property but not both to create an
* image. For example, the following are valid values: -
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/disks/disk -
* projects/project/zones/zone/disks/disk - zones/zone/disks/disk
* @return value or {@code null} for none
*/
public java.lang.String getSourceDisk() {
return sourceDisk;
}
/**
* URL of the source disk used to create this image. This can be a full or valid partial URL. You
* must provide either this property or the rawDisk.source property but not both to create an
* image. For example, the following are valid values: -
* https://www.googleapis.com/compute/v1/projects/project/zones/zone/disks/disk -
* projects/project/zones/zone/disks/disk - zones/zone/disks/disk
* @param sourceDisk sourceDisk or {@code null} for none
*/
public Image setSourceDisk(java.lang.String sourceDisk) {
this.sourceDisk = sourceDisk;
return this;
}
/**
* The customer-supplied encryption key of the source disk. Required if the source disk is
* protected by a customer-supplied encryption key.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getSourceDiskEncryptionKey() {
return sourceDiskEncryptionKey;
}
/**
* The customer-supplied encryption key of the source disk. Required if the source disk is
* protected by a customer-supplied encryption key.
* @param sourceDiskEncryptionKey sourceDiskEncryptionKey or {@code null} for none
*/
public Image setSourceDiskEncryptionKey(CustomerEncryptionKey sourceDiskEncryptionKey) {
this.sourceDiskEncryptionKey = sourceDiskEncryptionKey;
return this;
}
/**
* [Output Only] The ID value of the disk used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given disk
* name.
* @return value or {@code null} for none
*/
public java.lang.String getSourceDiskId() {
return sourceDiskId;
}
/**
* [Output Only] The ID value of the disk used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given disk
* name.
* @param sourceDiskId sourceDiskId or {@code null} for none
*/
public Image setSourceDiskId(java.lang.String sourceDiskId) {
this.sourceDiskId = sourceDiskId;
return this;
}
/**
* URL of the source image used to create this image. This can be a full or valid partial URL. You
* must provide exactly one of: - this property, or - the rawDisk.source property, or - the
* sourceDisk property in order to create an image.
* @return value or {@code null} for none
*/
public java.lang.String getSourceImage() {
return sourceImage;
}
/**
* URL of the source image used to create this image. This can be a full or valid partial URL. You
* must provide exactly one of: - this property, or - the rawDisk.source property, or - the
* sourceDisk property in order to create an image.
* @param sourceImage sourceImage or {@code null} for none
*/
public Image setSourceImage(java.lang.String sourceImage) {
this.sourceImage = sourceImage;
return this;
}
/**
* The customer-supplied encryption key of the source image. Required if the source image is
* protected by a customer-supplied encryption key.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getSourceImageEncryptionKey() {
return sourceImageEncryptionKey;
}
/**
* The customer-supplied encryption key of the source image. Required if the source image is
* protected by a customer-supplied encryption key.
* @param sourceImageEncryptionKey sourceImageEncryptionKey or {@code null} for none
*/
public Image setSourceImageEncryptionKey(CustomerEncryptionKey sourceImageEncryptionKey) {
this.sourceImageEncryptionKey = sourceImageEncryptionKey;
return this;
}
/**
* [Output Only] The ID value of the image used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given image
* name.
* @return value or {@code null} for none
*/
public java.lang.String getSourceImageId() {
return sourceImageId;
}
/**
* [Output Only] The ID value of the image used to create this image. This value may be used to
* determine whether the image was taken from the current or a previous instance of a given image
* name.
* @param sourceImageId sourceImageId or {@code null} for none
*/
public Image setSourceImageId(java.lang.String sourceImageId) {
this.sourceImageId = sourceImageId;
return this;
}
/**
* URL of the source snapshot used to create this image. This can be a full or valid partial URL.
* You must provide exactly one of: - this property, or - the sourceImage property, or - the
* rawDisk.source property, or - the sourceDisk property in order to create an image.
* @return value or {@code null} for none
*/
public java.lang.String getSourceSnapshot() {
return sourceSnapshot;
}
/**
* URL of the source snapshot used to create this image. This can be a full or valid partial URL.
* You must provide exactly one of: - this property, or - the sourceImage property, or - the
* rawDisk.source property, or - the sourceDisk property in order to create an image.
* @param sourceSnapshot sourceSnapshot or {@code null} for none
*/
public Image setSourceSnapshot(java.lang.String sourceSnapshot) {
this.sourceSnapshot = sourceSnapshot;
return this;
}
/**
* The customer-supplied encryption key of the source snapshot. Required if the source snapshot is
* protected by a customer-supplied encryption key.
* @return value or {@code null} for none
*/
public CustomerEncryptionKey getSourceSnapshotEncryptionKey() {
return sourceSnapshotEncryptionKey;
}
/**
* The customer-supplied encryption key of the source snapshot. Required if the source snapshot is
* protected by a customer-supplied encryption key.
* @param sourceSnapshotEncryptionKey sourceSnapshotEncryptionKey or {@code null} for none
*/
public Image setSourceSnapshotEncryptionKey(CustomerEncryptionKey sourceSnapshotEncryptionKey) {
this.sourceSnapshotEncryptionKey = sourceSnapshotEncryptionKey;
return this;
}
/**
* [Output Only] The ID value of the snapshot used to create this image. This value may be used to
* determine whether the snapshot was taken from the current or a previous instance of a given
* snapshot name.
* @return value or {@code null} for none
*/
public java.lang.String getSourceSnapshotId() {
return sourceSnapshotId;
}
/**
* [Output Only] The ID value of the snapshot used to create this image. This value may be used to
* determine whether the snapshot was taken from the current or a previous instance of a given
* snapshot name.
* @param sourceSnapshotId sourceSnapshotId or {@code null} for none
*/
public Image setSourceSnapshotId(java.lang.String sourceSnapshotId) {
this.sourceSnapshotId = sourceSnapshotId;
return this;
}
/**
* The type of the image used to create this disk. The default and only value is RAW
* @return value or {@code null} for none
*/
public java.lang.String getSourceType() {
return sourceType;
}
/**
* The type of the image used to create this disk. The default and only value is RAW
* @param sourceType sourceType or {@code null} for none
*/
public Image setSourceType(java.lang.String sourceType) {
this.sourceType = sourceType;
return this;
}
/**
* [Output Only] The status of the image. An image can be used to create other resources, such as
* instances, only after the image has been successfully created and the status is set to READY.
* Possible values are FAILED, PENDING, or READY.
* @return value or {@code null} for none
*/
public java.lang.String getStatus() {
return status;
}
/**
* [Output Only] The status of the image. An image can be used to create other resources, such as
* instances, only after the image has been successfully created and the status is set to READY.
* Possible values are FAILED, PENDING, or READY.
* @param status status or {@code null} for none
*/
public Image setStatus(java.lang.String status) {
this.status = status;
return this;
}
/**
* Cloud Storage bucket storage location of the image (regional or multi-regional).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getStorageLocations() {
return storageLocations;
}
/**
* Cloud Storage bucket storage location of the image (regional or multi-regional).
* @param storageLocations storageLocations or {@code null} for none
*/
public Image setStorageLocations(java.util.List<java.lang.String> storageLocations) {
this.storageLocations = storageLocations;
return this;
}
@Override
public Image set(String fieldName, Object value) {
return (Image) super.set(fieldName, value);
}
@Override
public Image clone() {
return (Image) super.clone();
}
/**
* The parameters of the raw disk image.
*/
public static final class RawDisk extends com.google.api.client.json.GenericJson {
/**
* The format used to encode and transmit the block device, which should be TAR. This is just a
* container and transmission format and not a runtime format. Provided by the client when the
* disk image is created.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String containerType;
/**
* [Deprecated] This field is deprecated. An optional SHA1 checksum of the disk image before
* unpackaging provided by the client when the disk image is created.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sha1Checksum;
/**
* The full Google Cloud Storage URL where the disk image is stored. You must provide either this
* property or the sourceDisk property but not both.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String source;
/**
* The format used to encode and transmit the block device, which should be TAR. This is just a
* container and transmission format and not a runtime format. Provided by the client when the
* disk image is created.
* @return value or {@code null} for none
*/
public java.lang.String getContainerType() {
return containerType;
}
/**
* The format used to encode and transmit the block device, which should be TAR. This is just a
* container and transmission format and not a runtime format. Provided by the client when the
* disk image is created.
* @param containerType containerType or {@code null} for none
*/
public RawDisk setContainerType(java.lang.String containerType) {
this.containerType = containerType;
return this;
}
/**
* [Deprecated] This field is deprecated. An optional SHA1 checksum of the disk image before
* unpackaging provided by the client when the disk image is created.
* @return value or {@code null} for none
*/
public java.lang.String getSha1Checksum() {
return sha1Checksum;
}
/**
* [Deprecated] This field is deprecated. An optional SHA1 checksum of the disk image before
* unpackaging provided by the client when the disk image is created.
* @param sha1Checksum sha1Checksum or {@code null} for none
*/
public RawDisk setSha1Checksum(java.lang.String sha1Checksum) {
this.sha1Checksum = sha1Checksum;
return this;
}
/**
* The full Google Cloud Storage URL where the disk image is stored. You must provide either this
* property or the sourceDisk property but not both.
* @return value or {@code null} for none
*/
public java.lang.String getSource() {
return source;
}
/**
* The full Google Cloud Storage URL where the disk image is stored. You must provide either this
* property or the sourceDisk property but not both.
* @param source source or {@code null} for none
*/
public RawDisk setSource(java.lang.String source) {
this.source = source;
return this;
}
@Override
public RawDisk set(String fieldName, Object value) {
return (RawDisk) super.set(fieldName, value);
}
@Override
public RawDisk clone() {
return (RawDisk) super.clone();
}
}
}
|
apache/incubator-seata | 36,765 | server/src/main/java/org/apache/seata/server/storage/redis/store/RedisTransactionStoreManager.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.seata.server.storage.redis.store;
import com.google.common.collect.ImmutableMap;
import org.apache.seata.common.XID;
import org.apache.seata.common.exception.RedisException;
import org.apache.seata.common.exception.StoreException;
import org.apache.seata.common.util.BeanUtils;
import org.apache.seata.common.util.CollectionUtils;
import org.apache.seata.common.util.StringUtils;
import org.apache.seata.config.Configuration;
import org.apache.seata.config.ConfigurationFactory;
import org.apache.seata.core.model.GlobalStatus;
import org.apache.seata.core.store.BranchTransactionDO;
import org.apache.seata.core.store.GlobalTransactionDO;
import org.apache.seata.server.console.entity.param.GlobalSessionParam;
import org.apache.seata.server.session.GlobalSession;
import org.apache.seata.server.session.SessionCondition;
import org.apache.seata.server.session.SessionStatusValidator;
import org.apache.seata.server.storage.SessionConverter;
import org.apache.seata.server.storage.redis.JedisPooledFactory;
import org.apache.seata.server.store.AbstractTransactionStoreManager;
import org.apache.seata.server.store.SessionStorable;
import org.apache.seata.server.store.TransactionStoreManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Transaction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.apache.seata.common.ConfigurationKeys.STORE_REDIS_QUERY_LIMIT;
import static org.apache.seata.common.DefaultValues.DEFAULT_QUERY_LIMIT;
import static org.apache.seata.core.constants.RedisKeyConstants.REDIS_KEY_BRANCH_APPLICATION_DATA;
import static org.apache.seata.core.constants.RedisKeyConstants.REDIS_KEY_BRANCH_GMT_MODIFIED;
import static org.apache.seata.core.constants.RedisKeyConstants.REDIS_KEY_BRANCH_STATUS;
import static org.apache.seata.core.constants.RedisKeyConstants.REDIS_KEY_BRANCH_XID;
import static org.apache.seata.core.constants.RedisKeyConstants.REDIS_KEY_GLOBAL_GMT_MODIFIED;
import static org.apache.seata.core.constants.RedisKeyConstants.REDIS_KEY_GLOBAL_STATUS;
import static org.apache.seata.core.constants.RedisKeyConstants.REDIS_KEY_GLOBAL_XID;
/**
* The redis transaction store manager
*
*/
public class RedisTransactionStoreManager extends AbstractTransactionStoreManager implements TransactionStoreManager {
private static final Logger LOGGER = LoggerFactory.getLogger(RedisTransactionStoreManager.class);
/**
* the prefix of the branch transactions
*/
private static final String REDIS_SEATA_BRANCHES_PREFIX = "SEATA_BRANCHES_";
/**
* the prefix of the branch transaction
*/
private static final String REDIS_SEATA_BRANCH_PREFIX = "SEATA_BRANCH_";
/**
* the prefix of the global transaction
*/
private static final String REDIS_SEATA_GLOBAL_PREFIX = "SEATA_GLOBAL_";
/**
* the prefix of the global transaction status
*/
private static final String REDIS_SEATA_STATUS_PREFIX = "SEATA_STATUS_";
/**the key of global transaction status for begin*/
protected static final String REDIS_SEATA_BEGIN_TRANSACTIONS_KEY = "SEATA_BEGIN_TRANSACTIONS";
private static volatile RedisTransactionStoreManager instance;
private static final String OK = "OK";
/**
* The constant CONFIG.
*/
protected static final Configuration CONFIG = ConfigurationFactory.getInstance();
/**
* The Log query limit.
*/
protected int logQueryLimit;
/**
* Get the instance.
*/
public static RedisTransactionStoreManager getInstance() {
if (instance == null) {
synchronized (RedisTransactionStoreManager.class) {
if (instance == null) {
instance = new RedisTransactionStoreManager();
}
}
}
return instance;
}
/**
* init map to constructor
*/
public RedisTransactionStoreManager() {
super();
initGlobalMap();
initBranchMap();
initLogQueryLimit();
}
protected void initLogQueryLimit() {
logQueryLimit = CONFIG.getInt(STORE_REDIS_QUERY_LIMIT, DEFAULT_QUERY_LIMIT);
}
/**
* Map for LogOperation Global Operation
*/
public static volatile ImmutableMap<LogOperation, Function<GlobalTransactionDO, Boolean>> globalMap;
/**
* Map for LogOperation Branch Operation
*/
public static volatile ImmutableMap<LogOperation, Function<BranchTransactionDO, Boolean>> branchMap;
/**
* init globalMap
*/
public void initGlobalMap() {
if (CollectionUtils.isEmpty(branchMap)) {
globalMap = ImmutableMap.<LogOperation, Function<GlobalTransactionDO, Boolean>>builder()
.put(LogOperation.GLOBAL_ADD, this::insertGlobalTransactionDO)
.put(LogOperation.GLOBAL_UPDATE, this::updateGlobalTransactionDO)
.put(LogOperation.GLOBAL_REMOVE, this::deleteGlobalTransactionDO)
.build();
}
}
/**
* init branchMap
*/
public void initBranchMap() {
if (CollectionUtils.isEmpty(branchMap)) {
branchMap = ImmutableMap.<LogOperation, Function<BranchTransactionDO, Boolean>>builder()
.put(LogOperation.BRANCH_ADD, this::insertBranchTransactionDO)
.put(LogOperation.BRANCH_UPDATE, this::updateBranchTransactionDO)
.put(LogOperation.BRANCH_REMOVE, this::deleteBranchTransactionDO)
.build();
}
}
@Override
public boolean writeSession(LogOperation logOperation, SessionStorable session) {
if (globalMap.containsKey(logOperation) || branchMap.containsKey(logOperation)) {
return globalMap.containsKey(logOperation)
? globalMap.get(logOperation).apply(SessionConverter.convertGlobalTransactionDO(session))
: branchMap.get(logOperation).apply(SessionConverter.convertBranchTransactionDO(session));
} else {
throw new StoreException("Unknown LogOperation:" + logOperation.name());
}
}
/**
* Insert branch transaction
*
* @param branchTransactionDO
* @return the boolean
*/
protected boolean insertBranchTransactionDO(BranchTransactionDO branchTransactionDO) {
String branchKey = buildBranchKey(branchTransactionDO.getBranchId());
String branchListKey = buildBranchListKeyByXid(branchTransactionDO.getXid());
try (Jedis jedis = JedisPooledFactory.getJedisInstance();
Pipeline pipelined = jedis.pipelined()) {
Date now = new Date();
branchTransactionDO.setGmtCreate(now);
branchTransactionDO.setGmtModified(now);
pipelined.hmset(branchKey, BeanUtils.objectToMap(branchTransactionDO));
pipelined.rpush(branchListKey, branchKey);
pipelined.sync();
return true;
} catch (Exception ex) {
throw new RedisException(ex);
}
}
/**
* Delete the branch transaction
*
* @param branchTransactionDO
* @return
*/
protected boolean deleteBranchTransactionDO(BranchTransactionDO branchTransactionDO) {
String branchKey = buildBranchKey(branchTransactionDO.getBranchId());
String branchListKey = buildBranchListKeyByXid(branchTransactionDO.getXid());
try (Jedis jedis = JedisPooledFactory.getJedisInstance()) {
String xid = jedis.hget(branchKey, REDIS_KEY_BRANCH_XID);
if (StringUtils.isEmpty(xid)) {
return true;
}
try (Pipeline pipelined = jedis.pipelined()) {
pipelined.lrem(branchListKey, 0, branchKey);
pipelined.del(branchKey);
pipelined.sync();
}
return true;
} catch (Exception ex) {
throw new RedisException(ex);
}
}
/**
* Update the branch transaction
*
* @param branchTransactionDO
* @return
*/
protected boolean updateBranchTransactionDO(BranchTransactionDO branchTransactionDO) {
String branchKey = buildBranchKey(branchTransactionDO.getBranchId());
String branchStatus = String.valueOf(branchTransactionDO.getStatus());
String applicationData = String.valueOf(branchTransactionDO.getApplicationData());
try (Jedis jedis = JedisPooledFactory.getJedisInstance()) {
String previousBranchStatus = jedis.hget(branchKey, REDIS_KEY_BRANCH_STATUS);
if (StringUtils.isEmpty(previousBranchStatus)) {
throw new StoreException("Branch transaction is not exist, update branch transaction failed.");
}
Map<String, String> map = new HashMap<>(3, 1);
map.put(REDIS_KEY_BRANCH_STATUS, branchStatus);
map.put(REDIS_KEY_BRANCH_GMT_MODIFIED, String.valueOf((new Date()).getTime()));
if (StringUtils.isNotBlank(branchTransactionDO.getApplicationData())) {
map.put(REDIS_KEY_BRANCH_APPLICATION_DATA, applicationData);
}
jedis.hmset(branchKey, map);
return true;
} catch (Exception ex) {
throw new RedisException(ex);
}
}
/**
* Insert the global transaction.
*
* @param globalTransactionDO
* @return
*/
protected boolean insertGlobalTransactionDO(GlobalTransactionDO globalTransactionDO) {
String globalKey = buildGlobalKeyByTransactionId(globalTransactionDO.getTransactionId());
try (Jedis jedis = JedisPooledFactory.getJedisInstance();
Pipeline pipelined = jedis.pipelined()) {
Date now = new Date();
globalTransactionDO.setGmtCreate(now);
globalTransactionDO.setGmtModified(now);
pipelined.hmset(globalKey, BeanUtils.objectToMap(globalTransactionDO));
String xid = globalTransactionDO.getXid();
pipelined.rpush(buildGlobalStatus(globalTransactionDO.getStatus()), xid);
pipelined.zadd(
REDIS_SEATA_BEGIN_TRANSACTIONS_KEY,
globalTransactionDO.getBeginTime() + globalTransactionDO.getTimeout(),
globalKey);
pipelined.sync();
return true;
} catch (Exception ex) {
throw new RedisException(ex);
}
}
/**
* Delete the global transaction.
* It will operate two parts:
* 1.delete the global session map
* 2.remove the xid from the global status list
* If the operate failed,the succeed operates will rollback
*
* @param globalTransactionDO
* @return
*/
protected boolean deleteGlobalTransactionDO(GlobalTransactionDO globalTransactionDO) {
String globalKey = buildGlobalKeyByTransactionId(globalTransactionDO.getTransactionId());
String globalStatus = buildGlobalStatus(globalTransactionDO.getStatus());
try (Jedis jedis = JedisPooledFactory.getJedisInstance()) {
// pipeline mode
String xid = jedis.hget(globalKey, REDIS_KEY_GLOBAL_XID);
if (StringUtils.isEmpty(xid)) {
LOGGER.warn(
"Global transaction is not exist,xid = {}.Maybe has been deleted by another tc server",
globalTransactionDO.getXid());
return true;
}
try (Pipeline pipelined = jedis.pipelined()) {
pipelined.lrem(globalStatus, 0, globalTransactionDO.getXid());
pipelined.del(globalKey);
if (GlobalStatus.Begin.getCode() == globalTransactionDO.getStatus()
|| GlobalStatus.UnKnown.getCode() == globalTransactionDO.getStatus()) {
pipelined.zrem(REDIS_SEATA_BEGIN_TRANSACTIONS_KEY, globalKey);
}
pipelined.sync();
}
return true;
} catch (Exception ex) {
throw new RedisException(ex);
}
}
/**
* Update the global transaction.
* It will update two parts:
* 1.the global session map
* 2.the global status list
* If the update failed,the succeed operates will rollback
*
* @param globalTransactionDO
* @return
*/
protected boolean updateGlobalTransactionDO(GlobalTransactionDO globalTransactionDO) {
String xid = globalTransactionDO.getXid();
String globalKey = buildGlobalKeyByTransactionId(globalTransactionDO.getTransactionId());
Integer status = globalTransactionDO.getStatus();
try (Jedis jedis = JedisPooledFactory.getJedisInstance()) {
// Defensive watch to prevent other TC server operating concurrently,Fail fast
jedis.watch(globalKey);
List<String> statusAndGmtModified =
jedis.hmget(globalKey, REDIS_KEY_GLOBAL_STATUS, REDIS_KEY_GLOBAL_GMT_MODIFIED);
String previousStatus = statusAndGmtModified.get(0);
if (StringUtils.isEmpty(previousStatus)) {
jedis.unwatch();
throw new StoreException("Global transaction is not exist, update global transaction failed.");
}
if (previousStatus.equals(String.valueOf(status))) {
jedis.unwatch();
return true;
}
GlobalStatus before = GlobalStatus.get(Integer.parseInt(previousStatus));
GlobalStatus after = GlobalStatus.get(status);
if (!SessionStatusValidator.validateUpdateStatus(before, after)) {
throw new StoreException(
"Illegal changing of global status, update global transaction failed." + " beforeStatus["
+ before.name() + "] cannot be changed to afterStatus[" + after.name() + "]");
}
String previousGmtModified = statusAndGmtModified.get(1);
Transaction multi = jedis.multi();
Map<String, String> map = new HashMap<>(2);
map.put(REDIS_KEY_GLOBAL_STATUS, String.valueOf(globalTransactionDO.getStatus()));
map.put(REDIS_KEY_GLOBAL_GMT_MODIFIED, String.valueOf((new Date()).getTime()));
multi.hmset(globalKey, map);
multi.lrem(buildGlobalStatus(Integer.valueOf(previousStatus)), 0, xid);
multi.rpush(buildGlobalStatus(globalTransactionDO.getStatus()), xid);
multi.zrem(REDIS_SEATA_BEGIN_TRANSACTIONS_KEY, globalKey);
List<Object> exec = multi.exec();
if (CollectionUtils.isEmpty(exec)) {
// The data has changed by another tc, so we still think the modification is successful.
LOGGER.warn(
"The global transaction xid = {}, maybe changed by another TC. It does not affect the results",
xid);
return true;
}
String hmset = exec.get(0).toString();
long lrem = (long) exec.get(1);
long rpush = (long) exec.get(2);
if (OK.equalsIgnoreCase(hmset) && lrem > 0 && rpush > 0) {
return true;
} else {
// pipeline mode
if (OK.equalsIgnoreCase(hmset)) {
// Defensive watch to prevent other TC server operating concurrently,give up this operate
jedis.watch(globalKey);
String xid2 = jedis.hget(globalKey, REDIS_KEY_GLOBAL_XID);
if (StringUtils.isNotEmpty(xid2)) {
Map<String, String> mapPrevious = new HashMap<>(2, 1);
mapPrevious.put(REDIS_KEY_GLOBAL_STATUS, previousStatus);
mapPrevious.put(REDIS_KEY_GLOBAL_GMT_MODIFIED, previousGmtModified);
Transaction multi2 = jedis.multi();
multi2.hmset(globalKey, mapPrevious);
multi2.exec();
}
}
if (lrem > 0) {
jedis.rpush(buildGlobalStatus(Integer.valueOf(previousStatus)), xid);
}
if (rpush > 0) {
jedis.lrem(buildGlobalStatus(status), 0, xid);
}
return false;
}
} catch (Exception ex) {
throw new RedisException(ex);
}
}
/**
* Read session global session.
*
* @param xid the xid
* @param withBranchSessions the withBranchSessions
* @return the global session
*/
@Override
public GlobalSession readSession(String xid, boolean withBranchSessions) {
String transactionId = String.valueOf(XID.getTransactionId(xid));
String globalKey = buildGlobalKeyByTransactionId(transactionId);
try (Jedis jedis = JedisPooledFactory.getJedisInstance()) {
Map<String, String> map = jedis.hgetAll(globalKey);
if (CollectionUtils.isEmpty(map)) {
return null;
}
GlobalTransactionDO globalTransactionDO =
(GlobalTransactionDO) BeanUtils.mapToObject(map, GlobalTransactionDO.class);
List<BranchTransactionDO> branchTransactionDOs = null;
if (withBranchSessions) {
branchTransactionDOs = this.readBranchSessionByXid(jedis, xid);
}
GlobalSession session = getGlobalSession(globalTransactionDO, branchTransactionDOs, withBranchSessions);
return session;
}
}
/**
* Read session global session.
*
* @param xid the xid
* @return the global session
*/
@Override
public GlobalSession readSession(String xid) {
return this.readSession(xid, true);
}
/**
* Read globalSession list by global status
*
* @param statuses the statuses
* @return the list
*/
@Override
public List<GlobalSession> readSession(GlobalStatus[] statuses, boolean withBranchSessions) {
List<GlobalSession> globalSessions = Collections.synchronizedList(new ArrayList<>());
List<String> statusKeys = convertStatusKeys(statuses);
Map<String, Integer> targetMap = calculateStatuskeysHasData(statusKeys);
if (targetMap.size() == 0 || logQueryLimit <= 0) {
return globalSessions;
}
int perStatusLimit = resetLogQueryLimit(targetMap);
final long countGlobalSessions = targetMap.values().stream()
.collect(Collectors.summarizingInt(Integer::intValue))
.getSum();
// queryCount
final long queryCount = Math.min(logQueryLimit, countGlobalSessions);
List<List<String>> list = new ArrayList<>();
dogetXidsForTargetMapRecursive(targetMap, 0L, perStatusLimit - 1, queryCount, list);
if (CollectionUtils.isNotEmpty(list)) {
List<String> xids = list.stream().flatMap(Collection::stream).collect(Collectors.toList());
xids.parallelStream().forEach(xid -> {
GlobalSession globalSession = this.readSession(xid, withBranchSessions);
if (globalSession != null) {
globalSessions.add(globalSession);
}
});
}
return globalSessions;
}
@Override
public List<GlobalSession> readSortByTimeoutBeginSessions(boolean withBranchSessions) {
List<GlobalSession> list = Collections.emptyList();
List<String> statusKeys = convertStatusKeys(GlobalStatus.Begin);
Map<String, Integer> targetMap = calculateStatuskeysHasData(statusKeys);
if (targetMap.size() == 0 || logQueryLimit <= 0) {
return list;
}
final long countGlobalSessions = targetMap.values().stream()
.collect(Collectors.summarizingInt(Integer::intValue))
.getSum();
// queryCount
final long queryCount = Math.min(logQueryLimit, countGlobalSessions);
try (Jedis jedis = JedisPooledFactory.getJedisInstance()) {
Set<String> values = jedis.zrangeByScore(
REDIS_SEATA_BEGIN_TRANSACTIONS_KEY, 0, System.currentTimeMillis(), 0, (int) queryCount);
List<Map<String, String>> rep;
try (Pipeline pipeline = jedis.pipelined()) {
for (String value : values) {
pipeline.hgetAll(value);
}
rep = (List<Map<String, String>>) (List) pipeline.syncAndReturnAll();
}
list = rep.stream()
.map(map -> {
GlobalTransactionDO globalTransactionDO =
(GlobalTransactionDO) BeanUtils.mapToObject(map, GlobalTransactionDO.class);
if (globalTransactionDO != null) {
String xid = globalTransactionDO.getXid();
List<BranchTransactionDO> branchTransactionDOs = new ArrayList<>();
if (withBranchSessions) {
branchTransactionDOs = this.readBranchSessionByXid(jedis, xid);
}
return getGlobalSession(globalTransactionDO, branchTransactionDOs, withBranchSessions);
}
return null;
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
return list;
}
/**
* get everyone keys limit
*
* @param targetMap
* @return
*/
private int resetLogQueryLimit(Map<String, Integer> targetMap) {
int resetLimitQuery = logQueryLimit;
if (targetMap.size() > 1) {
int size = targetMap.size();
resetLimitQuery = (logQueryLimit / size) == 0 ? 1 : (logQueryLimit / size);
}
return resetLimitQuery;
}
/**
* read the global session list by different condition
*
* @param sessionCondition the session condition
* @return the global sessions
*/
@Override
public List<GlobalSession> readSession(SessionCondition sessionCondition) {
List<GlobalSession> globalSessions = new ArrayList<>();
if (StringUtils.isNotEmpty(sessionCondition.getXid())) {
GlobalSession globalSession =
this.readSession(sessionCondition.getXid(), !sessionCondition.isLazyLoadBranch());
if (globalSession != null) {
globalSessions.add(globalSession);
}
return globalSessions;
} else if (sessionCondition.getTransactionId() != null) {
GlobalSession globalSession = this.readSessionByTransactionId(
sessionCondition.getTransactionId().toString(), !sessionCondition.isLazyLoadBranch());
if (globalSession != null) {
globalSessions.add(globalSession);
}
return globalSessions;
} else if (CollectionUtils.isNotEmpty(sessionCondition.getStatuses())) {
if (sessionCondition.getStatuses().length == 1 && sessionCondition.getStatuses()[0] == GlobalStatus.Begin) {
return this.readSortByTimeoutBeginSessions(!sessionCondition.isLazyLoadBranch());
} else {
return readSession(sessionCondition.getStatuses(), !sessionCondition.isLazyLoadBranch());
}
}
return null;
}
/**
* query GlobalSession by status with page
*
* @param param
* @return List<GlobalSession>
*/
public List<GlobalSession> readSessionStatusByPage(GlobalSessionParam param) {
List<GlobalSession> globalSessions = new ArrayList<>();
int pageNum = param.getPageNum();
int pageSize = param.getPageSize();
int start = Math.max((pageNum - 1) * pageSize, 0);
int end = pageNum * pageSize - 1;
if (param.getStatus() != null) {
String statusKey =
buildGlobalStatus(GlobalStatus.get(param.getStatus()).getCode());
try (Jedis jedis = JedisPooledFactory.getJedisInstance()) {
final List<String> xids = jedis.lrange(statusKey, start, end);
xids.forEach(xid -> {
GlobalSession globalSession = this.readSession(xid, param.isWithBranch());
if (globalSession != null) {
globalSessions.add(globalSession);
}
});
}
}
return globalSessions;
}
/**
* assemble the global session and branch session
*
* @param globalTransactionDO the global transactionDo
* @param branchTransactionDOs the branch transactionDos
* @param withBranchSessions if read branch sessions
* @return the global session with branch session
*/
private GlobalSession getGlobalSession(
GlobalTransactionDO globalTransactionDO,
List<BranchTransactionDO> branchTransactionDOs,
boolean withBranchSessions) {
GlobalSession globalSession = SessionConverter.convertGlobalSession(globalTransactionDO, !withBranchSessions);
if (CollectionUtils.isNotEmpty(branchTransactionDOs)) {
for (BranchTransactionDO branchTransactionDO : branchTransactionDOs) {
globalSession.add(SessionConverter.convertBranchSession(branchTransactionDO));
}
}
return globalSession;
}
/**
* read the global session by transactionId
*
* @param transactionId the transaction id
* @param withBranchSessions if read branch sessions
* @return the global session
*/
private GlobalSession readSessionByTransactionId(String transactionId, boolean withBranchSessions) {
String globalKey = buildGlobalKeyByTransactionId(transactionId);
String xid = null;
try (Jedis jedis = JedisPooledFactory.getJedisInstance()) {
Map<String, String> map = jedis.hgetAll(globalKey);
if (CollectionUtils.isEmpty(map)) {
return null;
}
GlobalTransactionDO globalTransactionDO =
(GlobalTransactionDO) BeanUtils.mapToObject(map, GlobalTransactionDO.class);
if (globalTransactionDO != null) {
xid = globalTransactionDO.getXid();
}
List<BranchTransactionDO> branchTransactionDOs = new ArrayList<>();
if (withBranchSessions) {
branchTransactionDOs = this.readBranchSessionByXid(jedis, xid);
}
return getGlobalSession(globalTransactionDO, branchTransactionDOs, withBranchSessions);
}
}
/**
* Read the branch session list by xid
*
* @param jedis the jedis
* @param xid the xid
* @return the branch transactionDo list
*/
private List<BranchTransactionDO> readBranchSessionByXid(Jedis jedis, String xid) {
List<BranchTransactionDO> branchTransactionDOs = new ArrayList<>();
String branchListKey = buildBranchListKeyByXid(xid);
List<String> branchKeys = lRange(jedis, branchListKey);
if (CollectionUtils.isNotEmpty(branchKeys)) {
try (Pipeline pipeline = jedis.pipelined()) {
branchKeys.stream().forEach(branchKey -> pipeline.hgetAll(branchKey));
List<Object> branchInfos = pipeline.syncAndReturnAll();
for (Object branchInfo : branchInfos) {
if (branchInfo != null) {
Map<String, String> branchInfoMap = (Map<String, String>) branchInfo;
Optional<BranchTransactionDO> branchTransactionDO = Optional.ofNullable(
(BranchTransactionDO) BeanUtils.mapToObject(branchInfoMap, BranchTransactionDO.class));
branchTransactionDO.ifPresent(branchTransactionDOs::add);
}
}
}
}
if (CollectionUtils.isNotEmpty(branchTransactionDOs)) {
Collections.sort(branchTransactionDOs);
}
return branchTransactionDOs;
}
private List<String> lRange(Jedis jedis, String key) {
List<String> keys = new ArrayList<>();
List<String> values;
int limit = 20;
int start = 0;
int stop = limit;
for (; ; ) {
values = jedis.lrange(key, start, stop);
keys.addAll(values);
if (CollectionUtils.isEmpty(values) || values.size() < limit) {
break;
}
start = keys.size();
stop = start + limit;
}
return keys;
}
public List<BranchTransactionDO> findBranchSessionByXid(String xid) {
try (Jedis jedis = JedisPooledFactory.getJedisInstance()) {
return readBranchSessionByXid(jedis, xid);
}
}
/**
* query globalSession by page
*
* @param pageNum
* @param pageSize
* @param withBranchSessions
* @return List<GlobalSession>
*/
public List<GlobalSession> findGlobalSessionByPage(int pageNum, int pageSize, boolean withBranchSessions) {
List<GlobalSession> globalSessions = new ArrayList<>();
int start = Math.max((pageNum - 1) * pageSize, 0);
int end = pageNum * pageSize - 1;
List<String> statusKeys = convertStatusKeys(GlobalStatus.values());
Map<String, Integer> stringLongMap = calculateStatuskeysHasData(statusKeys);
List<List<String>> list = dogetXidsForTargetMap(stringLongMap, start, end, pageSize);
if (CollectionUtils.isNotEmpty(list)) {
List<String> xids = list.stream().flatMap(Collection::stream).collect(Collectors.toList());
xids.forEach(xid -> {
if (globalSessions.size() < pageSize) {
GlobalSession globalSession = this.readSession(xid, withBranchSessions);
if (globalSession != null) {
globalSessions.add(globalSession);
}
}
});
}
return globalSessions;
}
/**
* query and sort existing values
*
* @param statusKeys
* @return
*/
private Map<String, Integer> calculateStatuskeysHasData(List<String> statusKeys) {
Map<String, Integer> resultMap = new LinkedHashMap<>();
Map<String, Integer> keysMap = new HashMap<>(statusKeys.size());
try (Jedis jedis = JedisPooledFactory.getJedisInstance();
Pipeline pipelined = jedis.pipelined()) {
statusKeys.forEach(key -> pipelined.llen(key));
List<Long> counts = (List) pipelined.syncAndReturnAll();
for (int i = 0; i < counts.size(); i++) {
if (counts.get(i) > 0) {
keysMap.put(statusKeys.get(i), counts.get(i).intValue());
}
}
}
// sort
List<Map.Entry<String, Integer>> list = new ArrayList<>(keysMap.entrySet());
list.sort((o1, o2) -> o2.getValue() - o1.getValue());
list.forEach(e -> resultMap.put(e.getKey(), e.getValue()));
return resultMap;
}
/**
* count GlobalSession total by status
*
* @param values
* @return Long
*/
public Long countByGlobalSessions(GlobalStatus[] values) {
List<String> statusKeys = new ArrayList<>();
Long total = 0L;
for (GlobalStatus status : values) {
statusKeys.add(buildGlobalStatus(status.getCode()));
}
try (Jedis jedis = JedisPooledFactory.getJedisInstance();
Pipeline pipelined = jedis.pipelined()) {
statusKeys.stream().forEach(statusKey -> pipelined.llen(statusKey));
List<Long> list = (List<Long>) (List) pipelined.syncAndReturnAll();
if (list.size() > 0) {
total = list.stream().mapToLong(value -> value).sum();
}
return total;
}
}
private List<String> convertStatusKeys(GlobalStatus... statuses) {
List<String> statusKeys = new ArrayList<>();
for (int i = 0; i < statuses.length; i++) {
statusKeys.add(buildGlobalStatus(statuses[i].getCode()));
}
return statusKeys;
}
private void dogetXidsForTargetMapRecursive(
Map<String, Integer> targetMap, long start, long end, long queryCount, List<List<String>> listList) {
long total = listList.stream().mapToLong(List::size).sum();
if (total >= queryCount) {
return;
}
// when start greater than offset(totalCount)
if (start >= queryCount) {
return;
}
if (targetMap.size() == 0) {
return;
}
try (Jedis jedis = JedisPooledFactory.getJedisInstance()) {
Iterator<Map.Entry<String, Integer>> iterator = targetMap.entrySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next().getKey();
final long sum = listList.stream().mapToLong(List::size).sum();
final long diffCount = queryCount - sum;
if (diffCount <= 0) {
return;
}
List<String> list;
if (end - start >= diffCount) {
long endNew = start + diffCount - 1;
list = jedis.lrange(key, start, endNew);
} else {
list = jedis.lrange(key, start, end);
}
if (list.size() > 0) {
listList.add(list);
} else {
iterator.remove();
}
}
}
long startNew = end + 1;
long endNew = startNew + end - start;
dogetXidsForTargetMapRecursive(targetMap, startNew, endNew, queryCount, listList);
}
private List<List<String>> dogetXidsForTargetMap(
Map<String, Integer> targetMap, int start, int end, int totalCount) {
List<List<String>> listList = new ArrayList<>();
try (Jedis jedis = JedisPooledFactory.getJedisInstance()) {
for (String key : targetMap.keySet()) {
final List<String> list = jedis.lrange(key, start, end);
final long sum = listList.stream().mapToLong(List::size).sum();
if (list.size() > 0 && sum < totalCount) {
listList.add(list);
} else {
start = 0;
end = totalCount - 1;
}
}
}
return listList;
}
protected String buildBranchListKeyByXid(String xid) {
return REDIS_SEATA_BRANCHES_PREFIX + xid;
}
protected String buildGlobalKeyByTransactionId(Object transactionId) {
return REDIS_SEATA_GLOBAL_PREFIX + transactionId;
}
protected String buildBranchKey(Long branchId) {
return REDIS_SEATA_BRANCH_PREFIX + branchId;
}
protected String buildGlobalStatus(Integer status) {
return REDIS_SEATA_STATUS_PREFIX + status;
}
/**
* Sets log query limit.
*
* @param logQueryLimit the log query limit
*/
public void setLogQueryLimit(int logQueryLimit) {
this.logQueryLimit = logQueryLimit;
}
}
|
apache/uima-uimaj | 36,599 | uimafit-core/src/test/java/org/apache/uima/fit/util/JCasUtilv3Test.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.
getCoveredAnnotations() contains code adapted from the UIMA Subiterator class.
*/
package org.apache.uima.fit.util;
import static java.util.Arrays.asList;
import static org.apache.uima.fit.factory.TypeSystemDescriptionFactory.createTypeSystemDescription;
import static org.apache.uima.fit.util.JCasUtil.getAnnotationType;
import static org.apache.uima.fit.util.JCasUtil.getView;
import static org.apache.uima.fit.util.JCasUtil.indexCovered;
import static org.apache.uima.fit.util.JCasUtil.indexCovering;
import static org.apache.uima.fit.util.JCasUtil.select;
import static org.apache.uima.fit.util.JCasUtil.selectAt;
import static org.apache.uima.fit.util.JCasUtil.selectCovered;
import static org.apache.uima.fit.util.JCasUtil.selectSingleAt;
import static org.apache.uima.fit.util.JCasUtil.toText;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;
import org.apache.uima.UIMAException;
import org.apache.uima.cas.CAS;
import org.apache.uima.cas.CASRuntimeException;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.text.AnnotationFS;
import org.apache.uima.fit.ComponentTestBase;
import org.apache.uima.fit.type.AnalyzedText;
import org.apache.uima.fit.type.Sentence;
import org.apache.uima.fit.type.Token;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.cas.EmptyFSList;
import org.apache.uima.jcas.cas.FSArray;
import org.apache.uima.jcas.cas.NonEmptyFSList;
import org.apache.uima.jcas.cas.TOP;
import org.apache.uima.jcas.tcas.Annotation;
import org.apache.uima.util.CasCreationUtils;
import org.junit.jupiter.api.Test;
/**
* Test cases for {@link JCasUtil}.
*
*/
public class JCasUtilv3Test extends ComponentTestBase {
/**
* Test Tokens (Stems + Lemmas) overlapping with each other.
*/
@Test
public void testSelectCoveredOverlapping() {
add(jCas, 3, 16);
add(jCas, 37, 61);
add(jCas, 49, 75);
add(jCas, 54, 58);
add(jCas, 66, 84);
for (Token t : select(jCas, Token.class)) {
// The naive approach is assumed to be correct
// uimaFIT: selectCovered(jCas, Sentence.class, t.getBegin(), t.getEnd());
List<Sentence> stem1 = jCas.select(Sentence.class).coveredBy(t.getBegin(), t.getEnd())
.asList();
// uimaFIT: selectCovered(jCas, Sentence.class, t);
List<Sentence> stem2 = jCas.select(Sentence.class).coveredBy(t).asList();
check(jCas, t, stem1, stem2);
}
}
/**
* Test what happens if there is actually nothing overlapping with the Token.
*/
@Test
public void testSelectCoveredNoOverlap() {
new Sentence(jCas, 3, 31).addToIndexes();
new Sentence(jCas, 21, 21).addToIndexes();
new Sentence(jCas, 24, 44).addToIndexes();
new Sentence(jCas, 30, 45).addToIndexes();
new Sentence(jCas, 32, 43).addToIndexes();
new Sentence(jCas, 47, 61).addToIndexes();
new Sentence(jCas, 48, 77).addToIndexes();
new Sentence(jCas, 65, 82).addToIndexes();
new Sentence(jCas, 68, 80).addToIndexes();
new Sentence(jCas, 72, 65).addToIndexes();
new Token(jCas, 73, 96).addToIndexes();
for (Token t : select(jCas, Token.class)) {
// The naive approach is assumed to be correct
// uimaFIT: selectCovered(jCas, Sentence.class, t.getBegin(), t.getEnd());
List<Sentence> stem1 = jCas.select(Sentence.class).coveredBy(t.getBegin(), t.getEnd())
.asList();
// uimaFIT: selectCovered(jCas, Sentence.class, t);
List<Sentence> stem2 = jCas.select(Sentence.class).coveredBy(t).asList();
check(jCas, t, stem1, stem2);
}
}
@Test
public void testSelectCoverRandom() throws Exception {
final int ITERATIONS = 10;
for (int i = 0; i < ITERATIONS; i++) {
CAS cas = jCas.getCas();
initRandomCas(cas, 10 * i);
JCas jcas = cas.getJCas();
Collection<Sentence> sentences = select(jcas, Sentence.class);
long timeNaive = 0;
long timeOptimized = 0;
// Prepare the index
long timeIndexed = System.currentTimeMillis();
Map<Sentence, List<Token>> index = indexCovered(jcas, Sentence.class, Token.class);
timeIndexed = System.currentTimeMillis() - timeIndexed;
// -- The order of entries in the index is NOT defined!
// Check that order of indexed sentences corresponds to regular CAS-index order
// List<Sentence> relevantSentences = new ArrayList<>(sentences);
// relevantSentences.retainAll(index.keySet());
// assertEquals(relevantSentences, new ArrayList<>(index.keySet()));
for (Sentence t : sentences) {
long ti = System.currentTimeMillis();
// The naive approach is assumed to be correct
// uimaFIT: selectCovered(jcas, Token.class, t.getBegin(), t.getEnd());
List<Token> expected = jcas.select(Token.class).coveredBy(t.getBegin(), t.getEnd())
.asList();
timeNaive += System.currentTimeMillis() - ti;
// Record time for optimized selectCovered
ti = System.currentTimeMillis();
// uimaFIT: selectCovered(jcas, Token.class, t);
List<Token> actual1 = jcas.select(Token.class).coveredBy(t).asList();
timeOptimized += System.currentTimeMillis() - ti;
// Record index lookup time
ti = System.currentTimeMillis();
Collection<Token> actual2 = index.get(t);
timeIndexed += System.currentTimeMillis() - ti;
check(jcas, t, expected, actual1);
check(jcas, t, expected, actual2);
// System.out.printf("%n--- OK ---------------%n%n");
}
System.out.printf(
"%3d Optimized: speed up factor %3.2f [naive:%4d optimized:%4d (diff:%4d)]%n", i,
(double) timeNaive / (double) timeOptimized, timeNaive, timeOptimized,
timeNaive - timeOptimized);
System.out.printf(
"%3d Indexed: speed up factor %3.2f [naive:%4d indexed :%4d (diff:%4d)]%n%n", i,
(double) timeNaive / (double) timeIndexed, timeNaive, timeIndexed,
timeNaive - timeIndexed);
}
}
/**
* Test what happens if there is actually nothing overlapping with the Token.
*/
@Test
public void testSelectBetweenInclusion() {
Token t1 = new Token(jCas, 45, 57);
t1.addToIndexes();
Token t2 = new Token(jCas, 52, 52);
t2.addToIndexes();
new Sentence(jCas, 52, 52).addToIndexes();
// uimaFIT: selectBetween(jCas, Sentence.class, t1, t2);
List<Sentence> stem1 = jCas.select(Sentence.class).between(t1, t2).asList();
assertTrue(stem1.isEmpty());
}
@Test
public void testSelectBetweenRandom() throws Exception {
final int ITERATIONS = 10;
Random rnd = new Random();
for (int i = 1; i <= ITERATIONS; i++) {
CAS cas = jCas.getCas();
initRandomCas(cas, 10 * i);
JCas jcas = cas.getJCas();
List<Token> tokens = new ArrayList<Token>(select(jcas, Token.class));
long timeNaive = 0;
long timeOptimized = 0;
for (int j = 0; j < ITERATIONS; j++) {
Token t1 = tokens.get(rnd.nextInt(tokens.size()));
Token t2 = tokens.get(rnd.nextInt(tokens.size()));
int left = Math.min(t1.getEnd(), t2.getEnd());
int right = Math.max(t1.getBegin(), t2.getBegin());
long ti;
List<Sentence> reference;
if ((t1.getBegin() < t2.getBegin() && t2.getBegin() < t1.getEnd())
|| (t1.getBegin() < t2.getEnd() && t2.getEnd() < t1.getEnd())
|| (t2.getBegin() < t1.getBegin() && t1.getBegin() < t2.getEnd())
|| (t2.getBegin() < t1.getEnd() && t1.getEnd() < t2.getEnd())) {
// If the boundary annotations overlap, the result must be empty
ti = System.currentTimeMillis();
reference = new ArrayList<Sentence>();
timeNaive += System.currentTimeMillis() - ti;
} else {
ti = System.currentTimeMillis();
reference = selectCovered(jcas, Sentence.class, left, right);
timeNaive += System.currentTimeMillis() - ti;
}
ti = System.currentTimeMillis();
// uimaFIT: selectBetween(Sentence.class, t1, t2);
List<Sentence> actual = jcas.select(Sentence.class).between(t1, t2).asList();
timeOptimized += System.currentTimeMillis() - ti;
assertThat(actual) //
.as("Naive: Searching between " + t1 + " and " + t2) //
.isEqualTo(reference);
}
System.out.format("Speed up factor %.2f [naive:%d optimized:%d diff:%d]\n",
(double) timeNaive / (double) timeOptimized, timeNaive, timeOptimized,
timeNaive - timeOptimized);
}
}
/**
* Test Tokens (Stems + Lemmas) overlapping with each other.
*/
@Test
public void testSelectCoveringOverlapping() {
add(jCas, 3, 16);
add(jCas, 37, 61);
add(jCas, 49, 75);
add(jCas, 54, 58);
add(jCas, 66, 84);
// uimaFIT: selectCovering(jCas, Token.class, 36, 52).size()
assertEquals(0, jCas.select(Token.class).covering(36, 52).count());
// uimaFIT: selectCovering(jCas, Token.class, 37, 52).size()
assertEquals(1, jCas.select(Token.class).covering(37, 52).count());
// uimaFIT: selectCovering(jCas, Token.class, 49, 52).size()
assertEquals(2, jCas.select(Token.class).covering(49, 52).count());
}
private void initRandomCas(CAS cas, int size) {
Random rnd = new Random();
List<Type> types = new ArrayList<Type>();
types.add(cas.getTypeSystem().getType(Token.class.getName()));
types.add(cas.getTypeSystem().getType(Sentence.class.getName()));
// Shuffle the types
for (int n = 0; n < 10; n++) {
Type t = types.remove(rnd.nextInt(types.size()));
types.add(t);
}
// Randomly generate annotations
for (int n = 0; n < size; n++) {
for (Type t : types) {
int begin = rnd.nextInt(100);
int end = begin + rnd.nextInt(30);
cas.addFsToIndexes(cas.createAnnotation(t, begin, end));
}
}
}
@SuppressWarnings("unused")
private void print(Collection<? extends Annotation> annos) {
for (Annotation a : annos) {
System.out.println(a.getClass().getSimpleName() + " " + a.getBegin() + " " + a.getEnd());
}
}
private Token add(JCas jcas, int begin, int end) {
Token t = new Token(jcas, begin, end);
t.addToIndexes();
new Sentence(jcas, begin, end).addToIndexes();
return t;
}
private void check(JCas jcas, Annotation t, Collection<? extends Annotation> a1,
Collection<? extends Annotation> a2) {
// List<Annotation> annos = new ArrayList<Annotation>();
// FSIterator fs = jcas.getAnnotationIndex().iterator();
// while (fs.hasNext()) {
// annos.add((Annotation) fs.next());
// }
//
// System.out.println("--- Index");
// print(annos);
// System.out.println("--- Container");
// print(Collections.singleton(t));
// System.out.println("--- Naive");
// print(a1);
// System.out.println("--- Optimized");
// print(a2);
assertThat(a1) //
.as("Container: [" + t.getBegin() + ".." + t.getEnd() + "]") //
.isEqualTo(a2);
}
@Test
public void testIterator() throws Exception {
String text = "Rot wood cheeses dew?";
tokenBuilder.buildTokens(jCas, text);
assertEquals(asList("Rot", "wood", "cheeses", "dew?"),
// uimaFIT: toText(JCasUtil.select(jCas, Token.class))
jCas.select(Token.class).map(AnnotationFS::getCoveredText)
.collect(Collectors.toList()));
}
@Test
public void testSelectByIndex() {
String text = "Rot wood cheeses dew?";
tokenBuilder.buildTokens(jCas, text);
// uimaFIT: JCasUtil.selectByIndex(jCas, Token.class, -1).getCoveredText()
assertEquals("dew?", jCas.select(Token.class).backwards().get(0).getCoveredText());
// uimaFIT: JCasUtil.selectByIndex(jCas, Token.class, 3).getCoveredText()
assertEquals("dew?", jCas.select(Token.class).get(3).getCoveredText());
// uimaFIT: JCasUtil.selectByIndex(jCas, Token.class, 0).getCoveredText()
assertEquals("Rot", jCas.select(Token.class).get(0).getCoveredText());
// uimaFIT: JCasUtil.selectByIndex(jCas, Token.class, -4).getCoveredText()
assertEquals("Rot", jCas.select(Token.class).backwards().get(3).getCoveredText());
// uimaFIT: assertNull(JCasUtil.selectByIndex(jCas, Token.class, -5));
assertThatExceptionOfType(CASRuntimeException.class)
.isThrownBy(() -> jCas.select(Token.class).backwards().get(4))
.withMessage("CAS does not contain any '" + Token.class.getName()
+ "' instances shifted by: 4.");
// uimaFIT: assertNull(JCasUtil.selectByIndex(jCas, Token.class, 4));
assertThatExceptionOfType(CASRuntimeException.class)
.isThrownBy(() -> jCas.select(Token.class).backwards().get(4))
.withMessage("CAS does not contain any '" + Token.class.getName()
+ "' instances shifted by: 4.");
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testSelectOnArrays() throws Exception {
String text = "Rot wood cheeses dew?";
tokenBuilder.buildTokens(jCas, text);
Collection<TOP> allFS = select(jCas, TOP.class);
FSArray allFSArray = new FSArray(jCas, allFS.size());
int i = 0;
for (FeatureStructure fs : allFS) {
allFSArray.set(i, fs);
i++;
}
// Print what is expected
for (FeatureStructure fs : allFS) {
System.out.println("Type: " + fs.getType().getName() + "]");
}
System.out.println("Tokens: [" + toText(select(jCas, Token.class)) + "]");
// Document Annotation, one sentence and 4 tokens.
assertEquals(6, allFS.size());
// uimaFIT: toText(select(allFSArray, Token.class))
assertEquals(toText(select(jCas, Token.class)), toText(allFSArray.select(Token.class)));
assertEquals(toText((Iterable) jCas.select(Token.class)),
toText((Iterable) allFSArray.select(Token.class)));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testSelectOnLists() throws Exception {
String text = "Rot wood cheeses dew?";
tokenBuilder.buildTokens(jCas, text);
Collection<TOP> allFS = select(jCas, TOP.class);
// Building a list... OMG!
NonEmptyFSList allFSList = new NonEmptyFSList(jCas);
NonEmptyFSList head = allFSList;
Iterator<TOP> i = allFS.iterator();
while (i.hasNext()) {
head.setHead(i.next());
if (i.hasNext()) {
head.setTail(new NonEmptyFSList(jCas));
head = (NonEmptyFSList) head.getTail();
} else {
head.setTail(new EmptyFSList(jCas));
}
}
// Print what is expected
for (FeatureStructure fs : allFS) {
System.out.println("Type: " + fs.getType().getName() + "]");
}
System.out.println("Tokens: [" + toText(select(jCas, Token.class)) + "]");
// Document Annotation, one sentence and 4 tokens.
assertEquals(6, allFS.size());
// uimaFIT: toText(select(allFSArray, Token.class))
assertEquals(toText(select(jCas, Token.class)), toText(allFSList.select(Token.class)));
assertEquals(toText((Iterable) select(jCas, Token.class)),
toText((Iterable) select(allFSList, Token.class)));
}
@Test
public void testToText() {
String text = "Rot wood cheeses dew?";
tokenBuilder.buildTokens(jCas, text);
// uimaFIT: toText(select(allFSArray, Token.class))
assertEquals(asList(text.split(" ")), toText(jCas.select(Token.class)));
}
@Test
public void testSelectSingleRelative() {
String text = "one two three";
tokenBuilder.buildTokens(jCas, text);
List<Token> token = new ArrayList<Token>(select(jCas, Token.class));
// uimaFIT: selectSingleRelative(jCas, Token.class, token.get(1), -1)
Token preceding = jCas.select(Token.class).startAt(token.get(1)).get(-1);
assertEquals(token.get(0).getCoveredText(), preceding.getCoveredText());
// selectSingleRelative(jCas, Token.class, token.get(1), 1);
Token following = jCas.select(Token.class).startAt(token.get(1)).get(1);
assertEquals(token.get(2).getCoveredText(), following.getCoveredText());
}
@Test
public void testSingleRelativePreceedingDifferentType() {
String text = "one two three";
tokenBuilder.buildTokens(jCas, text);
List<Token> tokens = new ArrayList<Token>(select(jCas, Token.class));
for (Token token : tokens) {
new AnalyzedText(jCas, token.getBegin(), token.getEnd()).addToIndexes();
}
Token lastToken = tokens.get(tokens.size() - 1);
Token preLastToken = tokens.get(tokens.size() - 2);
// uimaFIT selectSingleRelative(jCas, AnalyzedText.class, lastToken, -1);
AnalyzedText a = jCas.select(AnalyzedText.class).startAt(lastToken).shifted(-1).get();
assertEquals(preLastToken.getBegin(), a.getBegin());
assertEquals(preLastToken.getEnd(), a.getEnd());
}
@Test
public void testSingleRelativeFollowingDifferentType() {
String text = "one two three";
tokenBuilder.buildTokens(jCas, text);
List<Token> tokens = new ArrayList<Token>(select(jCas, Token.class));
for (Token token : tokens) {
new AnalyzedText(jCas, token.getBegin(), token.getEnd()).addToIndexes();
}
Token firstToken = tokens.get(0);
Token secondToken = tokens.get(1);
// uimaFIT:
// AnalyzedText a = selectSingleRelative(jCas, AnalyzedText.class, firstToken, 1);
AnalyzedText a = jCas.select(AnalyzedText.class).startAt(firstToken).get(1);
assertEquals(secondToken.getBegin(), a.getBegin());
assertEquals(secondToken.getEnd(), a.getEnd());
}
// Actually, in UIMAv3 this does not fail - and it is ok to not fail
@Deprecated()
@Test
public void testSingleRelativeDifferentTypeSamePositionFail() {
String text = "one two three";
tokenBuilder.buildTokens(jCas, text);
List<Token> tokens = new ArrayList<Token>(select(jCas, Token.class));
for (Token token : tokens) {
new AnalyzedText(jCas, token.getBegin(), token.getEnd()).addToIndexes();
}
Token firstToken = tokens.get(0);
// uimaFIT:
// assertThatExceptionOfType(IllegalArgumentException.class)
// .isThrownBy(() -> selectSingleRelative(jCas, AnalyzedText.class, firstToken, 0));
assertThat(jCas.select(AnalyzedText.class).startAt(firstToken).shifted(0).get())
.isSameAs(jCas.select(AnalyzedText.class).get());
}
@Test
public void testSingleRelativeSameTypeSamePositionOk() {
String text = "one two three";
tokenBuilder.buildTokens(jCas, text);
List<Token> tokens = new ArrayList<Token>(select(jCas, Token.class));
for (Token token : tokens) {
new AnalyzedText(jCas, token.getBegin(), token.getEnd()).addToIndexes();
}
Token firstToken = tokens.get(0);
// uimaFIT: selectSingleRelative(jCas, Token.class, firstToken, 0);
assertEquals(firstToken, jCas.select(Token.class).startAt(firstToken).shifted(0).get());
}
@Test
public void testSelectFollowing() {
String text = "one two three";
tokenBuilder.buildTokens(jCas, text);
List<Token> token = new ArrayList<Token>(select(jCas, Token.class));
// uimaFIT: selectFollowing(jCas, Token.class, token.get(1), 1).get(0).getCoveredText())
assertEquals(token.get(2).getCoveredText(),
jCas.select(Token.class).following(token.get(1)).get().getCoveredText());
}
@Test
public void testSelectPreceding() {
String text = "one two three";
tokenBuilder.buildTokens(jCas, text);
List<Token> token = new ArrayList<Token>(select(jCas, Token.class));
// uimaFIT: selectPreceding(jCas, Token.class, token.get(1), 1).get(0).getCoveredText());
assertEquals(token.get(0).getCoveredText(),
jCas.select(Token.class).preceding(token.get(1)).get().getCoveredText());
}
@Test
public void testSelectPrecedingWithOverlaps() {
String text = "a b c d e";
tokenBuilder.buildTokens(jCas, text);
new Token(jCas, 2, 7).addToIndexes();
Token c = JCasUtil.selectAt(jCas, Token.class, 4, 5).get(0);
// uimaFIT: selectPreceding(jCas, Token.class, c, 2);
List<Token> preceedingTokens = jCas.select(Token.class).preceding(c).limit(2).asList();
assertEquals(2, preceedingTokens.size());
assertEquals("b", preceedingTokens.get(1).getCoveredText());
assertEquals("a", preceedingTokens.get(0).getCoveredText());
}
@Test
public void testSelectPrecedingWithOverlaps2() {
jCas.setDocumentText("abcde");
new Token(jCas, 0, 1).addToIndexes();
new Token(jCas, 1, 2).addToIndexes();
new Token(jCas, 2, 3).addToIndexes();
new Token(jCas, 3, 4).addToIndexes();
new Token(jCas, 4, 5).addToIndexes();
new Token(jCas, 1, 3).addToIndexes();
Token c = JCasUtil.selectAt(jCas, Token.class, 2, 3).get(0);
// selectPreceding(jCas, Token.class, c, 2);
List<Token> preceedingTokens = jCas.select(Token.class).preceding(c).limit(2).asList();
assertEquals(2, preceedingTokens.size());
assertEquals("b", preceedingTokens.get(1).getCoveredText());
assertEquals("a", preceedingTokens.get(0).getCoveredText());
}
@Test
public void testPrecedingDifferentType() {
String text = "one two three";
tokenBuilder.buildTokens(jCas, text);
List<Token> tokens = new ArrayList<Token>(select(jCas, Token.class));
for (Token token : tokens) {
new AnalyzedText(jCas, token.getBegin(), token.getEnd()).addToIndexes();
}
Token lastToken = tokens.get(tokens.size() - 1);
Token preLastToken = tokens.get(tokens.size() - 2);
// selectPreceding(jCas, AnalyzedText.class, lastToken, 1).get(0);
AnalyzedText a = jCas.select(AnalyzedText.class).preceding(lastToken).limit(1).get();
assertEquals(preLastToken.getBegin(), a.getBegin());
assertEquals(preLastToken.getEnd(), a.getEnd());
}
@Test
public void testFollowingDifferentType() {
String text = "one two three";
tokenBuilder.buildTokens(jCas, text);
List<Token> tokens = new ArrayList<Token>(select(jCas, Token.class));
for (Token token : tokens) {
new AnalyzedText(jCas, token.getBegin(), token.getEnd()).addToIndexes();
}
Token firstToken = tokens.get(0);
Token secondToken = tokens.get(1);
// selectFollowing(jCas, AnalyzedText.class, firstToken, 1).get(0);
AnalyzedText a = jCas.select(AnalyzedText.class).following(firstToken).get();
assertEquals(secondToken.getBegin(), a.getBegin());
assertEquals(secondToken.getEnd(), a.getEnd());
}
@Test
public void testSelectFollowingPrecedingBuiltinTypes() {
this.jCas.setDocumentText("A B C");
// remove the DocumentAnnotation
for (Annotation ann : JCasUtil.select(jCas, Annotation.class)) {
ann.removeFromIndexes();
}
Annotation a = new Annotation(this.jCas, 0, 1);
Annotation b = new Annotation(this.jCas, 2, 3);
Annotation c = new Annotation(this.jCas, 4, 5);
for (Annotation ann : Arrays.asList(a, b, c)) {
ann.addToIndexes();
}
// uimaFIT: selectPreceding(this.jCas, Annotation.class, b, 2));
assertEquals(Arrays.asList(a), jCas.select(Annotation.class).preceding(b).limit(2).asList());
// uimaFIT: Arrays.asList(a, b), selectPreceding(this.jCas, Annotation.class, c, 2));
// Produces the wrong order
assertEquals(Arrays.asList(a, b), jCas.select(Annotation.class).preceding(c).limit(2).asList());
// uimaFIT: Arrays.asList(b, c), selectFollowing(this.jCas, Annotation.class, a, 2));
assertEquals(Arrays.asList(b, c), jCas.select(Annotation.class).following(a).limit(2).asList());
// uimaFIT: Arrays.asList(c), selectFollowing(this.jCas, Annotation.class, b, 2));
assertEquals(Arrays.asList(c), jCas.select(Annotation.class).following(b).limit(2).asList());
}
@Test
public void testSelectFollowingPrecedingDifferentTypes() {
this.jCas.setDocumentText("A B C D E");
Token a = new Token(this.jCas, 0, 1);
Token b = new Token(this.jCas, 2, 3);
Token c = new Token(this.jCas, 4, 5);
Token d = new Token(this.jCas, 6, 7);
Token e = new Token(this.jCas, 8, 9);
for (Token token : Arrays.asList(a, b, c, d, e)) {
token.addToIndexes();
}
Sentence sentence = new Sentence(this.jCas, 2, 5);
sentence.addToIndexes();
// uimaFIT: selectPreceding(this.jCas, Token.class, sentence, 1)
List<Token> preceding = jCas.select(Token.class).preceding(sentence).limit(1).asList();
assertEquals(Arrays.asList("A"), JCasUtil.toText(preceding));
assertEquals(Arrays.asList(a), preceding);
// uimaFIT: selectPreceding(this.jCas, Token.class, sentence, 2)
preceding = jCas.select(Token.class).preceding(sentence).limit(2).asList();
assertEquals(Arrays.asList("A"), JCasUtil.toText(preceding));
assertEquals(Arrays.asList(a), preceding);
// uimaFIT: selectFollowing(this.jCas, Token.class, sentence, 1);
List<Token> following1 = jCas.select(Token.class).following(sentence).limit(1).asList();
assertEquals(Arrays.asList("D"), JCasUtil.toText(following1));
assertEquals(Arrays.asList(d), following1);
// uimaFIT: selectFollowing(this.jCas, Token.class, sentence, 2);
List<Token> following2 = jCas.select(Token.class).following(sentence).limit(2).asList();
assertEquals(Arrays.asList("D", "E"), JCasUtil.toText(following2));
assertEquals(Arrays.asList(d, e), following2);
// uimaFIT: selectFollowing(this.jCas, Token.class, sentence, 3);
List<Token> following3 = jCas.select(Token.class).following(sentence).limit(3).asList();
assertEquals(Arrays.asList("D", "E"), JCasUtil.toText(following3));
assertEquals(Arrays.asList(d, e), following3);
}
@Test
public void testSelectFollowingPrecedingDifferentTypesMatchingSpansReversePriorities() {
this.jCas.setDocumentText("A B C D E");
Sentence a = new Sentence(this.jCas, 0, 1);
Sentence b = new Sentence(this.jCas, 2, 3);
Sentence c = new Sentence(this.jCas, 4, 5);
Sentence d = new Sentence(this.jCas, 6, 7);
Sentence e = new Sentence(this.jCas, 8, 9);
for (Sentence sentence : Arrays.asList(a, b, c, d, e)) {
sentence.addToIndexes();
}
AnalyzedText text = new AnalyzedText(this.jCas, 2, 3);
text.addToIndexes();
// uimaFIT: selectPreceding(this.jCas, Sentence.class, text, 1);
List<Sentence> preceding = jCas.select(Sentence.class).preceding(text).limit(1).asList();
assertEquals(Arrays.asList("A"), JCasUtil.toText(preceding));
assertEquals(Arrays.asList(a), preceding);
// uimaFIT: selectPreceding(this.jCas, Sentence.class, text, 2);
preceding = jCas.select(Sentence.class).preceding(text).limit(2).asList();
assertEquals(Arrays.asList("A"), JCasUtil.toText(preceding));
assertEquals(Arrays.asList(a), preceding);
// uimaFIT: selectFollowing(this.jCas, Sentence.class, text, 1);
List<Sentence> following = jCas.select(Sentence.class).following(text).limit(1).asList();
assertEquals(Arrays.asList("C"), JCasUtil.toText(following));
assertEquals(Arrays.asList(c), following);
// uimaFIT: selectFollowing(this.jCas, Sentence.class, text, 2);
following = jCas.select(Sentence.class).following(text).limit(2).asList();
assertEquals(Arrays.asList("C", "D"), JCasUtil.toText(following));
assertEquals(Arrays.asList(c, d), following);
}
@Test
public void testExists() throws UIMAException {
JCas jcas = CasCreationUtils.createCas(createTypeSystemDescription(), null, null).getJCas();
// uimaFIT: exists(jcas, Token.class)
assertFalse(jcas.select(Token.class).findAny().isPresent());
new Token(jcas, 0, 1).addToIndexes();
// uimaFIT: exists(jcas, Token.class)
assertTrue(jcas.select(Token.class).findAny().isPresent());
}
@Test
public void testSelectSingle() throws UIMAException {
JCas jcas = CasCreationUtils.createCas(createTypeSystemDescription(), null, null).getJCas();
// uimaFIT:
// assertThatExceptionOfType(IllegalArgumentException.class)
// .isThrownBy(() -> selectSingle(jcas, Token.class));
assertThatExceptionOfType(CASRuntimeException.class)
.isThrownBy(() -> jcas.select(Token.class).single());
new Token(jcas, 0, 1).addToIndexes();
// uimaFIT: selectSingle(jcas, Token.class);
jcas.select(Token.class).single();
new Token(jcas, 1, 2).addToIndexes();
// uimaFIT:
// assertThatExceptionOfType(IllegalArgumentException.class)
// .isThrownBy(() -> selectSingle(jcas, Token.class))
// .as("selectSingle must fail if there is more than one annotation of the type");
assertThatExceptionOfType(CASRuntimeException.class)
.isThrownBy(() -> jcas.select(Token.class).single())
.as("selectSingle must fail if there is more than one annotation of the type");
}
@Test
public void testSelectIsCovered() {
String text = "Will you come home today ? \n No , tomorrow !";
tokenBuilder.buildTokens(jCas, text);
List<Sentence> sentences = new ArrayList<Sentence>(select(jCas, Sentence.class));
List<Token> tokens = new ArrayList<Token>(select(jCas, Token.class));
// uimaFIT: selectCovered(Token.class, sentences.get(0)).size()
assertEquals(6, jCas.select(Token.class).coveredBy(sentences.get(0)).count());
// uimaFIT: selectCovered(Token.class, sentences.get(1)).size()
assertEquals(4, jCas.select(Token.class).coveredBy(sentences.get(1)).count());
// uimaFIT: contains(jCas, sentences.get(0), Token.class)
assertTrue(jCas.select(Token.class).coveredBy(sentences.get(0)).findAny().isPresent());
tokens.get(0).removeFromIndexes();
tokens.get(1).removeFromIndexes();
tokens.get(2).removeFromIndexes();
tokens.get(3).removeFromIndexes();
tokens.get(4).removeFromIndexes();
tokens.get(5).removeFromIndexes();
// uimaFIT: contains(jCas, sentences.get(0), Token.class)
assertFalse(jCas.select(Token.class).coveredBy(sentences.get(0)).findAny().isPresent());
}
@Test
public void testGetInternalUimaType() {
// uimaFIT: getType(jCas, Annotation.class);
Type t = jCas.getCasType(Annotation.class);
assertNotNull(t);
}
@Test
public void testGetView() throws Exception {
JCas jcas = CasCreationUtils.createCas(createTypeSystemDescription(), null, null).getJCas();
assertNull(getView(jcas, "view1", null));
assertNotNull(getView(jcas, "view1", true));
assertNotNull(getView(jcas, "view1", null));
}
@Test
public void testGetNonExistingView() throws Exception {
JCas jcas = CasCreationUtils.createCas(createTypeSystemDescription(), null, null).getJCas();
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> getView(jcas, "view1", false));
}
@Test
public void testGetType() {
String text = "Rot wood cheeses dew?";
tokenBuilder.buildTokens(jCas, text);
// uimaFIT: getType(jCas, Token.class).getName());
assertEquals(Token.class.getName(), jCas.getCasType(Token.class).getName());
// uimaFIT: getAnnotationType(jCas, Token.class).getName());
assertEquals(Token.class.getName(), jCas.getCasType(Token.class).getName());
// uimaFIT: getType(jCas, TOP.class).getName());
assertEquals("uima.cas.TOP", jCas.getCasType(TOP.class).getName());
// uimaFIT: getType(jCas, Annotation.class).getName());
assertEquals("uima.tcas.Annotation", jCas.getCasType(Annotation.class).getName());
// uimaFIT: getAnnotationType(jCas, Annotation.class).getName());
assertEquals("uima.tcas.Annotation", jCas.getCasType(Annotation.class).getName());
}
@Test
public void testGetNonAnnotationType() {
String text = "Rot wood cheeses dew?";
tokenBuilder.buildTokens(jCas, text);
// There is no alternative in UIMA v3
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> getAnnotationType(jCas, TOP.class));
}
@Test
public void testIndexCovering() throws Exception {
String text = "Will you come home today ? \n No , tomorrow !";
tokenBuilder.buildTokens(jCas, text);
List<Sentence> sentences = new ArrayList<Sentence>(select(jCas, Sentence.class));
List<Token> tokens = new ArrayList<Token>(select(jCas, Token.class));
Map<Token, List<Sentence>> index = indexCovering(jCas, Token.class, Sentence.class);
// Check covering annotations are found
assertEquals(asList(sentences.get(0)), index.get(tokens.get(0)));
assertEquals(asList(sentences.get(1)), index.get(tokens.get(tokens.size() - 1)));
// Check sentence 0 contains first token
assertTrue(index.get(tokens.get(0)).contains(sentences.get(0)));
// Check sentence 0 does not contain last token.
assertFalse(index.get(tokens.get(tokens.size() - 1)).contains(sentences.get(0)));
// Check the first token is contained in any sentence
assertTrue(!index.get(tokens.get(0)).isEmpty());
// After removing the annotation the index has to be rebuilt.
sentences.get(0).removeFromIndexes();
index = indexCovering(jCas, Token.class, Sentence.class);
// Check the first token is not contained in any sentence
assertFalse(!index.get(tokens.get(0)).isEmpty());
}
@Test
public void testSelectAt() throws Exception {
this.jCas.setDocumentText("A B C D E");
Token a = new Token(this.jCas, 0, 1);
Token b = new Token(this.jCas, 2, 3);
Token bc = new Token(this.jCas, 2, 5);
Token c = new Token(this.jCas, 4, 5);
Token c1 = new Token(this.jCas, 4, 5);
Token d = new Token(this.jCas, 4, 7);
Token cd = new Token(this.jCas, 6, 7);
Token e = new Token(this.jCas, 8, 9);
for (Token token : Arrays.asList(a, b, bc, c, c1, d, cd, e)) {
token.addToIndexes();
}
List<Token> tokensAt = selectAt(jCas, Token.class, c.getBegin(), c.getEnd());
assertEquals(2, tokensAt.size());
assertEquals(c.getBegin(), tokensAt.get(0).getBegin());
assertEquals(c.getEnd(), tokensAt.get(0).getEnd());
assertEquals(c.getBegin(), tokensAt.get(1).getBegin());
assertEquals(c.getEnd(), tokensAt.get(1).getEnd());
}
@Test
public void testSelectSingleAt() throws Exception {
this.jCas.setDocumentText("A B C D E");
Token a = new Token(this.jCas, 0, 1);
Token b = new Token(this.jCas, 2, 3);
Token bc = new Token(this.jCas, 2, 5);
Token c = new Token(this.jCas, 4, 5);
Token c1 = new Token(this.jCas, 4, 5);
Token d = new Token(this.jCas, 4, 7);
Token cd = new Token(this.jCas, 6, 7);
Token e = new Token(this.jCas, 8, 9);
for (Token token : Arrays.asList(a, b, bc, c, c1, d, cd, e)) {
token.addToIndexes();
}
try {
selectSingleAt(jCas, Token.class, c.getBegin(), c.getEnd());
fail("Expected exception not thrown");
} catch (IllegalArgumentException ex) {
// Ignore.
}
try {
selectSingleAt(jCas, Token.class, 1, 4);
fail("Expected exception not thrown");
} catch (IllegalArgumentException ex) {
// Ignore.
}
Token tokenAt = selectSingleAt(jCas, Token.class, b.getBegin(), b.getEnd());
assertEquals(b.getBegin(), tokenAt.getBegin());
assertEquals(b.getEnd(), tokenAt.getEnd());
}
}
|
googleapis/google-cloud-java | 36,471 | java-securitycenter/proto-google-cloud-securitycenter-v1beta1/src/main/java/com/google/cloud/securitycenter/v1beta1/ListSourcesResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/securitycenter/v1beta1/securitycenter_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.securitycenter.v1beta1;
/**
*
*
* <pre>
* Response message for listing sources.
* </pre>
*
* Protobuf type {@code google.cloud.securitycenter.v1beta1.ListSourcesResponse}
*/
public final class ListSourcesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.securitycenter.v1beta1.ListSourcesResponse)
ListSourcesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListSourcesResponse.newBuilder() to construct.
private ListSourcesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListSourcesResponse() {
sources_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListSourcesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securitycenter.v1beta1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1beta1_ListSourcesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securitycenter.v1beta1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1beta1_ListSourcesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securitycenter.v1beta1.ListSourcesResponse.class,
com.google.cloud.securitycenter.v1beta1.ListSourcesResponse.Builder.class);
}
public static final int SOURCES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.securitycenter.v1beta1.Source> sources_;
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.securitycenter.v1beta1.Source> getSourcesList() {
return sources_;
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.securitycenter.v1beta1.SourceOrBuilder>
getSourcesOrBuilderList() {
return sources_;
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
@java.lang.Override
public int getSourcesCount() {
return sources_.size();
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
@java.lang.Override
public com.google.cloud.securitycenter.v1beta1.Source getSources(int index) {
return sources_.get(index);
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
@java.lang.Override
public com.google.cloud.securitycenter.v1beta1.SourceOrBuilder getSourcesOrBuilder(int index) {
return sources_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* results.
* </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 < sources_.size(); i++) {
output.writeMessage(1, sources_.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 < sources_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, sources_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.securitycenter.v1beta1.ListSourcesResponse)) {
return super.equals(obj);
}
com.google.cloud.securitycenter.v1beta1.ListSourcesResponse other =
(com.google.cloud.securitycenter.v1beta1.ListSourcesResponse) obj;
if (!getSourcesList().equals(other.getSourcesList())) 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 (getSourcesCount() > 0) {
hash = (37 * hash) + SOURCES_FIELD_NUMBER;
hash = (53 * hash) + getSourcesList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.securitycenter.v1beta1.ListSourcesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycenter.v1beta1.ListSourcesResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1beta1.ListSourcesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycenter.v1beta1.ListSourcesResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1beta1.ListSourcesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycenter.v1beta1.ListSourcesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1beta1.ListSourcesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.securitycenter.v1beta1.ListSourcesResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1beta1.ListSourcesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.securitycenter.v1beta1.ListSourcesResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1beta1.ListSourcesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.securitycenter.v1beta1.ListSourcesResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.securitycenter.v1beta1.ListSourcesResponse 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 sources.
* </pre>
*
* Protobuf type {@code google.cloud.securitycenter.v1beta1.ListSourcesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.securitycenter.v1beta1.ListSourcesResponse)
com.google.cloud.securitycenter.v1beta1.ListSourcesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securitycenter.v1beta1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1beta1_ListSourcesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securitycenter.v1beta1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1beta1_ListSourcesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securitycenter.v1beta1.ListSourcesResponse.class,
com.google.cloud.securitycenter.v1beta1.ListSourcesResponse.Builder.class);
}
// Construct using com.google.cloud.securitycenter.v1beta1.ListSourcesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (sourcesBuilder_ == null) {
sources_ = java.util.Collections.emptyList();
} else {
sources_ = null;
sourcesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.securitycenter.v1beta1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1beta1_ListSourcesResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.securitycenter.v1beta1.ListSourcesResponse getDefaultInstanceForType() {
return com.google.cloud.securitycenter.v1beta1.ListSourcesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.securitycenter.v1beta1.ListSourcesResponse build() {
com.google.cloud.securitycenter.v1beta1.ListSourcesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.securitycenter.v1beta1.ListSourcesResponse buildPartial() {
com.google.cloud.securitycenter.v1beta1.ListSourcesResponse result =
new com.google.cloud.securitycenter.v1beta1.ListSourcesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.securitycenter.v1beta1.ListSourcesResponse result) {
if (sourcesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
sources_ = java.util.Collections.unmodifiableList(sources_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.sources_ = sources_;
} else {
result.sources_ = sourcesBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.securitycenter.v1beta1.ListSourcesResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.securitycenter.v1beta1.ListSourcesResponse) {
return mergeFrom((com.google.cloud.securitycenter.v1beta1.ListSourcesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.securitycenter.v1beta1.ListSourcesResponse other) {
if (other == com.google.cloud.securitycenter.v1beta1.ListSourcesResponse.getDefaultInstance())
return this;
if (sourcesBuilder_ == null) {
if (!other.sources_.isEmpty()) {
if (sources_.isEmpty()) {
sources_ = other.sources_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureSourcesIsMutable();
sources_.addAll(other.sources_);
}
onChanged();
}
} else {
if (!other.sources_.isEmpty()) {
if (sourcesBuilder_.isEmpty()) {
sourcesBuilder_.dispose();
sourcesBuilder_ = null;
sources_ = other.sources_;
bitField0_ = (bitField0_ & ~0x00000001);
sourcesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getSourcesFieldBuilder()
: null;
} else {
sourcesBuilder_.addAllMessages(other.sources_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.securitycenter.v1beta1.Source m =
input.readMessage(
com.google.cloud.securitycenter.v1beta1.Source.parser(), extensionRegistry);
if (sourcesBuilder_ == null) {
ensureSourcesIsMutable();
sources_.add(m);
} else {
sourcesBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.securitycenter.v1beta1.Source> sources_ =
java.util.Collections.emptyList();
private void ensureSourcesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
sources_ =
new java.util.ArrayList<com.google.cloud.securitycenter.v1beta1.Source>(sources_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.securitycenter.v1beta1.Source,
com.google.cloud.securitycenter.v1beta1.Source.Builder,
com.google.cloud.securitycenter.v1beta1.SourceOrBuilder>
sourcesBuilder_;
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public java.util.List<com.google.cloud.securitycenter.v1beta1.Source> getSourcesList() {
if (sourcesBuilder_ == null) {
return java.util.Collections.unmodifiableList(sources_);
} else {
return sourcesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public int getSourcesCount() {
if (sourcesBuilder_ == null) {
return sources_.size();
} else {
return sourcesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public com.google.cloud.securitycenter.v1beta1.Source getSources(int index) {
if (sourcesBuilder_ == null) {
return sources_.get(index);
} else {
return sourcesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public Builder setSources(int index, com.google.cloud.securitycenter.v1beta1.Source value) {
if (sourcesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSourcesIsMutable();
sources_.set(index, value);
onChanged();
} else {
sourcesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public Builder setSources(
int index, com.google.cloud.securitycenter.v1beta1.Source.Builder builderForValue) {
if (sourcesBuilder_ == null) {
ensureSourcesIsMutable();
sources_.set(index, builderForValue.build());
onChanged();
} else {
sourcesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public Builder addSources(com.google.cloud.securitycenter.v1beta1.Source value) {
if (sourcesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSourcesIsMutable();
sources_.add(value);
onChanged();
} else {
sourcesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public Builder addSources(int index, com.google.cloud.securitycenter.v1beta1.Source value) {
if (sourcesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSourcesIsMutable();
sources_.add(index, value);
onChanged();
} else {
sourcesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public Builder addSources(
com.google.cloud.securitycenter.v1beta1.Source.Builder builderForValue) {
if (sourcesBuilder_ == null) {
ensureSourcesIsMutable();
sources_.add(builderForValue.build());
onChanged();
} else {
sourcesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public Builder addSources(
int index, com.google.cloud.securitycenter.v1beta1.Source.Builder builderForValue) {
if (sourcesBuilder_ == null) {
ensureSourcesIsMutable();
sources_.add(index, builderForValue.build());
onChanged();
} else {
sourcesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public Builder addAllSources(
java.lang.Iterable<? extends com.google.cloud.securitycenter.v1beta1.Source> values) {
if (sourcesBuilder_ == null) {
ensureSourcesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, sources_);
onChanged();
} else {
sourcesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public Builder clearSources() {
if (sourcesBuilder_ == null) {
sources_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
sourcesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public Builder removeSources(int index) {
if (sourcesBuilder_ == null) {
ensureSourcesIsMutable();
sources_.remove(index);
onChanged();
} else {
sourcesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public com.google.cloud.securitycenter.v1beta1.Source.Builder getSourcesBuilder(int index) {
return getSourcesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public com.google.cloud.securitycenter.v1beta1.SourceOrBuilder getSourcesOrBuilder(int index) {
if (sourcesBuilder_ == null) {
return sources_.get(index);
} else {
return sourcesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public java.util.List<? extends com.google.cloud.securitycenter.v1beta1.SourceOrBuilder>
getSourcesOrBuilderList() {
if (sourcesBuilder_ != null) {
return sourcesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(sources_);
}
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public com.google.cloud.securitycenter.v1beta1.Source.Builder addSourcesBuilder() {
return getSourcesFieldBuilder()
.addBuilder(com.google.cloud.securitycenter.v1beta1.Source.getDefaultInstance());
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public com.google.cloud.securitycenter.v1beta1.Source.Builder addSourcesBuilder(int index) {
return getSourcesFieldBuilder()
.addBuilder(index, com.google.cloud.securitycenter.v1beta1.Source.getDefaultInstance());
}
/**
*
*
* <pre>
* Sources belonging to the requested parent.
* </pre>
*
* <code>repeated .google.cloud.securitycenter.v1beta1.Source sources = 1;</code>
*/
public java.util.List<com.google.cloud.securitycenter.v1beta1.Source.Builder>
getSourcesBuilderList() {
return getSourcesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.securitycenter.v1beta1.Source,
com.google.cloud.securitycenter.v1beta1.Source.Builder,
com.google.cloud.securitycenter.v1beta1.SourceOrBuilder>
getSourcesFieldBuilder() {
if (sourcesBuilder_ == null) {
sourcesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.securitycenter.v1beta1.Source,
com.google.cloud.securitycenter.v1beta1.Source.Builder,
com.google.cloud.securitycenter.v1beta1.SourceOrBuilder>(
sources_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
sources_ = null;
}
return sourcesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no more
* 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>
* Token to retrieve the next page of results, or empty if there are no more
* 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>
* Token to retrieve the next page of results, or empty if there are no more
* 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>
* Token to retrieve the next page of results, or empty if there are no more
* 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>
* Token to retrieve the next page of results, or empty if there are no more
* results.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.securitycenter.v1beta1.ListSourcesResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.ListSourcesResponse)
private static final com.google.cloud.securitycenter.v1beta1.ListSourcesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.securitycenter.v1beta1.ListSourcesResponse();
}
public static com.google.cloud.securitycenter.v1beta1.ListSourcesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListSourcesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListSourcesResponse>() {
@java.lang.Override
public ListSourcesResponse 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<ListSourcesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListSourcesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.securitycenter.v1beta1.ListSourcesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,479 | java-biglake/proto-google-cloud-biglake-v1alpha1/src/main/java/com/google/cloud/bigquery/biglake/v1alpha1/ListLocksResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/bigquery/biglake/v1alpha1/metastore.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.bigquery.biglake.v1alpha1;
/**
*
*
* <pre>
* Response message for the ListLocks method.
* </pre>
*
* Protobuf type {@code google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse}
*/
public final class ListLocksResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse)
ListLocksResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListLocksResponse.newBuilder() to construct.
private ListLocksResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListLocksResponse() {
locks_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListLocksResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.bigquery.biglake.v1alpha1.MetastoreProto
.internal_static_google_cloud_bigquery_biglake_v1alpha1_ListLocksResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.bigquery.biglake.v1alpha1.MetastoreProto
.internal_static_google_cloud_bigquery_biglake_v1alpha1_ListLocksResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse.class,
com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse.Builder.class);
}
public static final int LOCKS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.bigquery.biglake.v1alpha1.Lock> locks_;
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.bigquery.biglake.v1alpha1.Lock> getLocksList() {
return locks_;
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.bigquery.biglake.v1alpha1.LockOrBuilder>
getLocksOrBuilderList() {
return locks_;
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
@java.lang.Override
public int getLocksCount() {
return locks_.size();
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
@java.lang.Override
public com.google.cloud.bigquery.biglake.v1alpha1.Lock getLocks(int index) {
return locks_.get(index);
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
@java.lang.Override
public com.google.cloud.bigquery.biglake.v1alpha1.LockOrBuilder getLocksOrBuilder(int index) {
return locks_.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 < locks_.size(); i++) {
output.writeMessage(1, locks_.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 < locks_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, locks_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse)) {
return super.equals(obj);
}
com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse other =
(com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse) obj;
if (!getLocksList().equals(other.getLocksList())) 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 (getLocksCount() > 0) {
hash = (37 * hash) + LOCKS_FIELD_NUMBER;
hash = (53 * hash) + getLocksList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse 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 ListLocks method.
* </pre>
*
* Protobuf type {@code google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse)
com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.bigquery.biglake.v1alpha1.MetastoreProto
.internal_static_google_cloud_bigquery_biglake_v1alpha1_ListLocksResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.bigquery.biglake.v1alpha1.MetastoreProto
.internal_static_google_cloud_bigquery_biglake_v1alpha1_ListLocksResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse.class,
com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse.Builder.class);
}
// Construct using com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (locksBuilder_ == null) {
locks_ = java.util.Collections.emptyList();
} else {
locks_ = null;
locksBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.bigquery.biglake.v1alpha1.MetastoreProto
.internal_static_google_cloud_bigquery_biglake_v1alpha1_ListLocksResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse
getDefaultInstanceForType() {
return com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse build() {
com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse buildPartial() {
com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse result =
new com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse result) {
if (locksBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
locks_ = java.util.Collections.unmodifiableList(locks_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.locks_ = locks_;
} else {
result.locks_ = locksBuilder_.build();
}
}
private void buildPartial0(
com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse) {
return mergeFrom((com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse other) {
if (other
== com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse.getDefaultInstance())
return this;
if (locksBuilder_ == null) {
if (!other.locks_.isEmpty()) {
if (locks_.isEmpty()) {
locks_ = other.locks_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureLocksIsMutable();
locks_.addAll(other.locks_);
}
onChanged();
}
} else {
if (!other.locks_.isEmpty()) {
if (locksBuilder_.isEmpty()) {
locksBuilder_.dispose();
locksBuilder_ = null;
locks_ = other.locks_;
bitField0_ = (bitField0_ & ~0x00000001);
locksBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getLocksFieldBuilder()
: null;
} else {
locksBuilder_.addAllMessages(other.locks_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.bigquery.biglake.v1alpha1.Lock m =
input.readMessage(
com.google.cloud.bigquery.biglake.v1alpha1.Lock.parser(),
extensionRegistry);
if (locksBuilder_ == null) {
ensureLocksIsMutable();
locks_.add(m);
} else {
locksBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.bigquery.biglake.v1alpha1.Lock> locks_ =
java.util.Collections.emptyList();
private void ensureLocksIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
locks_ = new java.util.ArrayList<com.google.cloud.bigquery.biglake.v1alpha1.Lock>(locks_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.bigquery.biglake.v1alpha1.Lock,
com.google.cloud.bigquery.biglake.v1alpha1.Lock.Builder,
com.google.cloud.bigquery.biglake.v1alpha1.LockOrBuilder>
locksBuilder_;
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public java.util.List<com.google.cloud.bigquery.biglake.v1alpha1.Lock> getLocksList() {
if (locksBuilder_ == null) {
return java.util.Collections.unmodifiableList(locks_);
} else {
return locksBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public int getLocksCount() {
if (locksBuilder_ == null) {
return locks_.size();
} else {
return locksBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public com.google.cloud.bigquery.biglake.v1alpha1.Lock getLocks(int index) {
if (locksBuilder_ == null) {
return locks_.get(index);
} else {
return locksBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public Builder setLocks(int index, com.google.cloud.bigquery.biglake.v1alpha1.Lock value) {
if (locksBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureLocksIsMutable();
locks_.set(index, value);
onChanged();
} else {
locksBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public Builder setLocks(
int index, com.google.cloud.bigquery.biglake.v1alpha1.Lock.Builder builderForValue) {
if (locksBuilder_ == null) {
ensureLocksIsMutable();
locks_.set(index, builderForValue.build());
onChanged();
} else {
locksBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public Builder addLocks(com.google.cloud.bigquery.biglake.v1alpha1.Lock value) {
if (locksBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureLocksIsMutable();
locks_.add(value);
onChanged();
} else {
locksBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public Builder addLocks(int index, com.google.cloud.bigquery.biglake.v1alpha1.Lock value) {
if (locksBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureLocksIsMutable();
locks_.add(index, value);
onChanged();
} else {
locksBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public Builder addLocks(
com.google.cloud.bigquery.biglake.v1alpha1.Lock.Builder builderForValue) {
if (locksBuilder_ == null) {
ensureLocksIsMutable();
locks_.add(builderForValue.build());
onChanged();
} else {
locksBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public Builder addLocks(
int index, com.google.cloud.bigquery.biglake.v1alpha1.Lock.Builder builderForValue) {
if (locksBuilder_ == null) {
ensureLocksIsMutable();
locks_.add(index, builderForValue.build());
onChanged();
} else {
locksBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public Builder addAllLocks(
java.lang.Iterable<? extends com.google.cloud.bigquery.biglake.v1alpha1.Lock> values) {
if (locksBuilder_ == null) {
ensureLocksIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, locks_);
onChanged();
} else {
locksBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public Builder clearLocks() {
if (locksBuilder_ == null) {
locks_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
locksBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public Builder removeLocks(int index) {
if (locksBuilder_ == null) {
ensureLocksIsMutable();
locks_.remove(index);
onChanged();
} else {
locksBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public com.google.cloud.bigquery.biglake.v1alpha1.Lock.Builder getLocksBuilder(int index) {
return getLocksFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public com.google.cloud.bigquery.biglake.v1alpha1.LockOrBuilder getLocksOrBuilder(int index) {
if (locksBuilder_ == null) {
return locks_.get(index);
} else {
return locksBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public java.util.List<? extends com.google.cloud.bigquery.biglake.v1alpha1.LockOrBuilder>
getLocksOrBuilderList() {
if (locksBuilder_ != null) {
return locksBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(locks_);
}
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public com.google.cloud.bigquery.biglake.v1alpha1.Lock.Builder addLocksBuilder() {
return getLocksFieldBuilder()
.addBuilder(com.google.cloud.bigquery.biglake.v1alpha1.Lock.getDefaultInstance());
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public com.google.cloud.bigquery.biglake.v1alpha1.Lock.Builder addLocksBuilder(int index) {
return getLocksFieldBuilder()
.addBuilder(index, com.google.cloud.bigquery.biglake.v1alpha1.Lock.getDefaultInstance());
}
/**
*
*
* <pre>
* The locks from the specified database.
* </pre>
*
* <code>repeated .google.cloud.bigquery.biglake.v1alpha1.Lock locks = 1;</code>
*/
public java.util.List<com.google.cloud.bigquery.biglake.v1alpha1.Lock.Builder>
getLocksBuilderList() {
return getLocksFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.bigquery.biglake.v1alpha1.Lock,
com.google.cloud.bigquery.biglake.v1alpha1.Lock.Builder,
com.google.cloud.bigquery.biglake.v1alpha1.LockOrBuilder>
getLocksFieldBuilder() {
if (locksBuilder_ == null) {
locksBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.bigquery.biglake.v1alpha1.Lock,
com.google.cloud.bigquery.biglake.v1alpha1.Lock.Builder,
com.google.cloud.bigquery.biglake.v1alpha1.LockOrBuilder>(
locks_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
locks_ = null;
}
return locksBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse)
private static final com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse();
}
public static com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListLocksResponse> PARSER =
new com.google.protobuf.AbstractParser<ListLocksResponse>() {
@java.lang.Override
public ListLocksResponse 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<ListLocksResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListLocksResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,449 | java-service-control/proto-google-cloud-service-control-v1/src/main/java/com/google/api/servicecontrol/v1/CheckRequest.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/servicecontrol/v1/service_controller.proto
// Protobuf Java Version: 3.25.8
package com.google.api.servicecontrol.v1;
/**
*
*
* <pre>
* Request message for the Check method.
* </pre>
*
* Protobuf type {@code google.api.servicecontrol.v1.CheckRequest}
*/
public final class CheckRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.api.servicecontrol.v1.CheckRequest)
CheckRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CheckRequest.newBuilder() to construct.
private CheckRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CheckRequest() {
serviceName_ = "";
serviceConfigId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CheckRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.api.servicecontrol.v1.ServiceControllerProto
.internal_static_google_api_servicecontrol_v1_CheckRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.api.servicecontrol.v1.ServiceControllerProto
.internal_static_google_api_servicecontrol_v1_CheckRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.api.servicecontrol.v1.CheckRequest.class,
com.google.api.servicecontrol.v1.CheckRequest.Builder.class);
}
private int bitField0_;
public static final int SERVICE_NAME_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object serviceName_ = "";
/**
*
*
* <pre>
* The service name as specified in its service configuration. For example,
* `"pubsub.googleapis.com"`.
*
* See
* [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service)
* for the definition of a service name.
* </pre>
*
* <code>string service_name = 1;</code>
*
* @return The serviceName.
*/
@java.lang.Override
public java.lang.String getServiceName() {
java.lang.Object ref = serviceName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
serviceName_ = s;
return s;
}
}
/**
*
*
* <pre>
* The service name as specified in its service configuration. For example,
* `"pubsub.googleapis.com"`.
*
* See
* [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service)
* for the definition of a service name.
* </pre>
*
* <code>string service_name = 1;</code>
*
* @return The bytes for serviceName.
*/
@java.lang.Override
public com.google.protobuf.ByteString getServiceNameBytes() {
java.lang.Object ref = serviceName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
serviceName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int OPERATION_FIELD_NUMBER = 2;
private com.google.api.servicecontrol.v1.Operation operation_;
/**
*
*
* <pre>
* The operation to be checked.
* </pre>
*
* <code>.google.api.servicecontrol.v1.Operation operation = 2;</code>
*
* @return Whether the operation field is set.
*/
@java.lang.Override
public boolean hasOperation() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The operation to be checked.
* </pre>
*
* <code>.google.api.servicecontrol.v1.Operation operation = 2;</code>
*
* @return The operation.
*/
@java.lang.Override
public com.google.api.servicecontrol.v1.Operation getOperation() {
return operation_ == null
? com.google.api.servicecontrol.v1.Operation.getDefaultInstance()
: operation_;
}
/**
*
*
* <pre>
* The operation to be checked.
* </pre>
*
* <code>.google.api.servicecontrol.v1.Operation operation = 2;</code>
*/
@java.lang.Override
public com.google.api.servicecontrol.v1.OperationOrBuilder getOperationOrBuilder() {
return operation_ == null
? com.google.api.servicecontrol.v1.Operation.getDefaultInstance()
: operation_;
}
public static final int SERVICE_CONFIG_ID_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object serviceConfigId_ = "";
/**
*
*
* <pre>
* Specifies which version of service configuration should be used to process
* the request.
*
* If unspecified or no matching version can be found, the
* latest one will be used.
* </pre>
*
* <code>string service_config_id = 4;</code>
*
* @return The serviceConfigId.
*/
@java.lang.Override
public java.lang.String getServiceConfigId() {
java.lang.Object ref = serviceConfigId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
serviceConfigId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Specifies which version of service configuration should be used to process
* the request.
*
* If unspecified or no matching version can be found, the
* latest one will be used.
* </pre>
*
* <code>string service_config_id = 4;</code>
*
* @return The bytes for serviceConfigId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getServiceConfigIdBytes() {
java.lang.Object ref = serviceConfigId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
serviceConfigId_ = 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(serviceName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, serviceName_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getOperation());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(serviceConfigId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, serviceConfigId_);
}
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(serviceName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, serviceName_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getOperation());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(serviceConfigId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, serviceConfigId_);
}
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.servicecontrol.v1.CheckRequest)) {
return super.equals(obj);
}
com.google.api.servicecontrol.v1.CheckRequest other =
(com.google.api.servicecontrol.v1.CheckRequest) obj;
if (!getServiceName().equals(other.getServiceName())) return false;
if (hasOperation() != other.hasOperation()) return false;
if (hasOperation()) {
if (!getOperation().equals(other.getOperation())) return false;
}
if (!getServiceConfigId().equals(other.getServiceConfigId())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + SERVICE_NAME_FIELD_NUMBER;
hash = (53 * hash) + getServiceName().hashCode();
if (hasOperation()) {
hash = (37 * hash) + OPERATION_FIELD_NUMBER;
hash = (53 * hash) + getOperation().hashCode();
}
hash = (37 * hash) + SERVICE_CONFIG_ID_FIELD_NUMBER;
hash = (53 * hash) + getServiceConfigId().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.api.servicecontrol.v1.CheckRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.servicecontrol.v1.CheckRequest 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.servicecontrol.v1.CheckRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.servicecontrol.v1.CheckRequest 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.servicecontrol.v1.CheckRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.servicecontrol.v1.CheckRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.api.servicecontrol.v1.CheckRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.api.servicecontrol.v1.CheckRequest 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.servicecontrol.v1.CheckRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.api.servicecontrol.v1.CheckRequest 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.servicecontrol.v1.CheckRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.api.servicecontrol.v1.CheckRequest 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.servicecontrol.v1.CheckRequest 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 Check method.
* </pre>
*
* Protobuf type {@code google.api.servicecontrol.v1.CheckRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.api.servicecontrol.v1.CheckRequest)
com.google.api.servicecontrol.v1.CheckRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.api.servicecontrol.v1.ServiceControllerProto
.internal_static_google_api_servicecontrol_v1_CheckRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.api.servicecontrol.v1.ServiceControllerProto
.internal_static_google_api_servicecontrol_v1_CheckRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.api.servicecontrol.v1.CheckRequest.class,
com.google.api.servicecontrol.v1.CheckRequest.Builder.class);
}
// Construct using com.google.api.servicecontrol.v1.CheckRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getOperationFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
serviceName_ = "";
operation_ = null;
if (operationBuilder_ != null) {
operationBuilder_.dispose();
operationBuilder_ = null;
}
serviceConfigId_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.api.servicecontrol.v1.ServiceControllerProto
.internal_static_google_api_servicecontrol_v1_CheckRequest_descriptor;
}
@java.lang.Override
public com.google.api.servicecontrol.v1.CheckRequest getDefaultInstanceForType() {
return com.google.api.servicecontrol.v1.CheckRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.api.servicecontrol.v1.CheckRequest build() {
com.google.api.servicecontrol.v1.CheckRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.api.servicecontrol.v1.CheckRequest buildPartial() {
com.google.api.servicecontrol.v1.CheckRequest result =
new com.google.api.servicecontrol.v1.CheckRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.api.servicecontrol.v1.CheckRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.serviceName_ = serviceName_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.operation_ = operationBuilder_ == null ? operation_ : operationBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.serviceConfigId_ = serviceConfigId_;
}
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.api.servicecontrol.v1.CheckRequest) {
return mergeFrom((com.google.api.servicecontrol.v1.CheckRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.api.servicecontrol.v1.CheckRequest other) {
if (other == com.google.api.servicecontrol.v1.CheckRequest.getDefaultInstance()) return this;
if (!other.getServiceName().isEmpty()) {
serviceName_ = other.serviceName_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasOperation()) {
mergeOperation(other.getOperation());
}
if (!other.getServiceConfigId().isEmpty()) {
serviceConfigId_ = other.serviceConfigId_;
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:
{
serviceName_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getOperationFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 34:
{
serviceConfigId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 34
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object serviceName_ = "";
/**
*
*
* <pre>
* The service name as specified in its service configuration. For example,
* `"pubsub.googleapis.com"`.
*
* See
* [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service)
* for the definition of a service name.
* </pre>
*
* <code>string service_name = 1;</code>
*
* @return The serviceName.
*/
public java.lang.String getServiceName() {
java.lang.Object ref = serviceName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
serviceName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The service name as specified in its service configuration. For example,
* `"pubsub.googleapis.com"`.
*
* See
* [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service)
* for the definition of a service name.
* </pre>
*
* <code>string service_name = 1;</code>
*
* @return The bytes for serviceName.
*/
public com.google.protobuf.ByteString getServiceNameBytes() {
java.lang.Object ref = serviceName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
serviceName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The service name as specified in its service configuration. For example,
* `"pubsub.googleapis.com"`.
*
* See
* [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service)
* for the definition of a service name.
* </pre>
*
* <code>string service_name = 1;</code>
*
* @param value The serviceName to set.
* @return This builder for chaining.
*/
public Builder setServiceName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
serviceName_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The service name as specified in its service configuration. For example,
* `"pubsub.googleapis.com"`.
*
* See
* [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service)
* for the definition of a service name.
* </pre>
*
* <code>string service_name = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearServiceName() {
serviceName_ = getDefaultInstance().getServiceName();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* The service name as specified in its service configuration. For example,
* `"pubsub.googleapis.com"`.
*
* See
* [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service)
* for the definition of a service name.
* </pre>
*
* <code>string service_name = 1;</code>
*
* @param value The bytes for serviceName to set.
* @return This builder for chaining.
*/
public Builder setServiceNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
serviceName_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.api.servicecontrol.v1.Operation operation_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.api.servicecontrol.v1.Operation,
com.google.api.servicecontrol.v1.Operation.Builder,
com.google.api.servicecontrol.v1.OperationOrBuilder>
operationBuilder_;
/**
*
*
* <pre>
* The operation to be checked.
* </pre>
*
* <code>.google.api.servicecontrol.v1.Operation operation = 2;</code>
*
* @return Whether the operation field is set.
*/
public boolean hasOperation() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The operation to be checked.
* </pre>
*
* <code>.google.api.servicecontrol.v1.Operation operation = 2;</code>
*
* @return The operation.
*/
public com.google.api.servicecontrol.v1.Operation getOperation() {
if (operationBuilder_ == null) {
return operation_ == null
? com.google.api.servicecontrol.v1.Operation.getDefaultInstance()
: operation_;
} else {
return operationBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The operation to be checked.
* </pre>
*
* <code>.google.api.servicecontrol.v1.Operation operation = 2;</code>
*/
public Builder setOperation(com.google.api.servicecontrol.v1.Operation value) {
if (operationBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
} else {
operationBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The operation to be checked.
* </pre>
*
* <code>.google.api.servicecontrol.v1.Operation operation = 2;</code>
*/
public Builder setOperation(
com.google.api.servicecontrol.v1.Operation.Builder builderForValue) {
if (operationBuilder_ == null) {
operation_ = builderForValue.build();
} else {
operationBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The operation to be checked.
* </pre>
*
* <code>.google.api.servicecontrol.v1.Operation operation = 2;</code>
*/
public Builder mergeOperation(com.google.api.servicecontrol.v1.Operation value) {
if (operationBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& operation_ != null
&& operation_ != com.google.api.servicecontrol.v1.Operation.getDefaultInstance()) {
getOperationBuilder().mergeFrom(value);
} else {
operation_ = value;
}
} else {
operationBuilder_.mergeFrom(value);
}
if (operation_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The operation to be checked.
* </pre>
*
* <code>.google.api.servicecontrol.v1.Operation operation = 2;</code>
*/
public Builder clearOperation() {
bitField0_ = (bitField0_ & ~0x00000002);
operation_ = null;
if (operationBuilder_ != null) {
operationBuilder_.dispose();
operationBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The operation to be checked.
* </pre>
*
* <code>.google.api.servicecontrol.v1.Operation operation = 2;</code>
*/
public com.google.api.servicecontrol.v1.Operation.Builder getOperationBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getOperationFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The operation to be checked.
* </pre>
*
* <code>.google.api.servicecontrol.v1.Operation operation = 2;</code>
*/
public com.google.api.servicecontrol.v1.OperationOrBuilder getOperationOrBuilder() {
if (operationBuilder_ != null) {
return operationBuilder_.getMessageOrBuilder();
} else {
return operation_ == null
? com.google.api.servicecontrol.v1.Operation.getDefaultInstance()
: operation_;
}
}
/**
*
*
* <pre>
* The operation to be checked.
* </pre>
*
* <code>.google.api.servicecontrol.v1.Operation operation = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.api.servicecontrol.v1.Operation,
com.google.api.servicecontrol.v1.Operation.Builder,
com.google.api.servicecontrol.v1.OperationOrBuilder>
getOperationFieldBuilder() {
if (operationBuilder_ == null) {
operationBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.api.servicecontrol.v1.Operation,
com.google.api.servicecontrol.v1.Operation.Builder,
com.google.api.servicecontrol.v1.OperationOrBuilder>(
getOperation(), getParentForChildren(), isClean());
operation_ = null;
}
return operationBuilder_;
}
private java.lang.Object serviceConfigId_ = "";
/**
*
*
* <pre>
* Specifies which version of service configuration should be used to process
* the request.
*
* If unspecified or no matching version can be found, the
* latest one will be used.
* </pre>
*
* <code>string service_config_id = 4;</code>
*
* @return The serviceConfigId.
*/
public java.lang.String getServiceConfigId() {
java.lang.Object ref = serviceConfigId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
serviceConfigId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Specifies which version of service configuration should be used to process
* the request.
*
* If unspecified or no matching version can be found, the
* latest one will be used.
* </pre>
*
* <code>string service_config_id = 4;</code>
*
* @return The bytes for serviceConfigId.
*/
public com.google.protobuf.ByteString getServiceConfigIdBytes() {
java.lang.Object ref = serviceConfigId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
serviceConfigId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Specifies which version of service configuration should be used to process
* the request.
*
* If unspecified or no matching version can be found, the
* latest one will be used.
* </pre>
*
* <code>string service_config_id = 4;</code>
*
* @param value The serviceConfigId to set.
* @return This builder for chaining.
*/
public Builder setServiceConfigId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
serviceConfigId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Specifies which version of service configuration should be used to process
* the request.
*
* If unspecified or no matching version can be found, the
* latest one will be used.
* </pre>
*
* <code>string service_config_id = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearServiceConfigId() {
serviceConfigId_ = getDefaultInstance().getServiceConfigId();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Specifies which version of service configuration should be used to process
* the request.
*
* If unspecified or no matching version can be found, the
* latest one will be used.
* </pre>
*
* <code>string service_config_id = 4;</code>
*
* @param value The bytes for serviceConfigId to set.
* @return This builder for chaining.
*/
public Builder setServiceConfigIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
serviceConfigId_ = 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.api.servicecontrol.v1.CheckRequest)
}
// @@protoc_insertion_point(class_scope:google.api.servicecontrol.v1.CheckRequest)
private static final com.google.api.servicecontrol.v1.CheckRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.api.servicecontrol.v1.CheckRequest();
}
public static com.google.api.servicecontrol.v1.CheckRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CheckRequest> PARSER =
new com.google.protobuf.AbstractParser<CheckRequest>() {
@java.lang.Override
public CheckRequest 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<CheckRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CheckRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.api.servicecontrol.v1.CheckRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,433 | java-os-config/proto-google-cloud-os-config-v1alpha/src/main/java/com/google/cloud/osconfig/v1alpha/ListVulnerabilityReportsRequest.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/osconfig/v1alpha/vulnerability.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.osconfig.v1alpha;
/**
*
*
* <pre>
* A request message for listing vulnerability reports for all VM instances in
* the specified location.
* </pre>
*
* Protobuf type {@code google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest}
*/
public final class ListVulnerabilityReportsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest)
ListVulnerabilityReportsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListVulnerabilityReportsRequest.newBuilder() to construct.
private ListVulnerabilityReportsRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListVulnerabilityReportsRequest() {
parent_ = "";
pageToken_ = "";
filter_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListVulnerabilityReportsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.osconfig.v1alpha.VulnerabilityProto
.internal_static_google_cloud_osconfig_v1alpha_ListVulnerabilityReportsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.osconfig.v1alpha.VulnerabilityProto
.internal_static_google_cloud_osconfig_v1alpha_ListVulnerabilityReportsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest.class,
com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent resource name.
*
* Format: `projects/{project}/locations/{location}/instances/-`
*
* For `{project}`, either `project-number` or `project-id` can be provided.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The parent resource name.
*
* Format: `projects/{project}/locations/{location}/instances/-`
*
* For `{project}`, either `project-number` or `project-id` can be provided.
* </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 results to return.
* </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 pagination token returned from a previous call to
* `ListVulnerabilityReports` that indicates where this listing
* should continue from.
* </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 pagination token returned from a previous call to
* `ListVulnerabilityReports` that indicates where this listing
* should continue from.
* </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>
* If provided, this field specifies the criteria that must be met by a
* `vulnerabilityReport` API resource to be included in the response.
* </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>
* If provided, this field specifies the criteria that must be met by a
* `vulnerabilityReport` API resource to be included in the response.
* </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.osconfig.v1alpha.ListVulnerabilityReportsRequest)) {
return super.equals(obj);
}
com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest other =
(com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest) 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.osconfig.v1alpha.ListVulnerabilityReportsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest 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.osconfig.v1alpha.ListVulnerabilityReportsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest 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.osconfig.v1alpha.ListVulnerabilityReportsRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest 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.osconfig.v1alpha.ListVulnerabilityReportsRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest
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.osconfig.v1alpha.ListVulnerabilityReportsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest 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.osconfig.v1alpha.ListVulnerabilityReportsRequest 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 listing vulnerability reports for all VM instances in
* the specified location.
* </pre>
*
* Protobuf type {@code google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest)
com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.osconfig.v1alpha.VulnerabilityProto
.internal_static_google_cloud_osconfig_v1alpha_ListVulnerabilityReportsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.osconfig.v1alpha.VulnerabilityProto
.internal_static_google_cloud_osconfig_v1alpha_ListVulnerabilityReportsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest.class,
com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest.Builder.class);
}
// Construct using
// com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest.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.osconfig.v1alpha.VulnerabilityProto
.internal_static_google_cloud_osconfig_v1alpha_ListVulnerabilityReportsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest
getDefaultInstanceForType() {
return com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest build() {
com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest buildPartial() {
com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest result =
new com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest 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.osconfig.v1alpha.ListVulnerabilityReportsRequest) {
return mergeFrom((com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest other) {
if (other
== com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000008;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent resource name.
*
* Format: `projects/{project}/locations/{location}/instances/-`
*
* For `{project}`, either `project-number` or `project-id` can be provided.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The parent resource name.
*
* Format: `projects/{project}/locations/{location}/instances/-`
*
* For `{project}`, either `project-number` or `project-id` can be provided.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The parent resource name.
*
* Format: `projects/{project}/locations/{location}/instances/-`
*
* For `{project}`, either `project-number` or `project-id` can be provided.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The parent resource name.
*
* Format: `projects/{project}/locations/{location}/instances/-`
*
* For `{project}`, either `project-number` or `project-id` can be provided.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The parent resource name.
*
* Format: `projects/{project}/locations/{location}/instances/-`
*
* For `{project}`, either `project-number` or `project-id` can be provided.
* </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 results to return.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* The maximum number of results to return.
* </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 results to return.
* </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 pagination token returned from a previous call to
* `ListVulnerabilityReports` that indicates where this listing
* should continue from.
* </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 pagination token returned from a previous call to
* `ListVulnerabilityReports` that indicates where this listing
* should continue from.
* </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 pagination token returned from a previous call to
* `ListVulnerabilityReports` that indicates where this listing
* should continue from.
* </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 pagination token returned from a previous call to
* `ListVulnerabilityReports` that indicates where this listing
* should continue from.
* </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 pagination token returned from a previous call to
* `ListVulnerabilityReports` that indicates where this listing
* should continue from.
* </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>
* If provided, this field specifies the criteria that must be met by a
* `vulnerabilityReport` API resource to be included in the response.
* </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>
* If provided, this field specifies the criteria that must be met by a
* `vulnerabilityReport` API resource to be included in the response.
* </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>
* If provided, this field specifies the criteria that must be met by a
* `vulnerabilityReport` API resource to be included in the response.
* </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>
* If provided, this field specifies the criteria that must be met by a
* `vulnerabilityReport` API resource to be included in the response.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* If provided, this field specifies the criteria that must be met by a
* `vulnerabilityReport` API resource to be included in the response.
* </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.osconfig.v1alpha.ListVulnerabilityReportsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest)
private static final com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest();
}
public static com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListVulnerabilityReportsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListVulnerabilityReportsRequest>() {
@java.lang.Override
public ListVulnerabilityReportsRequest 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<ListVulnerabilityReportsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListVulnerabilityReportsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.osconfig.v1alpha.ListVulnerabilityReportsRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,747 | java-dialogflow/google-cloud-dialogflow/src/main/java/com/google/cloud/dialogflow/v2/AnswerRecordsClient.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 com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.paging.AbstractFixedSizeCollection;
import com.google.api.gax.paging.AbstractPage;
import com.google.api.gax.paging.AbstractPagedListResponse;
import com.google.api.gax.rpc.PageContext;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.dialogflow.v2.stub.AnswerRecordsStub;
import com.google.cloud.dialogflow.v2.stub.AnswerRecordsStubSettings;
import com.google.cloud.location.GetLocationRequest;
import com.google.cloud.location.ListLocationsRequest;
import com.google.cloud.location.ListLocationsResponse;
import com.google.cloud.location.Location;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Service Description: Service for managing
* [AnswerRecords][google.cloud.dialogflow.v2.AnswerRecord].
*
* <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 (AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create()) {
* AnswerRecord answerRecord = AnswerRecord.newBuilder().build();
* FieldMask updateMask = FieldMask.newBuilder().build();
* AnswerRecord response = answerRecordsClient.updateAnswerRecord(answerRecord, updateMask);
* }
* }</pre>
*
* <p>Note: close() needs to be called on the AnswerRecordsClient 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> ListAnswerRecords</td>
* <td><p> Returns the list of all answer records in the specified project in reverse chronological order.</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> listAnswerRecords(ListAnswerRecordsRequest 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> listAnswerRecords(LocationName parent)
* <li><p> listAnswerRecords(ProjectName parent)
* <li><p> listAnswerRecords(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> listAnswerRecordsPagedCallable()
* <li><p> listAnswerRecordsCallable()
* </ul>
* </td>
* </tr>
* <tr>
* <td><p> UpdateAnswerRecord</td>
* <td><p> Updates the specified answer record.</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> updateAnswerRecord(UpdateAnswerRecordRequest 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> updateAnswerRecord(AnswerRecord answerRecord, FieldMask updateMask)
* </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> updateAnswerRecordCallable()
* </ul>
* </td>
* </tr>
* <tr>
* <td><p> ListLocations</td>
* <td><p> Lists information about the supported locations for this service.</td>
* <td>
* <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p>
* <ul>
* <li><p> listLocations(ListLocationsRequest request)
* </ul>
* <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p>
* <ul>
* <li><p> listLocationsPagedCallable()
* <li><p> listLocationsCallable()
* </ul>
* </td>
* </tr>
* <tr>
* <td><p> GetLocation</td>
* <td><p> Gets information about a location.</td>
* <td>
* <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p>
* <ul>
* <li><p> getLocation(GetLocationRequest request)
* </ul>
* <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p>
* <ul>
* <li><p> getLocationCallable()
* </ul>
* </td>
* </tr>
* </table>
*
* <p>See the individual methods for example code.
*
* <p>Many parameters require resource names to be formatted in a particular way. To assist with
* these names, this class includes a format method for each type of name, and additionally a parse
* method to extract the individual identifiers contained within names that are returned.
*
* <p>This class can be customized by passing in a custom instance of AnswerRecordsSettings 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
* AnswerRecordsSettings answerRecordsSettings =
* AnswerRecordsSettings.newBuilder()
* .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
* .build();
* AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create(answerRecordsSettings);
* }</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
* AnswerRecordsSettings answerRecordsSettings =
* AnswerRecordsSettings.newBuilder().setEndpoint(myEndpoint).build();
* AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create(answerRecordsSettings);
* }</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
* AnswerRecordsSettings answerRecordsSettings =
* AnswerRecordsSettings.newHttpJsonBuilder().build();
* AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create(answerRecordsSettings);
* }</pre>
*
* <p>Please refer to the GitHub repository's samples for more quickstart code snippets.
*/
@Generated("by gapic-generator-java")
public class AnswerRecordsClient implements BackgroundResource {
private final AnswerRecordsSettings settings;
private final AnswerRecordsStub stub;
/** Constructs an instance of AnswerRecordsClient with default settings. */
public static final AnswerRecordsClient create() throws IOException {
return create(AnswerRecordsSettings.newBuilder().build());
}
/**
* Constructs an instance of AnswerRecordsClient, 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 AnswerRecordsClient create(AnswerRecordsSettings settings)
throws IOException {
return new AnswerRecordsClient(settings);
}
/**
* Constructs an instance of AnswerRecordsClient, using the given stub for making calls. This is
* for advanced usage - prefer using create(AnswerRecordsSettings).
*/
public static final AnswerRecordsClient create(AnswerRecordsStub stub) {
return new AnswerRecordsClient(stub);
}
/**
* Constructs an instance of AnswerRecordsClient, 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 AnswerRecordsClient(AnswerRecordsSettings settings) throws IOException {
this.settings = settings;
this.stub = ((AnswerRecordsStubSettings) settings.getStubSettings()).createStub();
}
protected AnswerRecordsClient(AnswerRecordsStub stub) {
this.settings = null;
this.stub = stub;
}
public final AnswerRecordsSettings getSettings() {
return settings;
}
public AnswerRecordsStub getStub() {
return stub;
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Returns the list of all answer records in the specified project in reverse chronological order.
*
* <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 (AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create()) {
* LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
* for (AnswerRecord element : answerRecordsClient.listAnswerRecords(parent).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
* @param parent Required. The project to list all answer records for in reverse chronological
* order. Format: `projects/<Project ID>/locations/<Location ID>`.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final ListAnswerRecordsPagedResponse listAnswerRecords(LocationName parent) {
ListAnswerRecordsRequest request =
ListAnswerRecordsRequest.newBuilder()
.setParent(parent == null ? null : parent.toString())
.build();
return listAnswerRecords(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Returns the list of all answer records in the specified project in reverse chronological order.
*
* <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 (AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create()) {
* ProjectName parent = ProjectName.of("[PROJECT]");
* for (AnswerRecord element : answerRecordsClient.listAnswerRecords(parent).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
* @param parent Required. The project to list all answer records for in reverse chronological
* order. Format: `projects/<Project ID>/locations/<Location ID>`.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final ListAnswerRecordsPagedResponse listAnswerRecords(ProjectName parent) {
ListAnswerRecordsRequest request =
ListAnswerRecordsRequest.newBuilder()
.setParent(parent == null ? null : parent.toString())
.build();
return listAnswerRecords(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Returns the list of all answer records in the specified project in reverse chronological order.
*
* <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 (AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create()) {
* String parent = ProjectName.of("[PROJECT]").toString();
* for (AnswerRecord element : answerRecordsClient.listAnswerRecords(parent).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
* @param parent Required. The project to list all answer records for in reverse chronological
* order. Format: `projects/<Project ID>/locations/<Location ID>`.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final ListAnswerRecordsPagedResponse listAnswerRecords(String parent) {
ListAnswerRecordsRequest request =
ListAnswerRecordsRequest.newBuilder().setParent(parent).build();
return listAnswerRecords(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Returns the list of all answer records in the specified project in reverse chronological order.
*
* <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 (AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create()) {
* ListAnswerRecordsRequest request =
* ListAnswerRecordsRequest.newBuilder()
* .setParent(ProjectName.of("[PROJECT]").toString())
* .setFilter("filter-1274492040")
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .build();
* for (AnswerRecord element : answerRecordsClient.listAnswerRecords(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 ListAnswerRecordsPagedResponse listAnswerRecords(ListAnswerRecordsRequest request) {
return listAnswerRecordsPagedCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Returns the list of all answer records in the specified project in reverse chronological order.
*
* <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 (AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create()) {
* ListAnswerRecordsRequest request =
* ListAnswerRecordsRequest.newBuilder()
* .setParent(ProjectName.of("[PROJECT]").toString())
* .setFilter("filter-1274492040")
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .build();
* ApiFuture<AnswerRecord> future =
* answerRecordsClient.listAnswerRecordsPagedCallable().futureCall(request);
* // Do something.
* for (AnswerRecord element : future.get().iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*/
public final UnaryCallable<ListAnswerRecordsRequest, ListAnswerRecordsPagedResponse>
listAnswerRecordsPagedCallable() {
return stub.listAnswerRecordsPagedCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Returns the list of all answer records in the specified project in reverse chronological order.
*
* <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 (AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create()) {
* ListAnswerRecordsRequest request =
* ListAnswerRecordsRequest.newBuilder()
* .setParent(ProjectName.of("[PROJECT]").toString())
* .setFilter("filter-1274492040")
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .build();
* while (true) {
* ListAnswerRecordsResponse response =
* answerRecordsClient.listAnswerRecordsCallable().call(request);
* for (AnswerRecord element : response.getAnswerRecordsList()) {
* // doThingsWith(element);
* }
* String nextPageToken = response.getNextPageToken();
* if (!Strings.isNullOrEmpty(nextPageToken)) {
* request = request.toBuilder().setPageToken(nextPageToken).build();
* } else {
* break;
* }
* }
* }
* }</pre>
*/
public final UnaryCallable<ListAnswerRecordsRequest, ListAnswerRecordsResponse>
listAnswerRecordsCallable() {
return stub.listAnswerRecordsCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Updates the specified answer record.
*
* <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 (AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create()) {
* AnswerRecord answerRecord = AnswerRecord.newBuilder().build();
* FieldMask updateMask = FieldMask.newBuilder().build();
* AnswerRecord response = answerRecordsClient.updateAnswerRecord(answerRecord, updateMask);
* }
* }</pre>
*
* @param answerRecord Required. Answer record to update.
* @param updateMask Required. The mask to control which fields get updated.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final AnswerRecord updateAnswerRecord(AnswerRecord answerRecord, FieldMask updateMask) {
UpdateAnswerRecordRequest request =
UpdateAnswerRecordRequest.newBuilder()
.setAnswerRecord(answerRecord)
.setUpdateMask(updateMask)
.build();
return updateAnswerRecord(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Updates the specified answer record.
*
* <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 (AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create()) {
* UpdateAnswerRecordRequest request =
* UpdateAnswerRecordRequest.newBuilder()
* .setAnswerRecord(AnswerRecord.newBuilder().build())
* .setUpdateMask(FieldMask.newBuilder().build())
* .build();
* AnswerRecord response = answerRecordsClient.updateAnswerRecord(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 AnswerRecord updateAnswerRecord(UpdateAnswerRecordRequest request) {
return updateAnswerRecordCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Updates the specified answer record.
*
* <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 (AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create()) {
* UpdateAnswerRecordRequest request =
* UpdateAnswerRecordRequest.newBuilder()
* .setAnswerRecord(AnswerRecord.newBuilder().build())
* .setUpdateMask(FieldMask.newBuilder().build())
* .build();
* ApiFuture<AnswerRecord> future =
* answerRecordsClient.updateAnswerRecordCallable().futureCall(request);
* // Do something.
* AnswerRecord response = future.get();
* }
* }</pre>
*/
public final UnaryCallable<UpdateAnswerRecordRequest, AnswerRecord> updateAnswerRecordCallable() {
return stub.updateAnswerRecordCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists information about the supported locations for this service.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create()) {
* ListLocationsRequest request =
* ListLocationsRequest.newBuilder()
* .setName("name3373707")
* .setFilter("filter-1274492040")
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .build();
* for (Location element : answerRecordsClient.listLocations(request).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final ListLocationsPagedResponse listLocations(ListLocationsRequest request) {
return listLocationsPagedCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists information about the supported locations for this service.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create()) {
* ListLocationsRequest request =
* ListLocationsRequest.newBuilder()
* .setName("name3373707")
* .setFilter("filter-1274492040")
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .build();
* ApiFuture<Location> future =
* answerRecordsClient.listLocationsPagedCallable().futureCall(request);
* // Do something.
* for (Location element : future.get().iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*/
public final UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse>
listLocationsPagedCallable() {
return stub.listLocationsPagedCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists information about the supported locations for this service.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create()) {
* ListLocationsRequest request =
* ListLocationsRequest.newBuilder()
* .setName("name3373707")
* .setFilter("filter-1274492040")
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .build();
* while (true) {
* ListLocationsResponse response = answerRecordsClient.listLocationsCallable().call(request);
* for (Location element : response.getLocationsList()) {
* // doThingsWith(element);
* }
* String nextPageToken = response.getNextPageToken();
* if (!Strings.isNullOrEmpty(nextPageToken)) {
* request = request.toBuilder().setPageToken(nextPageToken).build();
* } else {
* break;
* }
* }
* }
* }</pre>
*/
public final UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable() {
return stub.listLocationsCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Gets information about a location.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create()) {
* GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build();
* Location response = answerRecordsClient.getLocation(request);
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final Location getLocation(GetLocationRequest request) {
return getLocationCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Gets information about a location.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (AnswerRecordsClient answerRecordsClient = AnswerRecordsClient.create()) {
* GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build();
* ApiFuture<Location> future = answerRecordsClient.getLocationCallable().futureCall(request);
* // Do something.
* Location response = future.get();
* }
* }</pre>
*/
public final UnaryCallable<GetLocationRequest, Location> getLocationCallable() {
return stub.getLocationCallable();
}
@Override
public final void close() {
stub.close();
}
@Override
public void shutdown() {
stub.shutdown();
}
@Override
public boolean isShutdown() {
return stub.isShutdown();
}
@Override
public boolean isTerminated() {
return stub.isTerminated();
}
@Override
public void shutdownNow() {
stub.shutdownNow();
}
@Override
public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
return stub.awaitTermination(duration, unit);
}
public static class ListAnswerRecordsPagedResponse
extends AbstractPagedListResponse<
ListAnswerRecordsRequest,
ListAnswerRecordsResponse,
AnswerRecord,
ListAnswerRecordsPage,
ListAnswerRecordsFixedSizeCollection> {
public static ApiFuture<ListAnswerRecordsPagedResponse> createAsync(
PageContext<ListAnswerRecordsRequest, ListAnswerRecordsResponse, AnswerRecord> context,
ApiFuture<ListAnswerRecordsResponse> futureResponse) {
ApiFuture<ListAnswerRecordsPage> futurePage =
ListAnswerRecordsPage.createEmptyPage().createPageAsync(context, futureResponse);
return ApiFutures.transform(
futurePage,
input -> new ListAnswerRecordsPagedResponse(input),
MoreExecutors.directExecutor());
}
private ListAnswerRecordsPagedResponse(ListAnswerRecordsPage page) {
super(page, ListAnswerRecordsFixedSizeCollection.createEmptyCollection());
}
}
public static class ListAnswerRecordsPage
extends AbstractPage<
ListAnswerRecordsRequest,
ListAnswerRecordsResponse,
AnswerRecord,
ListAnswerRecordsPage> {
private ListAnswerRecordsPage(
PageContext<ListAnswerRecordsRequest, ListAnswerRecordsResponse, AnswerRecord> context,
ListAnswerRecordsResponse response) {
super(context, response);
}
private static ListAnswerRecordsPage createEmptyPage() {
return new ListAnswerRecordsPage(null, null);
}
@Override
protected ListAnswerRecordsPage createPage(
PageContext<ListAnswerRecordsRequest, ListAnswerRecordsResponse, AnswerRecord> context,
ListAnswerRecordsResponse response) {
return new ListAnswerRecordsPage(context, response);
}
@Override
public ApiFuture<ListAnswerRecordsPage> createPageAsync(
PageContext<ListAnswerRecordsRequest, ListAnswerRecordsResponse, AnswerRecord> context,
ApiFuture<ListAnswerRecordsResponse> futureResponse) {
return super.createPageAsync(context, futureResponse);
}
}
public static class ListAnswerRecordsFixedSizeCollection
extends AbstractFixedSizeCollection<
ListAnswerRecordsRequest,
ListAnswerRecordsResponse,
AnswerRecord,
ListAnswerRecordsPage,
ListAnswerRecordsFixedSizeCollection> {
private ListAnswerRecordsFixedSizeCollection(
List<ListAnswerRecordsPage> pages, int collectionSize) {
super(pages, collectionSize);
}
private static ListAnswerRecordsFixedSizeCollection createEmptyCollection() {
return new ListAnswerRecordsFixedSizeCollection(null, 0);
}
@Override
protected ListAnswerRecordsFixedSizeCollection createCollection(
List<ListAnswerRecordsPage> pages, int collectionSize) {
return new ListAnswerRecordsFixedSizeCollection(pages, collectionSize);
}
}
public static class ListLocationsPagedResponse
extends AbstractPagedListResponse<
ListLocationsRequest,
ListLocationsResponse,
Location,
ListLocationsPage,
ListLocationsFixedSizeCollection> {
public static ApiFuture<ListLocationsPagedResponse> createAsync(
PageContext<ListLocationsRequest, ListLocationsResponse, Location> context,
ApiFuture<ListLocationsResponse> futureResponse) {
ApiFuture<ListLocationsPage> futurePage =
ListLocationsPage.createEmptyPage().createPageAsync(context, futureResponse);
return ApiFutures.transform(
futurePage,
input -> new ListLocationsPagedResponse(input),
MoreExecutors.directExecutor());
}
private ListLocationsPagedResponse(ListLocationsPage page) {
super(page, ListLocationsFixedSizeCollection.createEmptyCollection());
}
}
public static class ListLocationsPage
extends AbstractPage<
ListLocationsRequest, ListLocationsResponse, Location, ListLocationsPage> {
private ListLocationsPage(
PageContext<ListLocationsRequest, ListLocationsResponse, Location> context,
ListLocationsResponse response) {
super(context, response);
}
private static ListLocationsPage createEmptyPage() {
return new ListLocationsPage(null, null);
}
@Override
protected ListLocationsPage createPage(
PageContext<ListLocationsRequest, ListLocationsResponse, Location> context,
ListLocationsResponse response) {
return new ListLocationsPage(context, response);
}
@Override
public ApiFuture<ListLocationsPage> createPageAsync(
PageContext<ListLocationsRequest, ListLocationsResponse, Location> context,
ApiFuture<ListLocationsResponse> futureResponse) {
return super.createPageAsync(context, futureResponse);
}
}
public static class ListLocationsFixedSizeCollection
extends AbstractFixedSizeCollection<
ListLocationsRequest,
ListLocationsResponse,
Location,
ListLocationsPage,
ListLocationsFixedSizeCollection> {
private ListLocationsFixedSizeCollection(List<ListLocationsPage> pages, int collectionSize) {
super(pages, collectionSize);
}
private static ListLocationsFixedSizeCollection createEmptyCollection() {
return new ListLocationsFixedSizeCollection(null, 0);
}
@Override
protected ListLocationsFixedSizeCollection createCollection(
List<ListLocationsPage> pages, int collectionSize) {
return new ListLocationsFixedSizeCollection(pages, collectionSize);
}
}
}
|
apache/directory-studio | 36,460 | plugins/openldap.syncrepl/src/main/java/org/apache/directory/studio/openldap/syncrepl/SyncReplParser.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.openldap.syncrepl;
import java.text.ParseException;
import org.apache.directory.api.util.Position;
import org.apache.directory.api.util.Strings;
/**
* A parser of SyncRepl value.
*/
public class SyncReplParser
{
private static final String KEYWORD_RID = "rid";
private static final String KEYWORD_PROVIDER = "provider";
private static final String KEYWORD_SEARCHBASE = "searchbase";
private static final String KEYWORD_TYPE = "type";
private static final String KEYWORD_INTERVAL = "interval";
private static final String KEYWORD_RETRY = "retry";
private static final String KEYWORD_FILTER = "filter";
private static final String KEYWORD_SCOPE = "scope";
private static final String KEYWORD_ATTRS = "attrs";
private static final String KEYWORD_ATTRSONLY = "attrsonly";
private static final String KEYWORD_SIZELIMIT = "sizelimit";
private static final String KEYWORD_TIMELIMIT = "timelimit";
private static final String KEYWORD_SCHEMACHECKING = "schemachecking";
private static final String KEYWORD_NETWORK_TIMEOUT = "network-timeout";
private static final String KEYWORD_TIMEOUT = "timeout";
private static final String KEYWORD_BINDMETHOD = "bindmethod";
private static final String KEYWORD_BINDDN = "binddn";
private static final String KEYWORD_SASLMECH = "saslmech";
private static final String KEYWORD_AUTHCID = "authcid";
private static final String KEYWORD_AUTHZID = "authzid";
private static final String KEYWORD_CREDENTIALS = "credentials";
private static final String KEYWORD_REALM = "realm";
private static final String KEYWORD_SECPROPS = "secprops";
private static final String KEYWORD_KEEPALIVE = "keepalive";
private static final String KEYWORD_STARTTLS = "starttls";
private static final String KEYWORD_TLS_CERT = "tls_cert";
private static final String KEYWORD_TLS_KEY = "tls_key";
private static final String KEYWORD_TLS_CACERT = "tls_cacert";
private static final String KEYWORD_TLS_CACERTDIR = "tls_cacertdir";
private static final String KEYWORD_TLS_REQCERT = "tls_reqcert";
private static final String KEYWORD_TLS_CIPHERSUITE = "tls_ciphersuite";
private static final String KEYWORD_TLS_CRLCHECK = "tls_crlcheck";
private static final String KEYWORD_LOGBASE = "logbase";
private static final String KEYWORD_LOGFILTER = "logfilter";
private static final String KEYWORD_SYNCDATA = "syncdata";
/**
* Parses a SyncRepl value.
*
* @param s
* the string to be parsed
* @return the associated SyncRepl object
* @throws SyncReplParserException
* if there are any recognition errors (bad syntax)
*/
public synchronized SyncRepl parse( String s ) throws SyncReplParserException
{
SyncReplParserException parserException = new SyncReplParserException();
// Trimming the value
s = Strings.trim( s );
// Getting the chars of the string
char[] chars = new char[s.length()];
s.getChars( 0, s.length(), chars, 0 );
// Creating the position
Position pos = new Position();
pos.start = 0;
pos.end = 0;
pos.length = chars.length;
SyncRepl syncRepl = parseInternal( chars, pos, parserException );
if ( parserException.size() > 0 )
{
throw parserException;
}
return syncRepl;
}
private SyncRepl parseInternal( char[] chars, Position pos, SyncReplParserException parserException )
{
SyncRepl syncRepl = new SyncRepl();
boolean foundAtLeastOneProperty = false;
char c = Strings.charAt( chars, pos.start );
do
{
// Whitespace
if ( Character.isWhitespace( c ) )
{
// We ignore all whitespaces
pos.start++;
}
// rid
else if ( Strings.areEquals( chars, pos.start, KEYWORD_RID, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_RID.length();
parseRid( chars, pos, syncRepl, parserException );
}
// provider
else if ( Strings.areEquals( chars, pos.start, KEYWORD_PROVIDER, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_PROVIDER.length();
parseProvider( chars, pos, syncRepl, parserException );
}
// searchbase
else if ( Strings.areEquals( chars, pos.start, KEYWORD_SEARCHBASE, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_SEARCHBASE.length();
parseSearchBase( chars, pos, syncRepl, parserException );
}
// type
else if ( Strings.areEquals( chars, pos.start, KEYWORD_TYPE, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_TYPE.length();
parseType( chars, pos, syncRepl, parserException );
}
// interval
else if ( Strings.areEquals( chars, pos.start, KEYWORD_INTERVAL, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_INTERVAL.length();
parseInterval( chars, pos, syncRepl, parserException );
}
// retry
else if ( Strings.areEquals( chars, pos.start, KEYWORD_RETRY, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_RETRY.length();
parseRetry( chars, pos, syncRepl, parserException );
}
// filter
else if ( Strings.areEquals( chars, pos.start, KEYWORD_FILTER, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_FILTER.length();
parseFilter( chars, pos, syncRepl, parserException );
}
// scope
else if ( Strings.areEquals( chars, pos.start, KEYWORD_SCOPE, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_SCOPE.length();
parseScope( chars, pos, syncRepl, parserException );
}
// attrsonly
else if ( Strings.areEquals( chars, pos.start, KEYWORD_ATTRSONLY, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_ATTRSONLY.length();
syncRepl.setAttrsOnly( true );
}
// attrs
else if ( Strings.areEquals( chars, pos.start, KEYWORD_ATTRS, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_ATTRS.length();
parseAttrs( chars, pos, syncRepl, parserException );
}
// sizelimit
else if ( Strings.areEquals( chars, pos.start, KEYWORD_SIZELIMIT, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_SIZELIMIT.length();
parseSizeLimit( chars, pos, syncRepl, parserException );
}
// timelimit
else if ( Strings.areEquals( chars, pos.start, KEYWORD_TIMELIMIT, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_TIMELIMIT.length();
parseTimeLimit( chars, pos, syncRepl, parserException );
}
// schemachecking
else if ( Strings.areEquals( chars, pos.start, KEYWORD_SCHEMACHECKING, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_SCHEMACHECKING.length();
parseSchemaChecking( chars, pos, syncRepl, parserException );
}
// network-timeout
else if ( Strings.areEquals( chars, pos.start, KEYWORD_NETWORK_TIMEOUT, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_NETWORK_TIMEOUT.length();
parseNetworkTimeout( chars, pos, syncRepl, parserException );
}
// timeout
else if ( Strings.areEquals( chars, pos.start, KEYWORD_TIMEOUT, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_TIMEOUT.length();
parseTimeout( chars, pos, syncRepl, parserException );
}
// bindmethod
else if ( Strings.areEquals( chars, pos.start, KEYWORD_BINDMETHOD, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_BINDMETHOD.length();
parseBindMethod( chars, pos, syncRepl, parserException );
}
// binddn
else if ( Strings.areEquals( chars, pos.start, KEYWORD_BINDDN, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_BINDDN.length();
parseBindDn( chars, pos, syncRepl, parserException );
}
// saslmech
else if ( Strings.areEquals( chars, pos.start, KEYWORD_SASLMECH, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_SASLMECH.length();
parseSaslMech( chars, pos, syncRepl, parserException );
}
// authcid
else if ( Strings.areEquals( chars, pos.start, KEYWORD_AUTHCID, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_AUTHCID.length();
parseAuthcId( chars, pos, syncRepl, parserException );
}
// authzid
else if ( Strings.areEquals( chars, pos.start, KEYWORD_AUTHZID, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_AUTHZID.length();
parseAuthzId( chars, pos, syncRepl, parserException );
}
// credentials
else if ( Strings.areEquals( chars, pos.start, KEYWORD_CREDENTIALS, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_CREDENTIALS.length();
parseCredentials( chars, pos, syncRepl, parserException );
}
// realm
else if ( Strings.areEquals( chars, pos.start, KEYWORD_REALM, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_REALM.length();
parseRealm( chars, pos, syncRepl, parserException );
}
// secprops
else if ( Strings.areEquals( chars, pos.start, KEYWORD_SECPROPS, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_SECPROPS.length();
parseSecProps( chars, pos, syncRepl, parserException );
}
// keepalive
else if ( Strings.areEquals( chars, pos.start, KEYWORD_KEEPALIVE, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_KEEPALIVE.length();
parseKeepAlive( chars, pos, syncRepl, parserException );
}
// starttls
else if ( Strings.areEquals( chars, pos.start, KEYWORD_STARTTLS, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_STARTTLS.length();
parseStartTls( chars, pos, syncRepl, parserException );
}
// tls_cert
else if ( Strings.areEquals( chars, pos.start, KEYWORD_TLS_CERT, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_TLS_CERT.length();
parseTlsCert( chars, pos, syncRepl, parserException );
}
// tls_key
else if ( Strings.areEquals( chars, pos.start, KEYWORD_TLS_KEY, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_TLS_KEY.length();
parseTlsKey( chars, pos, syncRepl, parserException );
}
// tls_cacert
else if ( Strings.areEquals( chars, pos.start, KEYWORD_TLS_CACERT, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_TLS_CACERT.length();
parseTlsCacert( chars, pos, syncRepl, parserException );
}
// tls_cacertdir
else if ( Strings.areEquals( chars, pos.start, KEYWORD_TLS_CACERTDIR, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_TLS_CACERTDIR.length();
parseTlsCacertDir( chars, pos, syncRepl, parserException );
}
// tls_reqcert
else if ( Strings.areEquals( chars, pos.start, KEYWORD_TLS_REQCERT, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_TLS_REQCERT.length();
parseTlsReqCert( chars, pos, syncRepl, parserException );
}
// tls_ciphersuite
else if ( Strings.areEquals( chars, pos.start, KEYWORD_TLS_CIPHERSUITE, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_TLS_CIPHERSUITE.length();
parseTlsCipherSuite( chars, pos, syncRepl, parserException );
}
// tls_crlcheck
else if ( Strings.areEquals( chars, pos.start, KEYWORD_TLS_CRLCHECK, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_TLS_CRLCHECK.length();
parseTlsCrlCheck( chars, pos, syncRepl, parserException );
}
// logbase
else if ( Strings.areEquals( chars, pos.start, KEYWORD_LOGBASE, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_LOGBASE.length();
parseLogBase( chars, pos, syncRepl, parserException );
}
// logfilter
else if ( Strings.areEquals( chars, pos.start, KEYWORD_LOGFILTER, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_LOGFILTER.length();
parseLogFilter( chars, pos, syncRepl, parserException );
}
// syncdata
else if ( Strings.areEquals( chars, pos.start, KEYWORD_SYNCDATA, false ) >= 0 )
{
foundAtLeastOneProperty = true;
pos.start += KEYWORD_SYNCDATA.length();
parseSyncData( chars, pos, syncRepl, parserException );
}
// We couldn't find the appropriate option
else
{
pos.start++;
}
}
while ( ( pos.start != pos.length ) && ( ( c = Strings.charAt( chars, pos.start ) ) != '\0' ) );
if ( foundAtLeastOneProperty )
{
return syncRepl;
}
return null;
}
/**
* Parses the 'rid' option.
*
* @param s the string
* @param pos the position
* @param syncRepl the SyncRepl object
* @param parserException the parser exception
*/
private void parseRid( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
syncRepl.setRid( value );
}
}
private void parseProvider( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
try
{
syncRepl.setProvider( Provider.parse( value ) );
}
catch ( ParseException e )
{
parserException.addParseException( e );
}
}
}
private void parseSearchBase( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
syncRepl.setSearchBase( value );
}
}
private void parseType( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
try
{
syncRepl.setType( Type.parse( value ) );
}
catch ( ParseException e )
{
parserException.addParseException( e );
}
}
}
private void parseInterval( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
try
{
syncRepl.setInterval( Interval.parse( value ) );
}
catch ( ParseException e )
{
parserException.addParseException( e );
}
}
}
private void parseRetry( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
try
{
syncRepl.setRetry( Retry.parse( value ) );
}
catch ( ParseException e )
{
parserException.addParseException( e );
}
}
}
private void parseFilter( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
syncRepl.setFilter( value );
}
}
private void parseScope( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
try
{
syncRepl.setScope( Scope.parse( value ) );
}
catch ( ParseException e )
{
parserException.addParseException( e );
}
}
}
private void parseAttrs( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
String[] attrs = value.split( ",( )*" );
if ( ( attrs != null ) && ( attrs.length > 0 ) )
{
syncRepl.addAttribute( attrs );
}
}
}
private void parseSizeLimit( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
try
{
syncRepl.setSizeLimit( Integer.parseInt( value ) );
}
catch ( NumberFormatException e )
{
parserException.addParseException( new ParseException( "Unable to convert size limit value '" + value
+ "' as an integer.", 0 ) );
}
}
}
private void parseTimeLimit( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
try
{
syncRepl.setTimeLimit( Integer.parseInt( value ) );
}
catch ( NumberFormatException e )
{
parserException.addParseException( new ParseException( "Unable to convert time limit value '" + value
+ "' as an integer.", 0 ) );
}
}
}
private void parseSchemaChecking( char[] chars, Position pos, SyncRepl syncRepl,
SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
try
{
syncRepl.setSchemaChecking( SchemaChecking.parse( value ) );
}
catch ( ParseException e )
{
parserException.addParseException( e );
}
}
}
private void parseNetworkTimeout( char[] chars, Position pos, SyncRepl syncRepl,
SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
try
{
syncRepl.setNetworkTimeout( Integer.parseInt( value ) );
}
catch ( NumberFormatException e )
{
parserException.addParseException( new ParseException( "Unable to convert network timeout value '"
+ value
+ "' as an integer.", 0 ) );
}
}
}
private void parseTimeout( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
try
{
syncRepl.setTimeout( Integer.parseInt( value ) );
}
catch ( NumberFormatException e )
{
parserException.addParseException( new ParseException( "Unable to convert timeout value '" + value
+ "' as an integer.", 0 ) );
}
}
}
private void parseBindMethod( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
try
{
syncRepl.setBindMethod( BindMethod.parse( value ) );
}
catch ( ParseException e )
{
parserException.addParseException( e );
}
}
}
private void parseBindDn( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
syncRepl.setBindDn( value );
}
}
private void parseSaslMech( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
syncRepl.setSaslMech( value );
}
}
private void parseAuthcId( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
syncRepl.setAuthcid( value );
}
}
private void parseAuthzId( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
syncRepl.setAuthzid( value );
}
}
private void parseCredentials( char[] chars, Position pos, SyncRepl syncRepl,
SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
syncRepl.setCredentials( value );
}
}
private void parseRealm( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
syncRepl.setRealm( value );
}
}
private void parseSecProps( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
syncRepl.setSecProps( value );
}
}
private void parseKeepAlive( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
try
{
syncRepl.setKeepAlive( KeepAlive.parse( value ) );
}
catch ( ParseException e )
{
parserException.addParseException( e );
}
}
}
private void parseStartTls( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
try
{
syncRepl.setStartTls( StartTls.parse( value ) );
}
catch ( ParseException e )
{
parserException.addParseException( e );
}
}
}
private void parseTlsCert( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
syncRepl.setTlsCert( value );
}
}
private void parseTlsKey( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
syncRepl.setTlsKey( value );
}
}
private void parseTlsCacert( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
syncRepl.setTlsCacert( value );
}
}
private void parseTlsCacertDir( char[] chars, Position pos, SyncRepl syncRepl,
SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
syncRepl.setTlsCacertDir( value );
}
}
private void parseTlsReqCert( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
try
{
syncRepl.setTlsReqcert( TlsReqCert.parse( value ) );
}
catch ( ParseException e )
{
parserException.addParseException( e );
}
}
}
private void parseTlsCipherSuite( char[] chars, Position pos, SyncRepl syncRepl,
SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
syncRepl.setTlsCipherSuite( value );
}
}
private void parseTlsCrlCheck( char[] chars, Position pos, SyncRepl syncRepl,
SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
try
{
syncRepl.setTlsCrlcheck( TlsCrlCheck.parse( value ) );
}
catch ( ParseException e )
{
parserException.addParseException( e );
}
}
}
private void parseLogBase( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
syncRepl.setLogBase( value );
}
}
private void parseLogFilter( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
syncRepl.setLogFilter( value );
}
}
private void parseSyncData( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
String value = getQuotedOrNotQuotedOptionValue( chars, pos, syncRepl, parserException );
if ( value != null )
{
try
{
syncRepl.setSyncData( SyncData.parse( value ) );
}
catch ( ParseException e )
{
parserException.addParseException( e );
}
}
}
private boolean findEqual( char[] chars, Position pos, SyncRepl syncRepl, SyncReplParserException parserException )
{
char c = Strings.charAt( chars, pos.start );
do
{
// Whitespace
if ( Character.isWhitespace( c ) )
{
pos.start++;
}
// '=' char
else if ( c == '=' )
{
pos.start++;
return true;
}
else
{
return false;
}
}
while ( ( c = Strings.charAt( chars, pos.start ) ) != '\0' );
return false;
}
private String getQuotedOrNotQuotedOptionValue( char[] chars, Position pos, SyncRepl syncRepl,
SyncReplParserException parserException )
{
if ( findEqual( chars, pos, syncRepl, parserException ) )
{
char quoteChar = '\0';
boolean isInQuotes = false;
char c = Strings.charAt( chars, pos.start );
char[] v = new char[chars.length - pos.start];
int current = 0;
do
{
if ( ( current == 0 ) && !isInQuotes )
{
// Whitespace
if ( Character.isWhitespace( c ) )
{
// We ignore all whitespaces until we find the start of the value
pos.start++;
continue;
}
// Double quotes (") or single quotes (')
else if ( ( c == '"' ) || ( c == '\'' ) )
{
isInQuotes = true;
quoteChar = c;
pos.start++;
continue;
}
// Any other char is part of a value
else
{
v[current++] = c;
pos.start++;
}
}
else
{
if ( isInQuotes )
{
// Double quotes (") or single quotes (')
if ( quoteChar == c )
{
isInQuotes = false;
pos.start++;
continue;
}
// Checking for escaped quotes
else if ( c == '\\' )
{
// Double quotes (")
if ( ( quoteChar == '"' ) && ( Strings.areEquals( chars, pos.start, "\\\"" ) >= 0 ) )
{
v[current++] = '"';
pos.start += 2;
continue;
}
// Single quotes (')
else if ( ( quoteChar == '\'' ) && ( Strings.areEquals( chars, pos.start, "\\'" ) >= 0 ) )
{
v[current++] = '\'';
pos.start += 2;
continue;
}
}
// Any other char is part of a value
else
{
v[current++] = c;
pos.start++;
}
}
else
{
// Whitespace
if ( Character.isWhitespace( c ) )
{
// Once we have found the start of the value, the first whitespace is the exit
break;
}
// Any other char is part of a value
else
{
v[current++] = c;
pos.start++;
}
}
}
}
while ( ( c = Strings.charAt( chars, pos.start ) ) != '\0' );
// Checking the resulting value
if ( current == 0 )
{
parserException.addParseException( new ParseException( "Couldn't find the value for option '"
+ KEYWORD_RID
+ "'.", pos.start ) );
return null;
}
char[] value = new char[current];
System.arraycopy( v, 0, value, 0, current );
// Getting the value as a String
return new String( value );
}
else
{
parserException.addParseException( new ParseException( "Couldn't find the value for option '" + KEYWORD_RID
+ "'.", pos.start ) );
return null;
}
}
}
|
googleapis/google-api-java-client-services | 36,496 | clients/google-api-services-content/v2.1/2.0.0/com/google/api/services/content/model/Promotion.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.content.model;
/**
* Represents a promotion. See the following articles for more details. * [Promotions feed
* specification](https://support.google.com/merchants/answer/2906014) * [Local promotions feed
* specification](https://support.google.com/merchants/answer/10146130) * [Promotions on Buy on
* Google product data specification](https://support.google.com/merchants/answer/9173673)
*
* <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 Content API for Shopping. 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 Promotion extends com.google.api.client.json.GenericJson {
/**
* Product filter by brand for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> brand;
/**
* Product filter by brand exclusion for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> brandExclusion;
/**
* Required. The content language used as part of the unique identifier. `en` content language is
* available for all target countries. `fr` content language is available for `CA` and `FR` target
* countries. `de` content language is available for `DE` target country. `nl` content language is
* available for `NL` target country. `it` content language is available for `IT` target country.
* `pt` content language is available for `BR` target country. `ja` content language is available
* for `JP` target country. `ko` content language is available for `KR` target country.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String contentLanguage;
/**
* Required. Coupon value type for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String couponValueType;
/**
* The custom redemption restriction for the promotion. If the `redemption_restriction` field is
* set to `CUSTOM`, this field must be set.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String customRedemptionRestriction;
/**
* Free gift description for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String freeGiftDescription;
/**
* Free gift item ID for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String freeGiftItemId;
/**
* Free gift value for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PriceAmount freeGiftValue;
/**
* Generic redemption code for the promotion. To be used with the `offerType` field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String genericRedemptionCode;
/**
* The number of items discounted in the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer getThisQuantityDiscounted;
/**
* Output only. The REST promotion ID to uniquely identify the promotion. Content API methods that
* operate on promotions take this as their `promotionId` parameter. The REST ID for a promotion
* is of the form channel:contentLanguage:targetCountry:promotionId The `channel` field has a
* value of `"online"`, `"in_store"`, or `"online_in_store"`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String id;
/**
* Product filter by item group ID for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> itemGroupId;
/**
* Product filter by item group ID exclusion for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> itemGroupIdExclusion;
/**
* Product filter by item ID for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> itemId;
/**
* Product filter by item ID exclusion for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> itemIdExclusion;
/**
* Maximum purchase quantity for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer limitQuantity;
/**
* Maximum purchase value for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PriceAmount limitValue;
/**
* Required. Long title for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String longTitle;
/**
* The maximum monetary discount a customer can receive for the promotion. This field is only
* supported with the `Percent off` coupon value type.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PriceAmount maxDiscountAmount;
/**
* Minimum purchase amount for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PriceAmount minimumPurchaseAmount;
/**
* Minimum purchase quantity for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer minimumPurchaseQuantity;
/**
* Cost cap for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PriceAmount moneyBudget;
/**
* The money off amount offered in the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PriceAmount moneyOffAmount;
/**
* Required. Type of the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String offerType;
/**
* Order limit for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer orderLimit;
/**
* The percentage discount offered in the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer percentOff;
/**
* Required. Applicability of the promotion to either all products or only specific products.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String productApplicability;
/**
* Product filter by product type for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> productType;
/**
* Product filter by product type exclusion for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> productTypeExclusion;
/**
* Destination ID for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> promotionDestinationIds;
/**
* String representation of the promotion display dates. Deprecated. Use
* `promotion_display_time_period` instead.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String promotionDisplayDates;
/**
* `TimePeriod` representation of the promotion's display dates.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TimePeriod promotionDisplayTimePeriod;
/**
* String representation of the promotion effective dates. Deprecated. Use
* `promotion_effective_time_period` instead.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String promotionEffectiveDates;
/**
* Required. `TimePeriod` representation of the promotion's effective dates.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TimePeriod promotionEffectiveTimePeriod;
/**
* Required. The user provided promotion ID to uniquely identify the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String promotionId;
/**
* Output only. The current status of the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PromotionPromotionStatus promotionStatus;
/**
* URL to the page on the merchant's site where the promotion shows. Local Inventory ads
* promotions throw an error if no promo url is included. URL is used to confirm that the
* promotion is valid and can be redeemed.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String promotionUrl;
/**
* Required. Redemption channel for the promotion. At least one channel is required.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> redemptionChannel;
/**
* The redemption restriction for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String redemptionRestriction;
/**
* Shipping service names for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> shippingServiceNames;
/**
* Whether the promotion applies to all stores, or only specified stores. Local Inventory ads
* promotions throw an error if no store applicability is included. An INVALID_ARGUMENT error is
* thrown if store_applicability is set to ALL_STORES and store_code or score_code_exclusion is
* set to a value.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String storeApplicability;
/**
* Store codes to include for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> storeCode;
/**
* Store codes to exclude for the promotion.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> storeCodeExclusion;
/**
* Required. The target country used as part of the unique identifier. Can be `AU`, `CA`, `DE`,
* `FR`, `GB`, `IN`, `US`, `BR`, `ES`, `NL`, `JP`, `IT` or `KR`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String targetCountry;
/**
* Product filter by brand for the promotion.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getBrand() {
return brand;
}
/**
* Product filter by brand for the promotion.
* @param brand brand or {@code null} for none
*/
public Promotion setBrand(java.util.List<java.lang.String> brand) {
this.brand = brand;
return this;
}
/**
* Product filter by brand exclusion for the promotion.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getBrandExclusion() {
return brandExclusion;
}
/**
* Product filter by brand exclusion for the promotion.
* @param brandExclusion brandExclusion or {@code null} for none
*/
public Promotion setBrandExclusion(java.util.List<java.lang.String> brandExclusion) {
this.brandExclusion = brandExclusion;
return this;
}
/**
* Required. The content language used as part of the unique identifier. `en` content language is
* available for all target countries. `fr` content language is available for `CA` and `FR` target
* countries. `de` content language is available for `DE` target country. `nl` content language is
* available for `NL` target country. `it` content language is available for `IT` target country.
* `pt` content language is available for `BR` target country. `ja` content language is available
* for `JP` target country. `ko` content language is available for `KR` target country.
* @return value or {@code null} for none
*/
public java.lang.String getContentLanguage() {
return contentLanguage;
}
/**
* Required. The content language used as part of the unique identifier. `en` content language is
* available for all target countries. `fr` content language is available for `CA` and `FR` target
* countries. `de` content language is available for `DE` target country. `nl` content language is
* available for `NL` target country. `it` content language is available for `IT` target country.
* `pt` content language is available for `BR` target country. `ja` content language is available
* for `JP` target country. `ko` content language is available for `KR` target country.
* @param contentLanguage contentLanguage or {@code null} for none
*/
public Promotion setContentLanguage(java.lang.String contentLanguage) {
this.contentLanguage = contentLanguage;
return this;
}
/**
* Required. Coupon value type for the promotion.
* @return value or {@code null} for none
*/
public java.lang.String getCouponValueType() {
return couponValueType;
}
/**
* Required. Coupon value type for the promotion.
* @param couponValueType couponValueType or {@code null} for none
*/
public Promotion setCouponValueType(java.lang.String couponValueType) {
this.couponValueType = couponValueType;
return this;
}
/**
* The custom redemption restriction for the promotion. If the `redemption_restriction` field is
* set to `CUSTOM`, this field must be set.
* @return value or {@code null} for none
*/
public java.lang.String getCustomRedemptionRestriction() {
return customRedemptionRestriction;
}
/**
* The custom redemption restriction for the promotion. If the `redemption_restriction` field is
* set to `CUSTOM`, this field must be set.
* @param customRedemptionRestriction customRedemptionRestriction or {@code null} for none
*/
public Promotion setCustomRedemptionRestriction(java.lang.String customRedemptionRestriction) {
this.customRedemptionRestriction = customRedemptionRestriction;
return this;
}
/**
* Free gift description for the promotion.
* @return value or {@code null} for none
*/
public java.lang.String getFreeGiftDescription() {
return freeGiftDescription;
}
/**
* Free gift description for the promotion.
* @param freeGiftDescription freeGiftDescription or {@code null} for none
*/
public Promotion setFreeGiftDescription(java.lang.String freeGiftDescription) {
this.freeGiftDescription = freeGiftDescription;
return this;
}
/**
* Free gift item ID for the promotion.
* @return value or {@code null} for none
*/
public java.lang.String getFreeGiftItemId() {
return freeGiftItemId;
}
/**
* Free gift item ID for the promotion.
* @param freeGiftItemId freeGiftItemId or {@code null} for none
*/
public Promotion setFreeGiftItemId(java.lang.String freeGiftItemId) {
this.freeGiftItemId = freeGiftItemId;
return this;
}
/**
* Free gift value for the promotion.
* @return value or {@code null} for none
*/
public PriceAmount getFreeGiftValue() {
return freeGiftValue;
}
/**
* Free gift value for the promotion.
* @param freeGiftValue freeGiftValue or {@code null} for none
*/
public Promotion setFreeGiftValue(PriceAmount freeGiftValue) {
this.freeGiftValue = freeGiftValue;
return this;
}
/**
* Generic redemption code for the promotion. To be used with the `offerType` field.
* @return value or {@code null} for none
*/
public java.lang.String getGenericRedemptionCode() {
return genericRedemptionCode;
}
/**
* Generic redemption code for the promotion. To be used with the `offerType` field.
* @param genericRedemptionCode genericRedemptionCode or {@code null} for none
*/
public Promotion setGenericRedemptionCode(java.lang.String genericRedemptionCode) {
this.genericRedemptionCode = genericRedemptionCode;
return this;
}
/**
* The number of items discounted in the promotion.
* @return value or {@code null} for none
*/
public java.lang.Integer getGetThisQuantityDiscounted() {
return getThisQuantityDiscounted;
}
/**
* The number of items discounted in the promotion.
* @param getThisQuantityDiscounted getThisQuantityDiscounted or {@code null} for none
*/
public Promotion setGetThisQuantityDiscounted(java.lang.Integer getThisQuantityDiscounted) {
this.getThisQuantityDiscounted = getThisQuantityDiscounted;
return this;
}
/**
* Output only. The REST promotion ID to uniquely identify the promotion. Content API methods that
* operate on promotions take this as their `promotionId` parameter. The REST ID for a promotion
* is of the form channel:contentLanguage:targetCountry:promotionId The `channel` field has a
* value of `"online"`, `"in_store"`, or `"online_in_store"`.
* @return value or {@code null} for none
*/
public java.lang.String getId() {
return id;
}
/**
* Output only. The REST promotion ID to uniquely identify the promotion. Content API methods that
* operate on promotions take this as their `promotionId` parameter. The REST ID for a promotion
* is of the form channel:contentLanguage:targetCountry:promotionId The `channel` field has a
* value of `"online"`, `"in_store"`, or `"online_in_store"`.
* @param id id or {@code null} for none
*/
public Promotion setId(java.lang.String id) {
this.id = id;
return this;
}
/**
* Product filter by item group ID for the promotion.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getItemGroupId() {
return itemGroupId;
}
/**
* Product filter by item group ID for the promotion.
* @param itemGroupId itemGroupId or {@code null} for none
*/
public Promotion setItemGroupId(java.util.List<java.lang.String> itemGroupId) {
this.itemGroupId = itemGroupId;
return this;
}
/**
* Product filter by item group ID exclusion for the promotion.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getItemGroupIdExclusion() {
return itemGroupIdExclusion;
}
/**
* Product filter by item group ID exclusion for the promotion.
* @param itemGroupIdExclusion itemGroupIdExclusion or {@code null} for none
*/
public Promotion setItemGroupIdExclusion(java.util.List<java.lang.String> itemGroupIdExclusion) {
this.itemGroupIdExclusion = itemGroupIdExclusion;
return this;
}
/**
* Product filter by item ID for the promotion.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getItemId() {
return itemId;
}
/**
* Product filter by item ID for the promotion.
* @param itemId itemId or {@code null} for none
*/
public Promotion setItemId(java.util.List<java.lang.String> itemId) {
this.itemId = itemId;
return this;
}
/**
* Product filter by item ID exclusion for the promotion.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getItemIdExclusion() {
return itemIdExclusion;
}
/**
* Product filter by item ID exclusion for the promotion.
* @param itemIdExclusion itemIdExclusion or {@code null} for none
*/
public Promotion setItemIdExclusion(java.util.List<java.lang.String> itemIdExclusion) {
this.itemIdExclusion = itemIdExclusion;
return this;
}
/**
* Maximum purchase quantity for the promotion.
* @return value or {@code null} for none
*/
public java.lang.Integer getLimitQuantity() {
return limitQuantity;
}
/**
* Maximum purchase quantity for the promotion.
* @param limitQuantity limitQuantity or {@code null} for none
*/
public Promotion setLimitQuantity(java.lang.Integer limitQuantity) {
this.limitQuantity = limitQuantity;
return this;
}
/**
* Maximum purchase value for the promotion.
* @return value or {@code null} for none
*/
public PriceAmount getLimitValue() {
return limitValue;
}
/**
* Maximum purchase value for the promotion.
* @param limitValue limitValue or {@code null} for none
*/
public Promotion setLimitValue(PriceAmount limitValue) {
this.limitValue = limitValue;
return this;
}
/**
* Required. Long title for the promotion.
* @return value or {@code null} for none
*/
public java.lang.String getLongTitle() {
return longTitle;
}
/**
* Required. Long title for the promotion.
* @param longTitle longTitle or {@code null} for none
*/
public Promotion setLongTitle(java.lang.String longTitle) {
this.longTitle = longTitle;
return this;
}
/**
* The maximum monetary discount a customer can receive for the promotion. This field is only
* supported with the `Percent off` coupon value type.
* @return value or {@code null} for none
*/
public PriceAmount getMaxDiscountAmount() {
return maxDiscountAmount;
}
/**
* The maximum monetary discount a customer can receive for the promotion. This field is only
* supported with the `Percent off` coupon value type.
* @param maxDiscountAmount maxDiscountAmount or {@code null} for none
*/
public Promotion setMaxDiscountAmount(PriceAmount maxDiscountAmount) {
this.maxDiscountAmount = maxDiscountAmount;
return this;
}
/**
* Minimum purchase amount for the promotion.
* @return value or {@code null} for none
*/
public PriceAmount getMinimumPurchaseAmount() {
return minimumPurchaseAmount;
}
/**
* Minimum purchase amount for the promotion.
* @param minimumPurchaseAmount minimumPurchaseAmount or {@code null} for none
*/
public Promotion setMinimumPurchaseAmount(PriceAmount minimumPurchaseAmount) {
this.minimumPurchaseAmount = minimumPurchaseAmount;
return this;
}
/**
* Minimum purchase quantity for the promotion.
* @return value or {@code null} for none
*/
public java.lang.Integer getMinimumPurchaseQuantity() {
return minimumPurchaseQuantity;
}
/**
* Minimum purchase quantity for the promotion.
* @param minimumPurchaseQuantity minimumPurchaseQuantity or {@code null} for none
*/
public Promotion setMinimumPurchaseQuantity(java.lang.Integer minimumPurchaseQuantity) {
this.minimumPurchaseQuantity = minimumPurchaseQuantity;
return this;
}
/**
* Cost cap for the promotion.
* @return value or {@code null} for none
*/
public PriceAmount getMoneyBudget() {
return moneyBudget;
}
/**
* Cost cap for the promotion.
* @param moneyBudget moneyBudget or {@code null} for none
*/
public Promotion setMoneyBudget(PriceAmount moneyBudget) {
this.moneyBudget = moneyBudget;
return this;
}
/**
* The money off amount offered in the promotion.
* @return value or {@code null} for none
*/
public PriceAmount getMoneyOffAmount() {
return moneyOffAmount;
}
/**
* The money off amount offered in the promotion.
* @param moneyOffAmount moneyOffAmount or {@code null} for none
*/
public Promotion setMoneyOffAmount(PriceAmount moneyOffAmount) {
this.moneyOffAmount = moneyOffAmount;
return this;
}
/**
* Required. Type of the promotion.
* @return value or {@code null} for none
*/
public java.lang.String getOfferType() {
return offerType;
}
/**
* Required. Type of the promotion.
* @param offerType offerType or {@code null} for none
*/
public Promotion setOfferType(java.lang.String offerType) {
this.offerType = offerType;
return this;
}
/**
* Order limit for the promotion.
* @return value or {@code null} for none
*/
public java.lang.Integer getOrderLimit() {
return orderLimit;
}
/**
* Order limit for the promotion.
* @param orderLimit orderLimit or {@code null} for none
*/
public Promotion setOrderLimit(java.lang.Integer orderLimit) {
this.orderLimit = orderLimit;
return this;
}
/**
* The percentage discount offered in the promotion.
* @return value or {@code null} for none
*/
public java.lang.Integer getPercentOff() {
return percentOff;
}
/**
* The percentage discount offered in the promotion.
* @param percentOff percentOff or {@code null} for none
*/
public Promotion setPercentOff(java.lang.Integer percentOff) {
this.percentOff = percentOff;
return this;
}
/**
* Required. Applicability of the promotion to either all products or only specific products.
* @return value or {@code null} for none
*/
public java.lang.String getProductApplicability() {
return productApplicability;
}
/**
* Required. Applicability of the promotion to either all products or only specific products.
* @param productApplicability productApplicability or {@code null} for none
*/
public Promotion setProductApplicability(java.lang.String productApplicability) {
this.productApplicability = productApplicability;
return this;
}
/**
* Product filter by product type for the promotion.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getProductType() {
return productType;
}
/**
* Product filter by product type for the promotion.
* @param productType productType or {@code null} for none
*/
public Promotion setProductType(java.util.List<java.lang.String> productType) {
this.productType = productType;
return this;
}
/**
* Product filter by product type exclusion for the promotion.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getProductTypeExclusion() {
return productTypeExclusion;
}
/**
* Product filter by product type exclusion for the promotion.
* @param productTypeExclusion productTypeExclusion or {@code null} for none
*/
public Promotion setProductTypeExclusion(java.util.List<java.lang.String> productTypeExclusion) {
this.productTypeExclusion = productTypeExclusion;
return this;
}
/**
* Destination ID for the promotion.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getPromotionDestinationIds() {
return promotionDestinationIds;
}
/**
* Destination ID for the promotion.
* @param promotionDestinationIds promotionDestinationIds or {@code null} for none
*/
public Promotion setPromotionDestinationIds(java.util.List<java.lang.String> promotionDestinationIds) {
this.promotionDestinationIds = promotionDestinationIds;
return this;
}
/**
* String representation of the promotion display dates. Deprecated. Use
* `promotion_display_time_period` instead.
* @return value or {@code null} for none
*/
public java.lang.String getPromotionDisplayDates() {
return promotionDisplayDates;
}
/**
* String representation of the promotion display dates. Deprecated. Use
* `promotion_display_time_period` instead.
* @param promotionDisplayDates promotionDisplayDates or {@code null} for none
*/
public Promotion setPromotionDisplayDates(java.lang.String promotionDisplayDates) {
this.promotionDisplayDates = promotionDisplayDates;
return this;
}
/**
* `TimePeriod` representation of the promotion's display dates.
* @return value or {@code null} for none
*/
public TimePeriod getPromotionDisplayTimePeriod() {
return promotionDisplayTimePeriod;
}
/**
* `TimePeriod` representation of the promotion's display dates.
* @param promotionDisplayTimePeriod promotionDisplayTimePeriod or {@code null} for none
*/
public Promotion setPromotionDisplayTimePeriod(TimePeriod promotionDisplayTimePeriod) {
this.promotionDisplayTimePeriod = promotionDisplayTimePeriod;
return this;
}
/**
* String representation of the promotion effective dates. Deprecated. Use
* `promotion_effective_time_period` instead.
* @return value or {@code null} for none
*/
public java.lang.String getPromotionEffectiveDates() {
return promotionEffectiveDates;
}
/**
* String representation of the promotion effective dates. Deprecated. Use
* `promotion_effective_time_period` instead.
* @param promotionEffectiveDates promotionEffectiveDates or {@code null} for none
*/
public Promotion setPromotionEffectiveDates(java.lang.String promotionEffectiveDates) {
this.promotionEffectiveDates = promotionEffectiveDates;
return this;
}
/**
* Required. `TimePeriod` representation of the promotion's effective dates.
* @return value or {@code null} for none
*/
public TimePeriod getPromotionEffectiveTimePeriod() {
return promotionEffectiveTimePeriod;
}
/**
* Required. `TimePeriod` representation of the promotion's effective dates.
* @param promotionEffectiveTimePeriod promotionEffectiveTimePeriod or {@code null} for none
*/
public Promotion setPromotionEffectiveTimePeriod(TimePeriod promotionEffectiveTimePeriod) {
this.promotionEffectiveTimePeriod = promotionEffectiveTimePeriod;
return this;
}
/**
* Required. The user provided promotion ID to uniquely identify the promotion.
* @return value or {@code null} for none
*/
public java.lang.String getPromotionId() {
return promotionId;
}
/**
* Required. The user provided promotion ID to uniquely identify the promotion.
* @param promotionId promotionId or {@code null} for none
*/
public Promotion setPromotionId(java.lang.String promotionId) {
this.promotionId = promotionId;
return this;
}
/**
* Output only. The current status of the promotion.
* @return value or {@code null} for none
*/
public PromotionPromotionStatus getPromotionStatus() {
return promotionStatus;
}
/**
* Output only. The current status of the promotion.
* @param promotionStatus promotionStatus or {@code null} for none
*/
public Promotion setPromotionStatus(PromotionPromotionStatus promotionStatus) {
this.promotionStatus = promotionStatus;
return this;
}
/**
* URL to the page on the merchant's site where the promotion shows. Local Inventory ads
* promotions throw an error if no promo url is included. URL is used to confirm that the
* promotion is valid and can be redeemed.
* @return value or {@code null} for none
*/
public java.lang.String getPromotionUrl() {
return promotionUrl;
}
/**
* URL to the page on the merchant's site where the promotion shows. Local Inventory ads
* promotions throw an error if no promo url is included. URL is used to confirm that the
* promotion is valid and can be redeemed.
* @param promotionUrl promotionUrl or {@code null} for none
*/
public Promotion setPromotionUrl(java.lang.String promotionUrl) {
this.promotionUrl = promotionUrl;
return this;
}
/**
* Required. Redemption channel for the promotion. At least one channel is required.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getRedemptionChannel() {
return redemptionChannel;
}
/**
* Required. Redemption channel for the promotion. At least one channel is required.
* @param redemptionChannel redemptionChannel or {@code null} for none
*/
public Promotion setRedemptionChannel(java.util.List<java.lang.String> redemptionChannel) {
this.redemptionChannel = redemptionChannel;
return this;
}
/**
* The redemption restriction for the promotion.
* @return value or {@code null} for none
*/
public java.lang.String getRedemptionRestriction() {
return redemptionRestriction;
}
/**
* The redemption restriction for the promotion.
* @param redemptionRestriction redemptionRestriction or {@code null} for none
*/
public Promotion setRedemptionRestriction(java.lang.String redemptionRestriction) {
this.redemptionRestriction = redemptionRestriction;
return this;
}
/**
* Shipping service names for the promotion.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getShippingServiceNames() {
return shippingServiceNames;
}
/**
* Shipping service names for the promotion.
* @param shippingServiceNames shippingServiceNames or {@code null} for none
*/
public Promotion setShippingServiceNames(java.util.List<java.lang.String> shippingServiceNames) {
this.shippingServiceNames = shippingServiceNames;
return this;
}
/**
* Whether the promotion applies to all stores, or only specified stores. Local Inventory ads
* promotions throw an error if no store applicability is included. An INVALID_ARGUMENT error is
* thrown if store_applicability is set to ALL_STORES and store_code or score_code_exclusion is
* set to a value.
* @return value or {@code null} for none
*/
public java.lang.String getStoreApplicability() {
return storeApplicability;
}
/**
* Whether the promotion applies to all stores, or only specified stores. Local Inventory ads
* promotions throw an error if no store applicability is included. An INVALID_ARGUMENT error is
* thrown if store_applicability is set to ALL_STORES and store_code or score_code_exclusion is
* set to a value.
* @param storeApplicability storeApplicability or {@code null} for none
*/
public Promotion setStoreApplicability(java.lang.String storeApplicability) {
this.storeApplicability = storeApplicability;
return this;
}
/**
* Store codes to include for the promotion.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getStoreCode() {
return storeCode;
}
/**
* Store codes to include for the promotion.
* @param storeCode storeCode or {@code null} for none
*/
public Promotion setStoreCode(java.util.List<java.lang.String> storeCode) {
this.storeCode = storeCode;
return this;
}
/**
* Store codes to exclude for the promotion.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getStoreCodeExclusion() {
return storeCodeExclusion;
}
/**
* Store codes to exclude for the promotion.
* @param storeCodeExclusion storeCodeExclusion or {@code null} for none
*/
public Promotion setStoreCodeExclusion(java.util.List<java.lang.String> storeCodeExclusion) {
this.storeCodeExclusion = storeCodeExclusion;
return this;
}
/**
* Required. The target country used as part of the unique identifier. Can be `AU`, `CA`, `DE`,
* `FR`, `GB`, `IN`, `US`, `BR`, `ES`, `NL`, `JP`, `IT` or `KR`.
* @return value or {@code null} for none
*/
public java.lang.String getTargetCountry() {
return targetCountry;
}
/**
* Required. The target country used as part of the unique identifier. Can be `AU`, `CA`, `DE`,
* `FR`, `GB`, `IN`, `US`, `BR`, `ES`, `NL`, `JP`, `IT` or `KR`.
* @param targetCountry targetCountry or {@code null} for none
*/
public Promotion setTargetCountry(java.lang.String targetCountry) {
this.targetCountry = targetCountry;
return this;
}
@Override
public Promotion set(String fieldName, Object value) {
return (Promotion) super.set(fieldName, value);
}
@Override
public Promotion clone() {
return (Promotion) super.clone();
}
}
|
googleapis/google-cloud-java | 36,500 | java-speech/proto-google-cloud-speech-v1/src/main/java/com/google/cloud/speech/v1/ListCustomClassesResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/speech/v1/cloud_speech_adaptation.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.speech.v1;
/**
*
*
* <pre>
* Message returned to the client by the `ListCustomClasses` method.
* </pre>
*
* Protobuf type {@code google.cloud.speech.v1.ListCustomClassesResponse}
*/
public final class ListCustomClassesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.speech.v1.ListCustomClassesResponse)
ListCustomClassesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListCustomClassesResponse.newBuilder() to construct.
private ListCustomClassesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListCustomClassesResponse() {
customClasses_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListCustomClassesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.speech.v1.SpeechAdaptationProto
.internal_static_google_cloud_speech_v1_ListCustomClassesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.speech.v1.SpeechAdaptationProto
.internal_static_google_cloud_speech_v1_ListCustomClassesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.speech.v1.ListCustomClassesResponse.class,
com.google.cloud.speech.v1.ListCustomClassesResponse.Builder.class);
}
public static final int CUSTOM_CLASSES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.speech.v1.CustomClass> customClasses_;
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.speech.v1.CustomClass> getCustomClassesList() {
return customClasses_;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.speech.v1.CustomClassOrBuilder>
getCustomClassesOrBuilderList() {
return customClasses_;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
@java.lang.Override
public int getCustomClassesCount() {
return customClasses_.size();
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
@java.lang.Override
public com.google.cloud.speech.v1.CustomClass getCustomClasses(int index) {
return customClasses_.get(index);
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
@java.lang.Override
public com.google.cloud.speech.v1.CustomClassOrBuilder getCustomClassesOrBuilder(int index) {
return customClasses_.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 < customClasses_.size(); i++) {
output.writeMessage(1, customClasses_.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 < customClasses_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, customClasses_.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.speech.v1.ListCustomClassesResponse)) {
return super.equals(obj);
}
com.google.cloud.speech.v1.ListCustomClassesResponse other =
(com.google.cloud.speech.v1.ListCustomClassesResponse) obj;
if (!getCustomClassesList().equals(other.getCustomClassesList())) 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 (getCustomClassesCount() > 0) {
hash = (37 * hash) + CUSTOM_CLASSES_FIELD_NUMBER;
hash = (53 * hash) + getCustomClassesList().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.speech.v1.ListCustomClassesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.speech.v1.ListCustomClassesResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.speech.v1.ListCustomClassesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.speech.v1.ListCustomClassesResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.speech.v1.ListCustomClassesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.speech.v1.ListCustomClassesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.speech.v1.ListCustomClassesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.speech.v1.ListCustomClassesResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.speech.v1.ListCustomClassesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.speech.v1.ListCustomClassesResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.speech.v1.ListCustomClassesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.speech.v1.ListCustomClassesResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.speech.v1.ListCustomClassesResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Message returned to the client by the `ListCustomClasses` method.
* </pre>
*
* Protobuf type {@code google.cloud.speech.v1.ListCustomClassesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.speech.v1.ListCustomClassesResponse)
com.google.cloud.speech.v1.ListCustomClassesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.speech.v1.SpeechAdaptationProto
.internal_static_google_cloud_speech_v1_ListCustomClassesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.speech.v1.SpeechAdaptationProto
.internal_static_google_cloud_speech_v1_ListCustomClassesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.speech.v1.ListCustomClassesResponse.class,
com.google.cloud.speech.v1.ListCustomClassesResponse.Builder.class);
}
// Construct using com.google.cloud.speech.v1.ListCustomClassesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (customClassesBuilder_ == null) {
customClasses_ = java.util.Collections.emptyList();
} else {
customClasses_ = null;
customClassesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.speech.v1.SpeechAdaptationProto
.internal_static_google_cloud_speech_v1_ListCustomClassesResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.speech.v1.ListCustomClassesResponse getDefaultInstanceForType() {
return com.google.cloud.speech.v1.ListCustomClassesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.speech.v1.ListCustomClassesResponse build() {
com.google.cloud.speech.v1.ListCustomClassesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.speech.v1.ListCustomClassesResponse buildPartial() {
com.google.cloud.speech.v1.ListCustomClassesResponse result =
new com.google.cloud.speech.v1.ListCustomClassesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.speech.v1.ListCustomClassesResponse result) {
if (customClassesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
customClasses_ = java.util.Collections.unmodifiableList(customClasses_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.customClasses_ = customClasses_;
} else {
result.customClasses_ = customClassesBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.speech.v1.ListCustomClassesResponse 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.speech.v1.ListCustomClassesResponse) {
return mergeFrom((com.google.cloud.speech.v1.ListCustomClassesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.speech.v1.ListCustomClassesResponse other) {
if (other == com.google.cloud.speech.v1.ListCustomClassesResponse.getDefaultInstance())
return this;
if (customClassesBuilder_ == null) {
if (!other.customClasses_.isEmpty()) {
if (customClasses_.isEmpty()) {
customClasses_ = other.customClasses_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureCustomClassesIsMutable();
customClasses_.addAll(other.customClasses_);
}
onChanged();
}
} else {
if (!other.customClasses_.isEmpty()) {
if (customClassesBuilder_.isEmpty()) {
customClassesBuilder_.dispose();
customClassesBuilder_ = null;
customClasses_ = other.customClasses_;
bitField0_ = (bitField0_ & ~0x00000001);
customClassesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getCustomClassesFieldBuilder()
: null;
} else {
customClassesBuilder_.addAllMessages(other.customClasses_);
}
}
}
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.speech.v1.CustomClass m =
input.readMessage(
com.google.cloud.speech.v1.CustomClass.parser(), extensionRegistry);
if (customClassesBuilder_ == null) {
ensureCustomClassesIsMutable();
customClasses_.add(m);
} else {
customClassesBuilder_.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.speech.v1.CustomClass> customClasses_ =
java.util.Collections.emptyList();
private void ensureCustomClassesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
customClasses_ =
new java.util.ArrayList<com.google.cloud.speech.v1.CustomClass>(customClasses_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.speech.v1.CustomClass,
com.google.cloud.speech.v1.CustomClass.Builder,
com.google.cloud.speech.v1.CustomClassOrBuilder>
customClassesBuilder_;
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public java.util.List<com.google.cloud.speech.v1.CustomClass> getCustomClassesList() {
if (customClassesBuilder_ == null) {
return java.util.Collections.unmodifiableList(customClasses_);
} else {
return customClassesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public int getCustomClassesCount() {
if (customClassesBuilder_ == null) {
return customClasses_.size();
} else {
return customClassesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public com.google.cloud.speech.v1.CustomClass getCustomClasses(int index) {
if (customClassesBuilder_ == null) {
return customClasses_.get(index);
} else {
return customClassesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public Builder setCustomClasses(int index, com.google.cloud.speech.v1.CustomClass value) {
if (customClassesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCustomClassesIsMutable();
customClasses_.set(index, value);
onChanged();
} else {
customClassesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public Builder setCustomClasses(
int index, com.google.cloud.speech.v1.CustomClass.Builder builderForValue) {
if (customClassesBuilder_ == null) {
ensureCustomClassesIsMutable();
customClasses_.set(index, builderForValue.build());
onChanged();
} else {
customClassesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public Builder addCustomClasses(com.google.cloud.speech.v1.CustomClass value) {
if (customClassesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCustomClassesIsMutable();
customClasses_.add(value);
onChanged();
} else {
customClassesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public Builder addCustomClasses(int index, com.google.cloud.speech.v1.CustomClass value) {
if (customClassesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCustomClassesIsMutable();
customClasses_.add(index, value);
onChanged();
} else {
customClassesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public Builder addCustomClasses(
com.google.cloud.speech.v1.CustomClass.Builder builderForValue) {
if (customClassesBuilder_ == null) {
ensureCustomClassesIsMutable();
customClasses_.add(builderForValue.build());
onChanged();
} else {
customClassesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public Builder addCustomClasses(
int index, com.google.cloud.speech.v1.CustomClass.Builder builderForValue) {
if (customClassesBuilder_ == null) {
ensureCustomClassesIsMutable();
customClasses_.add(index, builderForValue.build());
onChanged();
} else {
customClassesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public Builder addAllCustomClasses(
java.lang.Iterable<? extends com.google.cloud.speech.v1.CustomClass> values) {
if (customClassesBuilder_ == null) {
ensureCustomClassesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, customClasses_);
onChanged();
} else {
customClassesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public Builder clearCustomClasses() {
if (customClassesBuilder_ == null) {
customClasses_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
customClassesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public Builder removeCustomClasses(int index) {
if (customClassesBuilder_ == null) {
ensureCustomClassesIsMutable();
customClasses_.remove(index);
onChanged();
} else {
customClassesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public com.google.cloud.speech.v1.CustomClass.Builder getCustomClassesBuilder(int index) {
return getCustomClassesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public com.google.cloud.speech.v1.CustomClassOrBuilder getCustomClassesOrBuilder(int index) {
if (customClassesBuilder_ == null) {
return customClasses_.get(index);
} else {
return customClassesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public java.util.List<? extends com.google.cloud.speech.v1.CustomClassOrBuilder>
getCustomClassesOrBuilderList() {
if (customClassesBuilder_ != null) {
return customClassesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(customClasses_);
}
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public com.google.cloud.speech.v1.CustomClass.Builder addCustomClassesBuilder() {
return getCustomClassesFieldBuilder()
.addBuilder(com.google.cloud.speech.v1.CustomClass.getDefaultInstance());
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public com.google.cloud.speech.v1.CustomClass.Builder addCustomClassesBuilder(int index) {
return getCustomClassesFieldBuilder()
.addBuilder(index, com.google.cloud.speech.v1.CustomClass.getDefaultInstance());
}
/**
*
*
* <pre>
* The custom classes.
* </pre>
*
* <code>repeated .google.cloud.speech.v1.CustomClass custom_classes = 1;</code>
*/
public java.util.List<com.google.cloud.speech.v1.CustomClass.Builder>
getCustomClassesBuilderList() {
return getCustomClassesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.speech.v1.CustomClass,
com.google.cloud.speech.v1.CustomClass.Builder,
com.google.cloud.speech.v1.CustomClassOrBuilder>
getCustomClassesFieldBuilder() {
if (customClassesBuilder_ == null) {
customClassesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.speech.v1.CustomClass,
com.google.cloud.speech.v1.CustomClass.Builder,
com.google.cloud.speech.v1.CustomClassOrBuilder>(
customClasses_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
customClasses_ = null;
}
return customClassesBuilder_;
}
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.speech.v1.ListCustomClassesResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.speech.v1.ListCustomClassesResponse)
private static final com.google.cloud.speech.v1.ListCustomClassesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.speech.v1.ListCustomClassesResponse();
}
public static com.google.cloud.speech.v1.ListCustomClassesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListCustomClassesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListCustomClassesResponse>() {
@java.lang.Override
public ListCustomClassesResponse 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<ListCustomClassesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListCustomClassesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.speech.v1.ListCustomClassesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,592 | java-service-management/proto-google-cloud-service-management-v1/src/main/java/com/google/api/servicemanagement/v1/ChangeReport.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/resources.proto
// Protobuf Java Version: 3.25.8
package com.google.api.servicemanagement.v1;
/**
*
*
* <pre>
* Change report associated with a particular service configuration.
*
* It contains a list of ConfigChanges based on the comparison between
* two service configurations.
* </pre>
*
* Protobuf type {@code google.api.servicemanagement.v1.ChangeReport}
*/
public final class ChangeReport extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.api.servicemanagement.v1.ChangeReport)
ChangeReportOrBuilder {
private static final long serialVersionUID = 0L;
// Use ChangeReport.newBuilder() to construct.
private ChangeReport(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ChangeReport() {
configChanges_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ChangeReport();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.api.servicemanagement.v1.ResourcesProto
.internal_static_google_api_servicemanagement_v1_ChangeReport_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.api.servicemanagement.v1.ResourcesProto
.internal_static_google_api_servicemanagement_v1_ChangeReport_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.api.servicemanagement.v1.ChangeReport.class,
com.google.api.servicemanagement.v1.ChangeReport.Builder.class);
}
public static final int CONFIG_CHANGES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.api.ConfigChange> configChanges_;
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.api.ConfigChange> getConfigChangesList() {
return configChanges_;
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.api.ConfigChangeOrBuilder>
getConfigChangesOrBuilderList() {
return configChanges_;
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
@java.lang.Override
public int getConfigChangesCount() {
return configChanges_.size();
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
@java.lang.Override
public com.google.api.ConfigChange getConfigChanges(int index) {
return configChanges_.get(index);
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
@java.lang.Override
public com.google.api.ConfigChangeOrBuilder getConfigChangesOrBuilder(int index) {
return configChanges_.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 < configChanges_.size(); i++) {
output.writeMessage(1, configChanges_.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 < configChanges_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, configChanges_.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.api.servicemanagement.v1.ChangeReport)) {
return super.equals(obj);
}
com.google.api.servicemanagement.v1.ChangeReport other =
(com.google.api.servicemanagement.v1.ChangeReport) obj;
if (!getConfigChangesList().equals(other.getConfigChangesList())) 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 (getConfigChangesCount() > 0) {
hash = (37 * hash) + CONFIG_CHANGES_FIELD_NUMBER;
hash = (53 * hash) + getConfigChangesList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.api.servicemanagement.v1.ChangeReport parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.servicemanagement.v1.ChangeReport 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.ChangeReport parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.servicemanagement.v1.ChangeReport 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.ChangeReport parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.servicemanagement.v1.ChangeReport 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.ChangeReport parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.api.servicemanagement.v1.ChangeReport 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.ChangeReport parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.api.servicemanagement.v1.ChangeReport 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.ChangeReport 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.ChangeReport 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.ChangeReport 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>
* Change report associated with a particular service configuration.
*
* It contains a list of ConfigChanges based on the comparison between
* two service configurations.
* </pre>
*
* Protobuf type {@code google.api.servicemanagement.v1.ChangeReport}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.api.servicemanagement.v1.ChangeReport)
com.google.api.servicemanagement.v1.ChangeReportOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.api.servicemanagement.v1.ResourcesProto
.internal_static_google_api_servicemanagement_v1_ChangeReport_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.api.servicemanagement.v1.ResourcesProto
.internal_static_google_api_servicemanagement_v1_ChangeReport_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.api.servicemanagement.v1.ChangeReport.class,
com.google.api.servicemanagement.v1.ChangeReport.Builder.class);
}
// Construct using com.google.api.servicemanagement.v1.ChangeReport.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (configChangesBuilder_ == null) {
configChanges_ = java.util.Collections.emptyList();
} else {
configChanges_ = null;
configChangesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.api.servicemanagement.v1.ResourcesProto
.internal_static_google_api_servicemanagement_v1_ChangeReport_descriptor;
}
@java.lang.Override
public com.google.api.servicemanagement.v1.ChangeReport getDefaultInstanceForType() {
return com.google.api.servicemanagement.v1.ChangeReport.getDefaultInstance();
}
@java.lang.Override
public com.google.api.servicemanagement.v1.ChangeReport build() {
com.google.api.servicemanagement.v1.ChangeReport result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.api.servicemanagement.v1.ChangeReport buildPartial() {
com.google.api.servicemanagement.v1.ChangeReport result =
new com.google.api.servicemanagement.v1.ChangeReport(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.api.servicemanagement.v1.ChangeReport result) {
if (configChangesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
configChanges_ = java.util.Collections.unmodifiableList(configChanges_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.configChanges_ = configChanges_;
} else {
result.configChanges_ = configChangesBuilder_.build();
}
}
private void buildPartial0(com.google.api.servicemanagement.v1.ChangeReport 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.api.servicemanagement.v1.ChangeReport) {
return mergeFrom((com.google.api.servicemanagement.v1.ChangeReport) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.api.servicemanagement.v1.ChangeReport other) {
if (other == com.google.api.servicemanagement.v1.ChangeReport.getDefaultInstance())
return this;
if (configChangesBuilder_ == null) {
if (!other.configChanges_.isEmpty()) {
if (configChanges_.isEmpty()) {
configChanges_ = other.configChanges_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureConfigChangesIsMutable();
configChanges_.addAll(other.configChanges_);
}
onChanged();
}
} else {
if (!other.configChanges_.isEmpty()) {
if (configChangesBuilder_.isEmpty()) {
configChangesBuilder_.dispose();
configChangesBuilder_ = null;
configChanges_ = other.configChanges_;
bitField0_ = (bitField0_ & ~0x00000001);
configChangesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getConfigChangesFieldBuilder()
: null;
} else {
configChangesBuilder_.addAllMessages(other.configChanges_);
}
}
}
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.api.ConfigChange m =
input.readMessage(com.google.api.ConfigChange.parser(), extensionRegistry);
if (configChangesBuilder_ == null) {
ensureConfigChangesIsMutable();
configChanges_.add(m);
} else {
configChangesBuilder_.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.api.ConfigChange> configChanges_ =
java.util.Collections.emptyList();
private void ensureConfigChangesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
configChanges_ = new java.util.ArrayList<com.google.api.ConfigChange>(configChanges_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.api.ConfigChange,
com.google.api.ConfigChange.Builder,
com.google.api.ConfigChangeOrBuilder>
configChangesBuilder_;
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public java.util.List<com.google.api.ConfigChange> getConfigChangesList() {
if (configChangesBuilder_ == null) {
return java.util.Collections.unmodifiableList(configChanges_);
} else {
return configChangesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public int getConfigChangesCount() {
if (configChangesBuilder_ == null) {
return configChanges_.size();
} else {
return configChangesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public com.google.api.ConfigChange getConfigChanges(int index) {
if (configChangesBuilder_ == null) {
return configChanges_.get(index);
} else {
return configChangesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public Builder setConfigChanges(int index, com.google.api.ConfigChange value) {
if (configChangesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureConfigChangesIsMutable();
configChanges_.set(index, value);
onChanged();
} else {
configChangesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public Builder setConfigChanges(
int index, com.google.api.ConfigChange.Builder builderForValue) {
if (configChangesBuilder_ == null) {
ensureConfigChangesIsMutable();
configChanges_.set(index, builderForValue.build());
onChanged();
} else {
configChangesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public Builder addConfigChanges(com.google.api.ConfigChange value) {
if (configChangesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureConfigChangesIsMutable();
configChanges_.add(value);
onChanged();
} else {
configChangesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public Builder addConfigChanges(int index, com.google.api.ConfigChange value) {
if (configChangesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureConfigChangesIsMutable();
configChanges_.add(index, value);
onChanged();
} else {
configChangesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public Builder addConfigChanges(com.google.api.ConfigChange.Builder builderForValue) {
if (configChangesBuilder_ == null) {
ensureConfigChangesIsMutable();
configChanges_.add(builderForValue.build());
onChanged();
} else {
configChangesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public Builder addConfigChanges(
int index, com.google.api.ConfigChange.Builder builderForValue) {
if (configChangesBuilder_ == null) {
ensureConfigChangesIsMutable();
configChanges_.add(index, builderForValue.build());
onChanged();
} else {
configChangesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public Builder addAllConfigChanges(
java.lang.Iterable<? extends com.google.api.ConfigChange> values) {
if (configChangesBuilder_ == null) {
ensureConfigChangesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, configChanges_);
onChanged();
} else {
configChangesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public Builder clearConfigChanges() {
if (configChangesBuilder_ == null) {
configChanges_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
configChangesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public Builder removeConfigChanges(int index) {
if (configChangesBuilder_ == null) {
ensureConfigChangesIsMutable();
configChanges_.remove(index);
onChanged();
} else {
configChangesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public com.google.api.ConfigChange.Builder getConfigChangesBuilder(int index) {
return getConfigChangesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public com.google.api.ConfigChangeOrBuilder getConfigChangesOrBuilder(int index) {
if (configChangesBuilder_ == null) {
return configChanges_.get(index);
} else {
return configChangesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public java.util.List<? extends com.google.api.ConfigChangeOrBuilder>
getConfigChangesOrBuilderList() {
if (configChangesBuilder_ != null) {
return configChangesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(configChanges_);
}
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public com.google.api.ConfigChange.Builder addConfigChangesBuilder() {
return getConfigChangesFieldBuilder()
.addBuilder(com.google.api.ConfigChange.getDefaultInstance());
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public com.google.api.ConfigChange.Builder addConfigChangesBuilder(int index) {
return getConfigChangesFieldBuilder()
.addBuilder(index, com.google.api.ConfigChange.getDefaultInstance());
}
/**
*
*
* <pre>
* List of changes between two service configurations.
* The changes will be alphabetically sorted based on the identifier
* of each change.
* A ConfigChange identifier is a dot separated path to the configuration.
* Example: visibility.rules[selector='LibraryService.CreateBook'].restriction
* </pre>
*
* <code>repeated .google.api.ConfigChange config_changes = 1;</code>
*/
public java.util.List<com.google.api.ConfigChange.Builder> getConfigChangesBuilderList() {
return getConfigChangesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.api.ConfigChange,
com.google.api.ConfigChange.Builder,
com.google.api.ConfigChangeOrBuilder>
getConfigChangesFieldBuilder() {
if (configChangesBuilder_ == null) {
configChangesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.api.ConfigChange,
com.google.api.ConfigChange.Builder,
com.google.api.ConfigChangeOrBuilder>(
configChanges_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
configChanges_ = null;
}
return configChangesBuilder_;
}
@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.ChangeReport)
}
// @@protoc_insertion_point(class_scope:google.api.servicemanagement.v1.ChangeReport)
private static final com.google.api.servicemanagement.v1.ChangeReport DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.api.servicemanagement.v1.ChangeReport();
}
public static com.google.api.servicemanagement.v1.ChangeReport getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ChangeReport> PARSER =
new com.google.protobuf.AbstractParser<ChangeReport>() {
@java.lang.Override
public ChangeReport 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<ChangeReport> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ChangeReport> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.api.servicemanagement.v1.ChangeReport getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-api-java-client-services | 36,607 | clients/google-api-services-redis/v1beta1/1.31.0/com/google/api/services/redis/v1beta1/model/Instance.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.redis.v1beta1.model;
/**
* A Memorystore for Redis instance.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Google Cloud Memorystore for Redis 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 Instance extends com.google.api.client.json.GenericJson {
/**
* Optional. If specified, at least one node will be provisioned in this zone in addition to the
* zone specified in location_id. Only applicable to standard tier. If provided, it must be a
* different zone from the one provided in [location_id]. Additional nodes beyond the first 2 will
* be placed in zones selected by the service.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String alternativeLocationId;
/**
* Optional. Indicates whether OSS Redis AUTH is enabled for the instance. If set to "true" AUTH
* is enabled on the instance. Default value is "false" meaning AUTH is disabled.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean authEnabled;
/**
* Optional. The full name of the Google Compute Engine
* [network](https://cloud.google.com/vpc/docs/vpc) to which the instance is connected. If left
* unspecified, the `default` network will be used.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String authorizedNetwork;
/**
* Optional. The available maintenance versions that an instance could update to.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> availableMaintenanceVersions;
/**
* Optional. The network connect mode of the Redis instance. If not provided, the connect mode
* defaults to DIRECT_PEERING.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String connectMode;
/**
* Output only. The time the instance was created.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String createTime;
/**
* Output only. The current zone where the Redis primary node is located. In basic tier, this will
* always be the same as [location_id]. In standard tier, this can be the zone of any node in the
* instance.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String currentLocationId;
/**
* Optional. The KMS key reference that the customer provides when trying to create the instance.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String customerManagedKey;
/**
* An arbitrary and optional user-provided name for the instance.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String displayName;
/**
* Output only. Hostname or IP address of the exposed Redis endpoint used by clients to connect to
* the service.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String host;
/**
* Resource labels to represent user provided metadata
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, java.lang.String> labels;
/**
* Optional. The zone where the instance will be provisioned. If not provided, the service will
* choose a zone from the specified region for the instance. For standard tier, additional nodes
* will be added across multiple zones for protection against zonal failures. If specified, at
* least one node will be provisioned in this zone.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String locationId;
/**
* Optional. The maintenance policy for the instance. If not provided, maintenance events can be
* performed at any time.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private MaintenancePolicy maintenancePolicy;
/**
* Output only. Date and time of upcoming maintenance events which have been scheduled.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private MaintenanceSchedule maintenanceSchedule;
/**
* Optional. The self service update maintenance version. The version is date based such as
* "20210712_00_00".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String maintenanceVersion;
/**
* Required. Redis memory size in GiB.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer memorySizeGb;
/**
* Required. Unique name of the resource in this scope including project and location using the
* form: `projects/{project_id}/locations/{location_id}/instances/{instance_id}` Note: Redis
* instances are managed and addressed at regional level so location_id here refers to a GCP
* region; however, users may choose which specific zone (or collection of zones for cross-zone
* instances) an instance should be provisioned in. Refer to location_id and
* alternative_location_id fields for more details.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Output only. Info per node.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<NodeInfo> nodes;
/**
* Optional. Persistence configuration parameters
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private PersistenceConfig persistenceConfig;
/**
* Output only. Cloud IAM identity used by import / export operations to transfer data to/from
* Cloud Storage. Format is "serviceAccount:". The value may change over time for a given instance
* so should be checked before each import/export operation.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String persistenceIamIdentity;
/**
* Output only. The port number of the exposed Redis endpoint.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer port;
/**
* Output only. Hostname or IP address of the exposed readonly Redis endpoint. Standard tier only.
* Targets all healthy replica nodes in instance. Replication is asynchronous and replica nodes
* will exhibit some lag behind the primary. Write requests must target 'host'.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String readEndpoint;
/**
* Output only. The port number of the exposed readonly redis endpoint. Standard tier only. Write
* requests should target 'port'.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer readEndpointPort;
/**
* Optional. Read replicas mode for the instance. Defaults to READ_REPLICAS_DISABLED.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String readReplicasMode;
/**
* Optional. Redis configuration parameters, according to http://redis.io/topics/config.
* Currently, the only supported parameters are: Redis version 3.2 and newer: * maxmemory-policy *
* notify-keyspace-events Redis version 4.0 and newer: * activedefrag * lfu-decay-time * lfu-log-
* factor * maxmemory-gb Redis version 5.0 and newer: * stream-node-max-bytes * stream-node-max-
* entries
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, java.lang.String> redisConfigs;
/**
* Optional. The version of Redis software. If not provided, latest supported version will be
* used. Currently, the supported values are: * `REDIS_3_2` for Redis 3.2 compatibility *
* `REDIS_4_0` for Redis 4.0 compatibility (default) * `REDIS_5_0` for Redis 5.0 compatibility *
* `REDIS_6_X` for Redis 6.x compatibility
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String redisVersion;
/**
* Optional. The number of replica nodes. The valid range for the Standard Tier with read replicas
* enabled is [1-5] and defaults to 2. If read replicas are not enabled for a Standard Tier
* instance, the only valid value is 1 and the default is 1. The valid value for basic tier is 0
* and the default is also 0.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer replicaCount;
/**
* Optional. For DIRECT_PEERING mode, the CIDR range of internal addresses that are reserved for
* this instance. Range must be unique and non-overlapping with existing subnets in an authorized
* network. For PRIVATE_SERVICE_ACCESS mode, the name of one allocated IP address ranges
* associated with this private service access connection. If not provided, the service will
* choose an unused /29 block, for example, 10.0.0.0/29 or 192.168.0.0/29. For
* READ_REPLICAS_ENABLED the default block size is /28.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String reservedIpRange;
/**
* Optional. Additional IP range for node placement. Required when enabling read replicas on an
* existing instance. For DIRECT_PEERING mode value must be a CIDR range of size /28, or "auto".
* For PRIVATE_SERVICE_ACCESS mode value must be the name of an allocated address range associated
* with the private service access connection, or "auto".
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String secondaryIpRange;
/**
* Output only. List of server CA certificates for the instance.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<TlsCertificate> serverCaCerts;
/**
* Output only. The current state of this instance.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String state;
/**
* Output only. Additional information about the current status of this instance, if available.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String statusMessage;
/**
* Optional. reasons that causes instance in "SUSPENDED" state.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> suspensionReasons;
/**
* Required. The service tier of the instance.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String tier;
/**
* Optional. The TLS mode of the Redis instance. If not provided, TLS is disabled for the
* instance.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String transitEncryptionMode;
/**
* Optional. If specified, at least one node will be provisioned in this zone in addition to the
* zone specified in location_id. Only applicable to standard tier. If provided, it must be a
* different zone from the one provided in [location_id]. Additional nodes beyond the first 2 will
* be placed in zones selected by the service.
* @return value or {@code null} for none
*/
public java.lang.String getAlternativeLocationId() {
return alternativeLocationId;
}
/**
* Optional. If specified, at least one node will be provisioned in this zone in addition to the
* zone specified in location_id. Only applicable to standard tier. If provided, it must be a
* different zone from the one provided in [location_id]. Additional nodes beyond the first 2 will
* be placed in zones selected by the service.
* @param alternativeLocationId alternativeLocationId or {@code null} for none
*/
public Instance setAlternativeLocationId(java.lang.String alternativeLocationId) {
this.alternativeLocationId = alternativeLocationId;
return this;
}
/**
* Optional. Indicates whether OSS Redis AUTH is enabled for the instance. If set to "true" AUTH
* is enabled on the instance. Default value is "false" meaning AUTH is disabled.
* @return value or {@code null} for none
*/
public java.lang.Boolean getAuthEnabled() {
return authEnabled;
}
/**
* Optional. Indicates whether OSS Redis AUTH is enabled for the instance. If set to "true" AUTH
* is enabled on the instance. Default value is "false" meaning AUTH is disabled.
* @param authEnabled authEnabled or {@code null} for none
*/
public Instance setAuthEnabled(java.lang.Boolean authEnabled) {
this.authEnabled = authEnabled;
return this;
}
/**
* Optional. The full name of the Google Compute Engine
* [network](https://cloud.google.com/vpc/docs/vpc) to which the instance is connected. If left
* unspecified, the `default` network will be used.
* @return value or {@code null} for none
*/
public java.lang.String getAuthorizedNetwork() {
return authorizedNetwork;
}
/**
* Optional. The full name of the Google Compute Engine
* [network](https://cloud.google.com/vpc/docs/vpc) to which the instance is connected. If left
* unspecified, the `default` network will be used.
* @param authorizedNetwork authorizedNetwork or {@code null} for none
*/
public Instance setAuthorizedNetwork(java.lang.String authorizedNetwork) {
this.authorizedNetwork = authorizedNetwork;
return this;
}
/**
* Optional. The available maintenance versions that an instance could update to.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getAvailableMaintenanceVersions() {
return availableMaintenanceVersions;
}
/**
* Optional. The available maintenance versions that an instance could update to.
* @param availableMaintenanceVersions availableMaintenanceVersions or {@code null} for none
*/
public Instance setAvailableMaintenanceVersions(java.util.List<java.lang.String> availableMaintenanceVersions) {
this.availableMaintenanceVersions = availableMaintenanceVersions;
return this;
}
/**
* Optional. The network connect mode of the Redis instance. If not provided, the connect mode
* defaults to DIRECT_PEERING.
* @return value or {@code null} for none
*/
public java.lang.String getConnectMode() {
return connectMode;
}
/**
* Optional. The network connect mode of the Redis instance. If not provided, the connect mode
* defaults to DIRECT_PEERING.
* @param connectMode connectMode or {@code null} for none
*/
public Instance setConnectMode(java.lang.String connectMode) {
this.connectMode = connectMode;
return this;
}
/**
* Output only. The time the instance was created.
* @return value or {@code null} for none
*/
public String getCreateTime() {
return createTime;
}
/**
* Output only. The time the instance was created.
* @param createTime createTime or {@code null} for none
*/
public Instance setCreateTime(String createTime) {
this.createTime = createTime;
return this;
}
/**
* Output only. The current zone where the Redis primary node is located. In basic tier, this will
* always be the same as [location_id]. In standard tier, this can be the zone of any node in the
* instance.
* @return value or {@code null} for none
*/
public java.lang.String getCurrentLocationId() {
return currentLocationId;
}
/**
* Output only. The current zone where the Redis primary node is located. In basic tier, this will
* always be the same as [location_id]. In standard tier, this can be the zone of any node in the
* instance.
* @param currentLocationId currentLocationId or {@code null} for none
*/
public Instance setCurrentLocationId(java.lang.String currentLocationId) {
this.currentLocationId = currentLocationId;
return this;
}
/**
* Optional. The KMS key reference that the customer provides when trying to create the instance.
* @return value or {@code null} for none
*/
public java.lang.String getCustomerManagedKey() {
return customerManagedKey;
}
/**
* Optional. The KMS key reference that the customer provides when trying to create the instance.
* @param customerManagedKey customerManagedKey or {@code null} for none
*/
public Instance setCustomerManagedKey(java.lang.String customerManagedKey) {
this.customerManagedKey = customerManagedKey;
return this;
}
/**
* An arbitrary and optional user-provided name for the instance.
* @return value or {@code null} for none
*/
public java.lang.String getDisplayName() {
return displayName;
}
/**
* An arbitrary and optional user-provided name for the instance.
* @param displayName displayName or {@code null} for none
*/
public Instance setDisplayName(java.lang.String displayName) {
this.displayName = displayName;
return this;
}
/**
* Output only. Hostname or IP address of the exposed Redis endpoint used by clients to connect to
* the service.
* @return value or {@code null} for none
*/
public java.lang.String getHost() {
return host;
}
/**
* Output only. Hostname or IP address of the exposed Redis endpoint used by clients to connect to
* the service.
* @param host host or {@code null} for none
*/
public Instance setHost(java.lang.String host) {
this.host = host;
return this;
}
/**
* Resource labels to represent user provided metadata
* @return value or {@code null} for none
*/
public java.util.Map<String, java.lang.String> getLabels() {
return labels;
}
/**
* Resource labels to represent user provided metadata
* @param labels labels or {@code null} for none
*/
public Instance setLabels(java.util.Map<String, java.lang.String> labels) {
this.labels = labels;
return this;
}
/**
* Optional. The zone where the instance will be provisioned. If not provided, the service will
* choose a zone from the specified region for the instance. For standard tier, additional nodes
* will be added across multiple zones for protection against zonal failures. If specified, at
* least one node will be provisioned in this zone.
* @return value or {@code null} for none
*/
public java.lang.String getLocationId() {
return locationId;
}
/**
* Optional. The zone where the instance will be provisioned. If not provided, the service will
* choose a zone from the specified region for the instance. For standard tier, additional nodes
* will be added across multiple zones for protection against zonal failures. If specified, at
* least one node will be provisioned in this zone.
* @param locationId locationId or {@code null} for none
*/
public Instance setLocationId(java.lang.String locationId) {
this.locationId = locationId;
return this;
}
/**
* Optional. The maintenance policy for the instance. If not provided, maintenance events can be
* performed at any time.
* @return value or {@code null} for none
*/
public MaintenancePolicy getMaintenancePolicy() {
return maintenancePolicy;
}
/**
* Optional. The maintenance policy for the instance. If not provided, maintenance events can be
* performed at any time.
* @param maintenancePolicy maintenancePolicy or {@code null} for none
*/
public Instance setMaintenancePolicy(MaintenancePolicy maintenancePolicy) {
this.maintenancePolicy = maintenancePolicy;
return this;
}
/**
* Output only. Date and time of upcoming maintenance events which have been scheduled.
* @return value or {@code null} for none
*/
public MaintenanceSchedule getMaintenanceSchedule() {
return maintenanceSchedule;
}
/**
* Output only. Date and time of upcoming maintenance events which have been scheduled.
* @param maintenanceSchedule maintenanceSchedule or {@code null} for none
*/
public Instance setMaintenanceSchedule(MaintenanceSchedule maintenanceSchedule) {
this.maintenanceSchedule = maintenanceSchedule;
return this;
}
/**
* Optional. The self service update maintenance version. The version is date based such as
* "20210712_00_00".
* @return value or {@code null} for none
*/
public java.lang.String getMaintenanceVersion() {
return maintenanceVersion;
}
/**
* Optional. The self service update maintenance version. The version is date based such as
* "20210712_00_00".
* @param maintenanceVersion maintenanceVersion or {@code null} for none
*/
public Instance setMaintenanceVersion(java.lang.String maintenanceVersion) {
this.maintenanceVersion = maintenanceVersion;
return this;
}
/**
* Required. Redis memory size in GiB.
* @return value or {@code null} for none
*/
public java.lang.Integer getMemorySizeGb() {
return memorySizeGb;
}
/**
* Required. Redis memory size in GiB.
* @param memorySizeGb memorySizeGb or {@code null} for none
*/
public Instance setMemorySizeGb(java.lang.Integer memorySizeGb) {
this.memorySizeGb = memorySizeGb;
return this;
}
/**
* Required. Unique name of the resource in this scope including project and location using the
* form: `projects/{project_id}/locations/{location_id}/instances/{instance_id}` Note: Redis
* instances are managed and addressed at regional level so location_id here refers to a GCP
* region; however, users may choose which specific zone (or collection of zones for cross-zone
* instances) an instance should be provisioned in. Refer to location_id and
* alternative_location_id fields for more details.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Required. Unique name of the resource in this scope including project and location using the
* form: `projects/{project_id}/locations/{location_id}/instances/{instance_id}` Note: Redis
* instances are managed and addressed at regional level so location_id here refers to a GCP
* region; however, users may choose which specific zone (or collection of zones for cross-zone
* instances) an instance should be provisioned in. Refer to location_id and
* alternative_location_id fields for more details.
* @param name name or {@code null} for none
*/
public Instance setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Output only. Info per node.
* @return value or {@code null} for none
*/
public java.util.List<NodeInfo> getNodes() {
return nodes;
}
/**
* Output only. Info per node.
* @param nodes nodes or {@code null} for none
*/
public Instance setNodes(java.util.List<NodeInfo> nodes) {
this.nodes = nodes;
return this;
}
/**
* Optional. Persistence configuration parameters
* @return value or {@code null} for none
*/
public PersistenceConfig getPersistenceConfig() {
return persistenceConfig;
}
/**
* Optional. Persistence configuration parameters
* @param persistenceConfig persistenceConfig or {@code null} for none
*/
public Instance setPersistenceConfig(PersistenceConfig persistenceConfig) {
this.persistenceConfig = persistenceConfig;
return this;
}
/**
* Output only. Cloud IAM identity used by import / export operations to transfer data to/from
* Cloud Storage. Format is "serviceAccount:". The value may change over time for a given instance
* so should be checked before each import/export operation.
* @return value or {@code null} for none
*/
public java.lang.String getPersistenceIamIdentity() {
return persistenceIamIdentity;
}
/**
* Output only. Cloud IAM identity used by import / export operations to transfer data to/from
* Cloud Storage. Format is "serviceAccount:". The value may change over time for a given instance
* so should be checked before each import/export operation.
* @param persistenceIamIdentity persistenceIamIdentity or {@code null} for none
*/
public Instance setPersistenceIamIdentity(java.lang.String persistenceIamIdentity) {
this.persistenceIamIdentity = persistenceIamIdentity;
return this;
}
/**
* Output only. The port number of the exposed Redis endpoint.
* @return value or {@code null} for none
*/
public java.lang.Integer getPort() {
return port;
}
/**
* Output only. The port number of the exposed Redis endpoint.
* @param port port or {@code null} for none
*/
public Instance setPort(java.lang.Integer port) {
this.port = port;
return this;
}
/**
* Output only. Hostname or IP address of the exposed readonly Redis endpoint. Standard tier only.
* Targets all healthy replica nodes in instance. Replication is asynchronous and replica nodes
* will exhibit some lag behind the primary. Write requests must target 'host'.
* @return value or {@code null} for none
*/
public java.lang.String getReadEndpoint() {
return readEndpoint;
}
/**
* Output only. Hostname or IP address of the exposed readonly Redis endpoint. Standard tier only.
* Targets all healthy replica nodes in instance. Replication is asynchronous and replica nodes
* will exhibit some lag behind the primary. Write requests must target 'host'.
* @param readEndpoint readEndpoint or {@code null} for none
*/
public Instance setReadEndpoint(java.lang.String readEndpoint) {
this.readEndpoint = readEndpoint;
return this;
}
/**
* Output only. The port number of the exposed readonly redis endpoint. Standard tier only. Write
* requests should target 'port'.
* @return value or {@code null} for none
*/
public java.lang.Integer getReadEndpointPort() {
return readEndpointPort;
}
/**
* Output only. The port number of the exposed readonly redis endpoint. Standard tier only. Write
* requests should target 'port'.
* @param readEndpointPort readEndpointPort or {@code null} for none
*/
public Instance setReadEndpointPort(java.lang.Integer readEndpointPort) {
this.readEndpointPort = readEndpointPort;
return this;
}
/**
* Optional. Read replicas mode for the instance. Defaults to READ_REPLICAS_DISABLED.
* @return value or {@code null} for none
*/
public java.lang.String getReadReplicasMode() {
return readReplicasMode;
}
/**
* Optional. Read replicas mode for the instance. Defaults to READ_REPLICAS_DISABLED.
* @param readReplicasMode readReplicasMode or {@code null} for none
*/
public Instance setReadReplicasMode(java.lang.String readReplicasMode) {
this.readReplicasMode = readReplicasMode;
return this;
}
/**
* Optional. Redis configuration parameters, according to http://redis.io/topics/config.
* Currently, the only supported parameters are: Redis version 3.2 and newer: * maxmemory-policy *
* notify-keyspace-events Redis version 4.0 and newer: * activedefrag * lfu-decay-time * lfu-log-
* factor * maxmemory-gb Redis version 5.0 and newer: * stream-node-max-bytes * stream-node-max-
* entries
* @return value or {@code null} for none
*/
public java.util.Map<String, java.lang.String> getRedisConfigs() {
return redisConfigs;
}
/**
* Optional. Redis configuration parameters, according to http://redis.io/topics/config.
* Currently, the only supported parameters are: Redis version 3.2 and newer: * maxmemory-policy *
* notify-keyspace-events Redis version 4.0 and newer: * activedefrag * lfu-decay-time * lfu-log-
* factor * maxmemory-gb Redis version 5.0 and newer: * stream-node-max-bytes * stream-node-max-
* entries
* @param redisConfigs redisConfigs or {@code null} for none
*/
public Instance setRedisConfigs(java.util.Map<String, java.lang.String> redisConfigs) {
this.redisConfigs = redisConfigs;
return this;
}
/**
* Optional. The version of Redis software. If not provided, latest supported version will be
* used. Currently, the supported values are: * `REDIS_3_2` for Redis 3.2 compatibility *
* `REDIS_4_0` for Redis 4.0 compatibility (default) * `REDIS_5_0` for Redis 5.0 compatibility *
* `REDIS_6_X` for Redis 6.x compatibility
* @return value or {@code null} for none
*/
public java.lang.String getRedisVersion() {
return redisVersion;
}
/**
* Optional. The version of Redis software. If not provided, latest supported version will be
* used. Currently, the supported values are: * `REDIS_3_2` for Redis 3.2 compatibility *
* `REDIS_4_0` for Redis 4.0 compatibility (default) * `REDIS_5_0` for Redis 5.0 compatibility *
* `REDIS_6_X` for Redis 6.x compatibility
* @param redisVersion redisVersion or {@code null} for none
*/
public Instance setRedisVersion(java.lang.String redisVersion) {
this.redisVersion = redisVersion;
return this;
}
/**
* Optional. The number of replica nodes. The valid range for the Standard Tier with read replicas
* enabled is [1-5] and defaults to 2. If read replicas are not enabled for a Standard Tier
* instance, the only valid value is 1 and the default is 1. The valid value for basic tier is 0
* and the default is also 0.
* @return value or {@code null} for none
*/
public java.lang.Integer getReplicaCount() {
return replicaCount;
}
/**
* Optional. The number of replica nodes. The valid range for the Standard Tier with read replicas
* enabled is [1-5] and defaults to 2. If read replicas are not enabled for a Standard Tier
* instance, the only valid value is 1 and the default is 1. The valid value for basic tier is 0
* and the default is also 0.
* @param replicaCount replicaCount or {@code null} for none
*/
public Instance setReplicaCount(java.lang.Integer replicaCount) {
this.replicaCount = replicaCount;
return this;
}
/**
* Optional. For DIRECT_PEERING mode, the CIDR range of internal addresses that are reserved for
* this instance. Range must be unique and non-overlapping with existing subnets in an authorized
* network. For PRIVATE_SERVICE_ACCESS mode, the name of one allocated IP address ranges
* associated with this private service access connection. If not provided, the service will
* choose an unused /29 block, for example, 10.0.0.0/29 or 192.168.0.0/29. For
* READ_REPLICAS_ENABLED the default block size is /28.
* @return value or {@code null} for none
*/
public java.lang.String getReservedIpRange() {
return reservedIpRange;
}
/**
* Optional. For DIRECT_PEERING mode, the CIDR range of internal addresses that are reserved for
* this instance. Range must be unique and non-overlapping with existing subnets in an authorized
* network. For PRIVATE_SERVICE_ACCESS mode, the name of one allocated IP address ranges
* associated with this private service access connection. If not provided, the service will
* choose an unused /29 block, for example, 10.0.0.0/29 or 192.168.0.0/29. For
* READ_REPLICAS_ENABLED the default block size is /28.
* @param reservedIpRange reservedIpRange or {@code null} for none
*/
public Instance setReservedIpRange(java.lang.String reservedIpRange) {
this.reservedIpRange = reservedIpRange;
return this;
}
/**
* Optional. Additional IP range for node placement. Required when enabling read replicas on an
* existing instance. For DIRECT_PEERING mode value must be a CIDR range of size /28, or "auto".
* For PRIVATE_SERVICE_ACCESS mode value must be the name of an allocated address range associated
* with the private service access connection, or "auto".
* @return value or {@code null} for none
*/
public java.lang.String getSecondaryIpRange() {
return secondaryIpRange;
}
/**
* Optional. Additional IP range for node placement. Required when enabling read replicas on an
* existing instance. For DIRECT_PEERING mode value must be a CIDR range of size /28, or "auto".
* For PRIVATE_SERVICE_ACCESS mode value must be the name of an allocated address range associated
* with the private service access connection, or "auto".
* @param secondaryIpRange secondaryIpRange or {@code null} for none
*/
public Instance setSecondaryIpRange(java.lang.String secondaryIpRange) {
this.secondaryIpRange = secondaryIpRange;
return this;
}
/**
* Output only. List of server CA certificates for the instance.
* @return value or {@code null} for none
*/
public java.util.List<TlsCertificate> getServerCaCerts() {
return serverCaCerts;
}
/**
* Output only. List of server CA certificates for the instance.
* @param serverCaCerts serverCaCerts or {@code null} for none
*/
public Instance setServerCaCerts(java.util.List<TlsCertificate> serverCaCerts) {
this.serverCaCerts = serverCaCerts;
return this;
}
/**
* Output only. The current state of this instance.
* @return value or {@code null} for none
*/
public java.lang.String getState() {
return state;
}
/**
* Output only. The current state of this instance.
* @param state state or {@code null} for none
*/
public Instance setState(java.lang.String state) {
this.state = state;
return this;
}
/**
* Output only. Additional information about the current status of this instance, if available.
* @return value or {@code null} for none
*/
public java.lang.String getStatusMessage() {
return statusMessage;
}
/**
* Output only. Additional information about the current status of this instance, if available.
* @param statusMessage statusMessage or {@code null} for none
*/
public Instance setStatusMessage(java.lang.String statusMessage) {
this.statusMessage = statusMessage;
return this;
}
/**
* Optional. reasons that causes instance in "SUSPENDED" state.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSuspensionReasons() {
return suspensionReasons;
}
/**
* Optional. reasons that causes instance in "SUSPENDED" state.
* @param suspensionReasons suspensionReasons or {@code null} for none
*/
public Instance setSuspensionReasons(java.util.List<java.lang.String> suspensionReasons) {
this.suspensionReasons = suspensionReasons;
return this;
}
/**
* Required. The service tier of the instance.
* @return value or {@code null} for none
*/
public java.lang.String getTier() {
return tier;
}
/**
* Required. The service tier of the instance.
* @param tier tier or {@code null} for none
*/
public Instance setTier(java.lang.String tier) {
this.tier = tier;
return this;
}
/**
* Optional. The TLS mode of the Redis instance. If not provided, TLS is disabled for the
* instance.
* @return value or {@code null} for none
*/
public java.lang.String getTransitEncryptionMode() {
return transitEncryptionMode;
}
/**
* Optional. The TLS mode of the Redis instance. If not provided, TLS is disabled for the
* instance.
* @param transitEncryptionMode transitEncryptionMode or {@code null} for none
*/
public Instance setTransitEncryptionMode(java.lang.String transitEncryptionMode) {
this.transitEncryptionMode = transitEncryptionMode;
return this;
}
@Override
public Instance set(String fieldName, Object value) {
return (Instance) super.set(fieldName, value);
}
@Override
public Instance clone() {
return (Instance) super.clone();
}
}
|
openjdk/jdk8 | 36,505 | jaxws/src/share/jaxws_classes/com/sun/tools/internal/ws/resources/WscompileMessages.java | /*
* Copyright (c) 1997, 2012, 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.tools.internal.ws.resources;
import com.sun.istack.internal.localization.Localizable;
import com.sun.istack.internal.localization.LocalizableMessageFactory;
import com.sun.istack.internal.localization.Localizer;
/**
* Defines string formatting method for each constant in the resource file
*
*/
public final class WscompileMessages {
private final static LocalizableMessageFactory messageFactory = new LocalizableMessageFactory("com.sun.tools.internal.ws.resources.wscompile");
private final static Localizer localizer = new Localizer();
public static Localizable localizableWSIMPORT_ARCHIVING_ARTIFACTS(Object arg0) {
return messageFactory.getMessage("wsimport.archivingArtifacts", arg0);
}
/**
*
* Archiving the generated artifacts into {0}.
*
*
*/
public static String WSIMPORT_ARCHIVING_ARTIFACTS(Object arg0) {
return localizer.localize(localizableWSIMPORT_ARCHIVING_ARTIFACTS(arg0));
}
public static Localizable localizableWSGEN_CLASS_MUST_BE_IMPLEMENTATION_CLASS(Object arg0) {
return messageFactory.getMessage("wsgen.class.must.be.implementation.class", arg0);
}
/**
* The class "{0}" is not an endpoint implementation class.
*
*/
public static String WSGEN_CLASS_MUST_BE_IMPLEMENTATION_CLASS(Object arg0) {
return localizer.localize(localizableWSGEN_CLASS_MUST_BE_IMPLEMENTATION_CLASS(arg0));
}
public static Localizable localizableWSGEN_FULLVERSION(Object arg0) {
return messageFactory.getMessage("wsgen.fullversion", arg0);
}
/**
* wsgen full version "{0}"
*
*/
public static String WSGEN_FULLVERSION(Object arg0) {
return localizer.localize(localizableWSGEN_FULLVERSION(arg0));
}
public static Localizable localizableWRAPPER_TASK_LOADING_INCORRECT_API(Object arg0, Object arg1, Object arg2) {
return messageFactory.getMessage("wrapperTask.loadingIncorrectApi", arg0, arg1, arg2);
}
/**
* You are loading JAX-WS {0} API from {1} but this tool requires JAX-WS {2} API.
*
*/
public static String WRAPPER_TASK_LOADING_INCORRECT_API(Object arg0, Object arg1, Object arg2) {
return localizer.localize(localizableWRAPPER_TASK_LOADING_INCORRECT_API(arg0, arg1, arg2));
}
public static Localizable localizableWSIMPORT_WSDLLOCATION_CLIENTJAR() {
return messageFactory.getMessage("wsimport.wsdllocation.clientjar");
}
/**
* wsdlLocation cannot be specified when using clientJar option
*
*/
public static String WSIMPORT_WSDLLOCATION_CLIENTJAR() {
return localizer.localize(localizableWSIMPORT_WSDLLOCATION_CLIENTJAR());
}
public static Localizable localizableWSIMPORT_VERSION(Object arg0) {
return messageFactory.getMessage("wsimport.version", arg0);
}
/**
* wsimport version "{0}"
*
*/
public static String WSIMPORT_VERSION(Object arg0) {
return localizer.localize(localizableWSIMPORT_VERSION(arg0));
}
public static Localizable localizableWSGEN_CLASS_NOT_FOUND(Object arg0) {
return messageFactory.getMessage("wsgen.class.not.found", arg0);
}
/**
* Class not found: "{0}"
*
*/
public static String WSGEN_CLASS_NOT_FOUND(Object arg0) {
return localizer.localize(localizableWSGEN_CLASS_NOT_FOUND(arg0));
}
public static Localizable localizableWSIMPORT_HTTP_REDIRECT(Object arg0, Object arg1) {
return messageFactory.getMessage("wsimport.httpRedirect", arg0, arg1);
}
/**
* Server returned HTTP Status code: "{0}", retrying with "{1}"
*
*/
public static String WSIMPORT_HTTP_REDIRECT(Object arg0, Object arg1) {
return localizer.localize(localizableWSIMPORT_HTTP_REDIRECT(arg0, arg1));
}
public static Localizable localizableWSIMPORT_AUTH_INFO_NEEDED(Object arg0, Object arg1, Object arg2) {
return messageFactory.getMessage("wsimport.authInfoNeeded", arg0, arg1, arg2);
}
/**
* {0}, "{1}" needs authorization, please provide authorization file with read access at {2} or use -Xauthfile to give the authorization file and on each line provide authorization information using this format : http[s]://user:password@host:port//<url-path>
*
*/
public static String WSIMPORT_AUTH_INFO_NEEDED(Object arg0, Object arg1, Object arg2) {
return localizer.localize(localizableWSIMPORT_AUTH_INFO_NEEDED(arg0, arg1, arg2));
}
public static Localizable localizableWSGEN_USAGE_EXAMPLES() {
return messageFactory.getMessage("wsgen.usage.examples");
}
/**
*
* Examples:
* wsgen -cp . example.Stock
* wsgen -cp . example.Stock -wsdl -servicename '{http://mynamespace}MyService'
*
*
*/
public static String WSGEN_USAGE_EXAMPLES() {
return localizer.localize(localizableWSGEN_USAGE_EXAMPLES());
}
public static Localizable localizableWSIMPORT_FETCHING_METADATA() {
return messageFactory.getMessage("wsimport.fetchingMetadata");
}
/**
*
* Downloading the WSDL and associated metadata
*
*
*/
public static String WSIMPORT_FETCHING_METADATA() {
return localizer.localize(localizableWSIMPORT_FETCHING_METADATA());
}
public static Localizable localizableWSGEN_INVALID_PROTOCOL(Object arg0, Object arg1) {
return messageFactory.getMessage("wsgen.invalid.protocol", arg0, arg1);
}
/**
* "{0}" is not a supported protocol. Supported protocols include: {1}.
*
*/
public static String WSGEN_INVALID_PROTOCOL(Object arg0, Object arg1) {
return localizer.localize(localizableWSGEN_INVALID_PROTOCOL(arg0, arg1));
}
public static Localizable localizableWSIMPORT_USAGE_EXAMPLES() {
return messageFactory.getMessage("wsimport.usage.examples");
}
/**
*
* Examples:
* wsimport stock.wsdl -b stock.xml -b stock.xjb
* wsimport -d generated http://example.org/stock?wsdl
*
*
*/
public static String WSIMPORT_USAGE_EXAMPLES() {
return localizer.localize(localizableWSIMPORT_USAGE_EXAMPLES());
}
public static Localizable localizableINVOKER_NEED_ENDORSED(Object arg0, Object arg1) {
return messageFactory.getMessage("invoker.needEndorsed", arg0, arg1);
}
/**
* You are running on JDK6 which comes with JAX-WS {0} API, but this tool requires JAX-WS {1} API. Use the endorsed standards override mechanism (http://docs.oracle.com/javase/6/docs/technotes/guides/standards/), or use -Xendorsed option.
*
*/
public static String INVOKER_NEED_ENDORSED(Object arg0, Object arg1) {
return localizer.localize(localizableINVOKER_NEED_ENDORSED(arg0, arg1));
}
public static Localizable localizableWSIMPORT_MISSING_FILE() {
return messageFactory.getMessage("wsimport.missingFile");
}
/**
* Missing WSDL_URI
*
*/
public static String WSIMPORT_MISSING_FILE() {
return localizer.localize(localizableWSIMPORT_MISSING_FILE());
}
public static Localizable localizableWSIMPORT_USAGE_EXTENSIONS() {
return messageFactory.getMessage("wsimport.usage.extensions");
}
/**
*
* Extensions:
* -XadditionalHeaders map headers not bound to request or response message to
* Java method parameters
* -Xauthfile file to carry authorization information in the format
* http://username:password@example.org/stock?wsdl
* -Xdebug print debug information
* -Xno-addressing-databinding enable binding of W3C EndpointReferenceType to Java
* -Xnocompile do not compile generated Java files
* -XdisableAuthenticator disable Authenticator used by JAX-WS RI,
* -Xauthfile option will be ignored if set
* -XdisableSSLHostnameVerification disable the SSL Hostname verification while fetching
* wsdls
*
*/
public static String WSIMPORT_USAGE_EXTENSIONS() {
return localizer.localize(localizableWSIMPORT_USAGE_EXTENSIONS());
}
public static Localizable localizableWSIMPORT_USAGE(Object arg0) {
return messageFactory.getMessage("wsimport.usage", arg0);
}
/**
* Usage: {0} [options] <WSDL_URI>
*
* Use "wsimport -help" for a detailed description of options.
*
*/
public static String WSIMPORT_USAGE(Object arg0) {
return localizer.localize(localizableWSIMPORT_USAGE(arg0));
}
public static Localizable localizableWSGEN_USAGE_EXTENSIONS() {
return messageFactory.getMessage("wsgen.usage.extensions");
}
/**
*
* Extensions:
* -Xnocompile do not compile generated Java files
*
*/
public static String WSGEN_USAGE_EXTENSIONS() {
return localizer.localize(localizableWSGEN_USAGE_EXTENSIONS());
}
public static Localizable localizablePLEASE() {
return messageFactory.getMessage("Please");
}
/**
* specify "-extension" and "-wsdl:protocol XSoap1.2" switches. For example:
*
*
*
*/
public static String PLEASE() {
return localizer.localize(localizablePLEASE());
}
public static Localizable localizableWSCOMPILE_EXISTING_OPTION(Object arg0) {
return messageFactory.getMessage("wscompile.existingOption", arg0);
}
/**
* Ignoring already defined option {0}
*
*
*/
public static String WSCOMPILE_EXISTING_OPTION(Object arg0) {
return localizer.localize(localizableWSCOMPILE_EXISTING_OPTION(arg0));
}
public static Localizable localizableWSIMPORT_PARSING_WSDL() {
return messageFactory.getMessage("wsimport.ParsingWSDL");
}
/**
* parsing WSDL...
*
*
*
*/
public static String WSIMPORT_PARSING_WSDL() {
return localizer.localize(localizableWSIMPORT_PARSING_WSDL());
}
public static Localizable localizableWSGEN_MISSING_FILE() {
return messageFactory.getMessage("wsgen.missingFile");
}
/**
* Missing SEI
*
*/
public static String WSGEN_MISSING_FILE() {
return localizer.localize(localizableWSGEN_MISSING_FILE());
}
public static Localizable localizableWSIMPORT_HELP(Object arg0) {
return messageFactory.getMessage("wsimport.help", arg0);
}
/**
*
* Usage: {0} [options] <WSDL_URI>
*
* where [options] include:
* -b <path> specify jaxws/jaxb binding files or additional schemas
* (Each <path> must have its own -b)
* -B<jaxbOption> Pass this option to JAXB schema compiler
* -catalog <file> specify catalog file to resolve external entity references
* supports TR9401, XCatalog, and OASIS XML Catalog format.
* -classpath <path> specify where to find user class files and wsimport extensions
* -cp <path> specify where to find user class files and wsimport extensions
* -d <directory> specify where to place generated output files
* -encoding <encoding> specify character encoding used by source files
* -extension allow vendor extensions - functionality not specified
* by the specification. Use of extensions may
* result in applications that are not portable or
* may not interoperate with other implementations
* -help display help
* -httpproxy:<proxy> set a HTTP proxy. Format is [user[:password]@]proxyHost:proxyPort
* (port defaults to 8080)
* -J<javacOption> pass this option to javac
* -keep keep generated files
* -p <pkg> specifies the target package
* -quiet suppress wsimport output
* -s <directory> specify where to place generated source files
* -target <version> generate code as per the given JAXWS spec version
* Defaults to 2.2, Accepted values are 2.0, 2.1 and 2.2
* e.g. 2.0 will generate compliant code for JAXWS 2.0 spec
* -verbose output messages about what the compiler is doing
* -version print version information
* -fullversion print full version information
* -wsdllocation <location> @WebServiceClient.wsdlLocation value
* -clientjar <jarfile> creates the jar file of the generated artifacts along with the
* WSDL metadata required for invoking the web service.
* -generateJWS generate stubbed JWS implementation file
* -implDestDir <directory> specify where to generate JWS implementation file
* -implServiceName <name> local portion of service name for generated JWS implementation
* -implPortName <name> local portion of port name for generated JWS implementation
*
*/
public static String WSIMPORT_HELP(Object arg0) {
return localizer.localize(localizableWSIMPORT_HELP(arg0));
}
public static Localizable localizableWSCOMPILE_ERROR(Object arg0) {
return messageFactory.getMessage("wscompile.error", arg0);
}
/**
* error: {0}
*
*/
public static String WSCOMPILE_ERROR(Object arg0) {
return localizer.localize(localizableWSCOMPILE_ERROR(arg0));
}
public static Localizable localizableWSGEN_PROTOCOL_WITHOUT_EXTENSION(Object arg0) {
return messageFactory.getMessage("wsgen.protocol.without.extension", arg0);
}
/**
* The optional protocol "{0}" must be used in conjunction with the "-extension" option.
*
*/
public static String WSGEN_PROTOCOL_WITHOUT_EXTENSION(Object arg0) {
return localizer.localize(localizableWSGEN_PROTOCOL_WITHOUT_EXTENSION(arg0));
}
public static Localizable localizableWSIMPORT_COMPILING_CODE() {
return messageFactory.getMessage("wsimport.CompilingCode");
}
/**
*
* Compiling code...
*
*
*/
public static String WSIMPORT_COMPILING_CODE() {
return localizer.localize(localizableWSIMPORT_COMPILING_CODE());
}
public static Localizable localizableWSIMPORT_READING_AUTH_FILE(Object arg0) {
return messageFactory.getMessage("wsimport.readingAuthFile", arg0);
}
/**
* Trying to read authorization file : "{0}"...
*
*/
public static String WSIMPORT_READING_AUTH_FILE(Object arg0) {
return localizer.localize(localizableWSIMPORT_READING_AUTH_FILE(arg0));
}
public static Localizable localizableWSCOMPILE_UNSUPPORTED_ENCODING(Object arg0) {
return messageFactory.getMessage("wscompile.unsupportedEncoding", arg0);
}
/**
* unsupported encoding: {0}
*
*/
public static String WSCOMPILE_UNSUPPORTED_ENCODING(Object arg0) {
return localizer.localize(localizableWSCOMPILE_UNSUPPORTED_ENCODING(arg0));
}
public static Localizable localizableWSGEN_NO_WEBSERVICES_CLASS(Object arg0) {
return messageFactory.getMessage("wsgen.no.webservices.class", arg0);
}
/**
* wsgen did not find any class with @WebService annotation. Please specify @WebService annotation on {0}.
*
*/
public static String WSGEN_NO_WEBSERVICES_CLASS(Object arg0) {
return localizer.localize(localizableWSGEN_NO_WEBSERVICES_CLASS(arg0));
}
public static Localizable localizableWSIMPORT_ARCHIVE_ARTIFACT(Object arg0, Object arg1) {
return messageFactory.getMessage("wsimport.archiveArtifact", arg0, arg1);
}
/**
* Adding {0} to the archive {1}
*
*/
public static String WSIMPORT_ARCHIVE_ARTIFACT(Object arg0, Object arg1) {
return localizer.localize(localizableWSIMPORT_ARCHIVE_ARTIFACT(arg0, arg1));
}
public static Localizable localizableWSCOMPILE_NO_SUCH_DIRECTORY(Object arg0) {
return messageFactory.getMessage("wscompile.noSuchDirectory", arg0);
}
/**
* directory not found: {0}
*
*/
public static String WSCOMPILE_NO_SUCH_DIRECTORY(Object arg0) {
return localizer.localize(localizableWSCOMPILE_NO_SUCH_DIRECTORY(arg0));
}
public static Localizable localizableWSCOMPILE_INFO(Object arg0) {
return messageFactory.getMessage("wscompile.info", arg0);
}
/**
* info: {0}
*
*/
public static String WSCOMPILE_INFO(Object arg0) {
return localizer.localize(localizableWSCOMPILE_INFO(arg0));
}
public static Localizable localizableWSIMPORT_MAX_REDIRECT_ATTEMPT() {
return messageFactory.getMessage("wsimport.maxRedirectAttempt");
}
/**
* Can not get a WSDL maximum number of redirects(5) reached
*
*/
public static String WSIMPORT_MAX_REDIRECT_ATTEMPT() {
return localizer.localize(localizableWSIMPORT_MAX_REDIRECT_ATTEMPT());
}
public static Localizable localizableWSIMPORT_WARNING_MESSAGE(Object arg0) {
return messageFactory.getMessage("wsimport.WarningMessage", arg0);
}
/**
* [WARNING] {0}
*
*/
public static String WSIMPORT_WARNING_MESSAGE(Object arg0) {
return localizer.localize(localizableWSIMPORT_WARNING_MESSAGE(arg0));
}
public static Localizable localizableWSCOMPILE_INVALID_OPTION(Object arg0) {
return messageFactory.getMessage("wscompile.invalidOption", arg0);
}
/**
* unrecognized parameter {0}
*
*/
public static String WSCOMPILE_INVALID_OPTION(Object arg0) {
return localizer.localize(localizableWSCOMPILE_INVALID_OPTION(arg0));
}
public static Localizable localizableWSIMPORT_ERROR_MESSAGE(Object arg0) {
return messageFactory.getMessage("wsimport.ErrorMessage", arg0);
}
/**
* [ERROR] {0}
*
*/
public static String WSIMPORT_ERROR_MESSAGE(Object arg0) {
return localizer.localize(localizableWSIMPORT_ERROR_MESSAGE(arg0));
}
public static Localizable localizableWSIMPORT_GENERATING_CODE() {
return messageFactory.getMessage("wsimport.GeneratingCode");
}
/**
*
* Generating code...
*
*
*/
public static String WSIMPORT_GENERATING_CODE() {
return localizer.localize(localizableWSIMPORT_GENERATING_CODE());
}
public static Localizable localizableWSGEN() {
return messageFactory.getMessage("wsgen");
}
/**
* -wsdl:protocol XSoap1.2 -extenson {1}
*
*/
public static String WSGEN() {
return localizer.localize(localizableWSGEN());
}
public static Localizable localizableWSIMPORT_NOT_A_FILE_NOR_URL(Object arg0) {
return messageFactory.getMessage("wsimport.NotAFileNorURL", arg0);
}
/**
* "{0}" is neither a file name nor an URL
*
*/
public static String WSIMPORT_NOT_A_FILE_NOR_URL(Object arg0) {
return localizer.localize(localizableWSIMPORT_NOT_A_FILE_NOR_URL(arg0));
}
public static Localizable localizableWSCOMPILE_WARNING(Object arg0) {
return messageFactory.getMessage("wscompile.warning", arg0);
}
/**
* warning: {0}
*
*/
public static String WSCOMPILE_WARNING(Object arg0) {
return localizer.localize(localizableWSCOMPILE_WARNING(arg0));
}
public static Localizable localizableWRAPPER_TASK_NEED_ENDORSED(Object arg0, Object arg1, Object arg2) {
return messageFactory.getMessage("wrapperTask.needEndorsed", arg0, arg1, arg2);
}
/**
* You are running on JDK6 which comes with JAX-WS {0} API, but this tool requires JAX-WS {1} API. Use the endorsed standards override mechanism (http://docs.oracle.com/javase/6/docs/technotes/guides/standards/), or set xendorsed="true" on <{2}>.
*
*/
public static String WRAPPER_TASK_NEED_ENDORSED(Object arg0, Object arg1, Object arg2) {
return localizer.localize(localizableWRAPPER_TASK_NEED_ENDORSED(arg0, arg1, arg2));
}
public static Localizable localizableWSIMPORT_NO_SUCH_JAXB_OPTION(Object arg0) {
return messageFactory.getMessage("wsimport.noSuchJaxbOption", arg0);
}
/**
* no such JAXB option: {0}
*
*/
public static String WSIMPORT_NO_SUCH_JAXB_OPTION(Object arg0) {
return localizer.localize(localizableWSIMPORT_NO_SUCH_JAXB_OPTION(arg0));
}
public static Localizable localizableWSGEN_VERSION(Object arg0) {
return messageFactory.getMessage("wsgen.version", arg0);
}
/**
* wsgen version "{0}"
*
*/
public static String WSGEN_VERSION(Object arg0) {
return localizer.localize(localizableWSGEN_VERSION(arg0));
}
public static Localizable localizableWSIMPORT_AUTH_FILE_NOT_FOUND(Object arg0, Object arg1) {
return messageFactory.getMessage("wsimport.authFileNotFound", arg0, arg1);
}
/**
* Authorization file "{0}" not found. If the WSDL access needs Basic Authentication, please provide authorization file with read access at {1} or use -Xauthfile to give the authorization file and on each line provide authorization information using this format : http[s]://user:password@host:port//<url-path>
*
*/
public static String WSIMPORT_AUTH_FILE_NOT_FOUND(Object arg0, Object arg1) {
return localizer.localize(localizableWSIMPORT_AUTH_FILE_NOT_FOUND(arg0, arg1));
}
public static Localizable localizableWSIMPORT_DEBUG_MESSAGE(Object arg0) {
return messageFactory.getMessage("wsimport.DebugMessage", arg0);
}
/**
* [DEBUG] {0}
*
*/
public static String WSIMPORT_DEBUG_MESSAGE(Object arg0) {
return localizer.localize(localizableWSIMPORT_DEBUG_MESSAGE(arg0));
}
public static Localizable localizableWSGEN_COULD_NOT_CREATE_FILE(Object arg0) {
return messageFactory.getMessage("wsgen.could.not.create.file", arg0);
}
/**
* "Could not create file: "{0}"
*
*/
public static String WSGEN_COULD_NOT_CREATE_FILE(Object arg0) {
return localizer.localize(localizableWSGEN_COULD_NOT_CREATE_FILE(arg0));
}
public static Localizable localizableWSGEN_WSDL_ARG_NO_GENWSDL(Object arg0) {
return messageFactory.getMessage("wsgen.wsdl.arg.no.genwsdl", arg0);
}
/**
* The "{0}" option can only be in conjunction with the "-wsdl" option.
*
*/
public static String WSGEN_WSDL_ARG_NO_GENWSDL(Object arg0) {
return localizer.localize(localizableWSGEN_WSDL_ARG_NO_GENWSDL(arg0));
}
public static Localizable localizableWSGEN_HELP(Object arg0, Object arg1, Object arg2) {
return messageFactory.getMessage("wsgen.help", arg0, arg1, arg2);
}
/**
*
* Usage: {0} [options] <SEI>
*
* where [options] include:
* -classpath <path> specify where to find input class files and wsgen extensions
* -cp <path> specify where to find input class files and wsgen extensions
* -d <directory> specify where to place generated output files
* -encoding <encoding> specify character encoding used by source files
* -extension allow vendor extensions - functionality not specified
* by the specification. Use of extensions may
* result in applications that are not portable or
* may not interoperate with other implementations
* -help display help
* -J<javacOption> pass this option to javac
* -keep keep generated files
* -r <directory> resource destination directory, specify where to
* place resouce files such as WSDLs
* -s <directory> specify where to place generated source files
* -verbose output messages about what the compiler is doing
* -version print version information
* -fullversion print full version information
* -wsdl[:protocol] generate a WSDL file. The protocol is optional.
* Valid protocols are {1},
* the default is soap1.1.
* The non standard protocols {2}
* can only be used in conjunction with the
* -extension option.
* -inlineSchemas inline schemas in the generated wsdl. Must be
* used in conjunction with the -wsdl option.
* -servicename <name> specify the Service name to use in the generated WSDL
* Used in conjunction with the -wsdl option.
* -portname <name> specify the Port name to use in the generated WSDL
* Used in conjunction with the -wsdl option.
* -x <file> specify External Web Service Metadata xml descriptor
*
*/
public static String WSGEN_HELP(Object arg0, Object arg1, Object arg2) {
return localizer.localize(localizableWSGEN_HELP(arg0, arg1, arg2));
}
public static Localizable localizableWSIMPORT_INFO_MESSAGE(Object arg0) {
return messageFactory.getMessage("wsimport.InfoMessage", arg0);
}
/**
* [INFO] {0}
*
*/
public static String WSIMPORT_INFO_MESSAGE(Object arg0) {
return localizer.localize(localizableWSIMPORT_INFO_MESSAGE(arg0));
}
public static Localizable localizableWSGEN_INLINE_SCHEMAS_ONLY_WITH_WSDL() {
return messageFactory.getMessage("wsgen.inlineSchemas.only.with.wsdl");
}
/**
* "-inlineSchemas" must be used in conjunction with the "-wsdl" option
*
*/
public static String WSGEN_INLINE_SCHEMAS_ONLY_WITH_WSDL() {
return localizer.localize(localizableWSGEN_INLINE_SCHEMAS_ONLY_WITH_WSDL());
}
public static Localizable localizableWSGEN_SOAP_12_WITHOUT_EXTENSION() {
return messageFactory.getMessage("wsgen.soap12.without.extension");
}
/**
* The optional protocol "Xsoap1.2" must be used in conjunction with the "-extension" option.
*
*/
public static String WSGEN_SOAP_12_WITHOUT_EXTENSION() {
return localizer.localize(localizableWSGEN_SOAP_12_WITHOUT_EXTENSION());
}
public static Localizable localizableWSIMPORT_ILLEGAL_AUTH_INFO(Object arg0) {
return messageFactory.getMessage("wsimport.ILLEGAL_AUTH_INFO", arg0);
}
/**
* "{0}" is not a valid authorization information format. The format is http[s]://user:password@host:port//<url-path>.
*
*/
public static String WSIMPORT_ILLEGAL_AUTH_INFO(Object arg0) {
return localizer.localize(localizableWSIMPORT_ILLEGAL_AUTH_INFO(arg0));
}
public static Localizable localizableWSCOMPILE_COMPILATION_FAILED() {
return messageFactory.getMessage("wscompile.compilationFailed");
}
/**
* compilation failed, errors should have been reported
*
*/
public static String WSCOMPILE_COMPILATION_FAILED() {
return localizer.localize(localizableWSCOMPILE_COMPILATION_FAILED());
}
public static Localizable localizableWSCOMPILE_MISSING_OPTION_ARGUMENT(Object arg0) {
return messageFactory.getMessage("wscompile.missingOptionArgument", arg0);
}
/**
* option "{0}" requires an argument
*
*/
public static String WSCOMPILE_MISSING_OPTION_ARGUMENT(Object arg0) {
return localizer.localize(localizableWSCOMPILE_MISSING_OPTION_ARGUMENT(arg0));
}
public static Localizable localizableWSIMPORT_DOCUMENT_DOWNLOAD(Object arg0, Object arg1) {
return messageFactory.getMessage("wsimport.document.download", arg0, arg1);
}
/**
*
* Downloading metadata document from {0} to {1}
*
*/
public static String WSIMPORT_DOCUMENT_DOWNLOAD(Object arg0, Object arg1) {
return localizer.localize(localizableWSIMPORT_DOCUMENT_DOWNLOAD(arg0, arg1));
}
public static Localizable localizableWSGEN_CANNOT_GEN_WSDL_FOR_NON_SOAP_BINDING(Object arg0, Object arg1) {
return messageFactory.getMessage("wsgen.cannot.gen.wsdl.for.non.soap.binding", arg0, arg1);
}
/**
* wsgen can not generate WSDL for non-SOAP binding: {0} on Class {1}
*
*/
public static String WSGEN_CANNOT_GEN_WSDL_FOR_NON_SOAP_BINDING(Object arg0, Object arg1) {
return localizer.localize(localizableWSGEN_CANNOT_GEN_WSDL_FOR_NON_SOAP_BINDING(arg0, arg1));
}
public static Localizable localizableWSCOMPILE_DUPLICATE_OPTION(Object arg0) {
return messageFactory.getMessage("wscompile.duplicateOption", arg0);
}
/**
* duplicate option: {0}
*
*/
public static String WSCOMPILE_DUPLICATE_OPTION(Object arg0) {
return localizer.localize(localizableWSCOMPILE_DUPLICATE_OPTION(arg0));
}
public static Localizable localizableWSIMPORT_FAILED_TO_PARSE(Object arg0, Object arg1) {
return messageFactory.getMessage("wsimport.FailedToParse", arg0, arg1);
}
/**
* Failed to parse "{0}": {1}
*
*/
public static String WSIMPORT_FAILED_TO_PARSE(Object arg0, Object arg1) {
return localizer.localize(localizableWSIMPORT_FAILED_TO_PARSE(arg0, arg1));
}
public static Localizable localizableWSIMPORT_NO_WSDL(Object arg0) {
return messageFactory.getMessage("wsimport.no.wsdl", arg0);
}
/**
* Failed to read the WSDL document: {0}, because 1) could not find the document; /2) the document could not be read; 3) the root element of the document is not <wsdl:definitions>.
*
*/
public static String WSIMPORT_NO_WSDL(Object arg0) {
return localizer.localize(localizableWSIMPORT_NO_WSDL(arg0));
}
public static Localizable localizableWSIMPORT_AUTH_INFO_LINENO(Object arg0, Object arg1) {
return messageFactory.getMessage("wsimport.AUTH_INFO_LINENO", arg0, arg1);
}
/**
* "line {0} of {1}
*
*/
public static String WSIMPORT_AUTH_INFO_LINENO(Object arg0, Object arg1) {
return localizer.localize(localizableWSIMPORT_AUTH_INFO_LINENO(arg0, arg1));
}
public static Localizable localizableWSGEN_SERVICENAME_MISSING_LOCALNAME(Object arg0) {
return messageFactory.getMessage("wsgen.servicename.missing.localname", arg0);
}
/**
* The service name "{0}" is missing a localname.
*
*/
public static String WSGEN_SERVICENAME_MISSING_LOCALNAME(Object arg0) {
return localizer.localize(localizableWSGEN_SERVICENAME_MISSING_LOCALNAME(arg0));
}
public static Localizable localizableWSGEN_USAGE(Object arg0) {
return messageFactory.getMessage("wsgen.usage", arg0);
}
/**
* Usage: {0} [options] <SEI>
*
* Use "wsgen -help" for a detailed description of options.
*
*/
public static String WSGEN_USAGE(Object arg0) {
return localizer.localize(localizableWSGEN_USAGE(arg0));
}
public static Localizable localizableWSGEN_SERVICENAME_MISSING_NAMESPACE(Object arg0) {
return messageFactory.getMessage("wsgen.servicename.missing.namespace", arg0);
}
/**
* The service name "{0}" is missing a namespace.
*
*/
public static String WSGEN_SERVICENAME_MISSING_NAMESPACE(Object arg0) {
return localizer.localize(localizableWSGEN_SERVICENAME_MISSING_NAMESPACE(arg0));
}
public static Localizable localizableWSGEN_INVALID_TRANSPORT(Object arg0, Object arg1) {
return messageFactory.getMessage("wsgen.invalid.transport", arg0, arg1);
}
/**
* "{0}" is not a supported transport. Supported transport includes: {1}.
*
*/
public static String WSGEN_INVALID_TRANSPORT(Object arg0, Object arg1) {
return localizer.localize(localizableWSGEN_INVALID_TRANSPORT(arg0, arg1));
}
public static Localizable localizableWSGEN_CANNOT_GEN_WSDL_FOR_SOAP_12_BINDING(Object arg0, Object arg1) {
return messageFactory.getMessage("wsgen.cannot.gen.wsdl.for.soap12.binding", arg0, arg1);
}
/**
* wsgen can not generate WSDL for SOAP 1.2 binding: {0} on class: {1}.
*
*
*/
public static String WSGEN_CANNOT_GEN_WSDL_FOR_SOAP_12_BINDING(Object arg0, Object arg1) {
return localizer.localize(localizableWSGEN_CANNOT_GEN_WSDL_FOR_SOAP_12_BINDING(arg0, arg1));
}
public static Localizable localizableWSIMPORT_ILLEGAL_TARGET_VERSION(Object arg0) {
return messageFactory.getMessage("wsimport.ILLEGAL_TARGET_VERSION", arg0);
}
/**
* "{0}" is not a valid target version. "2.0" and "2.1" are supported.
*
*/
public static String WSIMPORT_ILLEGAL_TARGET_VERSION(Object arg0) {
return localizer.localize(localizableWSIMPORT_ILLEGAL_TARGET_VERSION(arg0));
}
public static Localizable localizableWSIMPORT_ILLEGAL_PROXY(Object arg0) {
return messageFactory.getMessage("wsimport.ILLEGAL_PROXY", arg0);
}
/**
* "{0}" is not a valid proxy format. The format is [user[:password]@]proxyHost:proxyPort
*
*/
public static String WSIMPORT_ILLEGAL_PROXY(Object arg0) {
return localizer.localize(localizableWSIMPORT_ILLEGAL_PROXY(arg0));
}
public static Localizable localizableWSGEN_PORTNAME_MISSING_LOCALNAME(Object arg0) {
return messageFactory.getMessage("wsgen.portname.missing.localname", arg0);
}
/**
* The port name "{0}" is missing a localname.
*
*/
public static String WSGEN_PORTNAME_MISSING_LOCALNAME(Object arg0) {
return localizer.localize(localizableWSGEN_PORTNAME_MISSING_LOCALNAME(arg0));
}
public static Localizable localizableWSGEN_PORTNAME_MISSING_NAMESPACE(Object arg0) {
return messageFactory.getMessage("wsgen.portname.missing.namespace", arg0);
}
/**
* The port name "{0}" is missing a namespace.
*
*/
public static String WSGEN_PORTNAME_MISSING_NAMESPACE(Object arg0) {
return localizer.localize(localizableWSGEN_PORTNAME_MISSING_NAMESPACE(arg0));
}
public static Localizable localizableWSIMPORT_FULLVERSION(Object arg0) {
return messageFactory.getMessage("wsimport.fullversion", arg0);
}
/**
* wsimport full version "{0}"
*
*/
public static String WSIMPORT_FULLVERSION(Object arg0) {
return localizer.localize(localizableWSIMPORT_FULLVERSION(arg0));
}
}
|
googleapis/google-cloud-java | 36,489 | java-securitycentermanagement/proto-google-cloud-securitycentermanagement-v1/src/main/java/com/google/cloud/securitycentermanagement/v1/ListDescendantEventThreatDetectionCustomModulesRequest.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.ListDescendantEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules].
* </pre>
*
* Protobuf type {@code
* google.cloud.securitycentermanagement.v1.ListDescendantEventThreatDetectionCustomModulesRequest}
*/
public final class ListDescendantEventThreatDetectionCustomModulesRequest
extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.securitycentermanagement.v1.ListDescendantEventThreatDetectionCustomModulesRequest)
ListDescendantEventThreatDetectionCustomModulesRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListDescendantEventThreatDetectionCustomModulesRequest.newBuilder() to construct.
private ListDescendantEventThreatDetectionCustomModulesRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListDescendantEventThreatDetectionCustomModulesRequest() {
parent_ = "";
pageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListDescendantEventThreatDetectionCustomModulesRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto
.internal_static_google_cloud_securitycentermanagement_v1_ListDescendantEventThreatDetectionCustomModulesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto
.internal_static_google_cloud_securitycentermanagement_v1_ListDescendantEventThreatDetectionCustomModulesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest.class,
com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Name of parent to list custom modules, in one of the following
* formats:
*
* * `organizations/{organization}/locations/{location}`
* * `folders/{folder}/locations/{location}`
* * `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Name of parent to list custom modules, in one of the following
* formats:
*
* * `organizations/{organization}/locations/{location}`
* * `folders/{folder}/locations/{location}`
* * `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* Optional. The maximum number of modules to return. The service may return
* fewer than this value. If unspecified, at most 10 configs will be returned.
* The maximum value is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Optional. A pagination token returned from a previous request. Provide this
* token to retrieve the next page of results.
*
* When paginating, the rest of the request must match the request that
* generated the page token.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. A pagination token returned from a previous request. Provide this
* token to retrieve the next page of results.
*
* When paginating, the rest of the request must match the request that
* generated the page token.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj
instanceof
com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest)) {
return super.equals(obj);
}
com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest
other =
(com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest)
obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest
parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest
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
.ListDescendantEventThreatDetectionCustomModulesRequest
parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest
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
.ListDescendantEventThreatDetectionCustomModulesRequest
parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest
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
.ListDescendantEventThreatDetectionCustomModulesRequest
parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest
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
.ListDescendantEventThreatDetectionCustomModulesRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest
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
.ListDescendantEventThreatDetectionCustomModulesRequest
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
.ListDescendantEventThreatDetectionCustomModulesRequest
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
.ListDescendantEventThreatDetectionCustomModulesRequest
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.ListDescendantEventThreatDetectionCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantEventThreatDetectionCustomModules].
* </pre>
*
* Protobuf type {@code
* google.cloud.securitycentermanagement.v1.ListDescendantEventThreatDetectionCustomModulesRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.securitycentermanagement.v1.ListDescendantEventThreatDetectionCustomModulesRequest)
com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto
.internal_static_google_cloud_securitycentermanagement_v1_ListDescendantEventThreatDetectionCustomModulesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto
.internal_static_google_cloud_securitycentermanagement_v1_ListDescendantEventThreatDetectionCustomModulesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest.class,
com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest.Builder.class);
}
// Construct using
// com.google.cloud.securitycentermanagement.v1.ListDescendantEventThreatDetectionCustomModulesRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto
.internal_static_google_cloud_securitycentermanagement_v1_ListDescendantEventThreatDetectionCustomModulesRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest
getDefaultInstanceForType() {
return com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest
build() {
com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest
result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest
buildPartial() {
com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest
result =
new com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest
result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other
instanceof
com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest) {
return mergeFrom(
(com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest)
other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest
other) {
if (other
== com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Name of parent to list custom modules, in one of the following
* formats:
*
* * `organizations/{organization}/locations/{location}`
* * `folders/{folder}/locations/{location}`
* * `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Name of parent to list custom modules, in one of the following
* formats:
*
* * `organizations/{organization}/locations/{location}`
* * `folders/{folder}/locations/{location}`
* * `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Name of parent to list custom modules, in one of the following
* formats:
*
* * `organizations/{organization}/locations/{location}`
* * `folders/{folder}/locations/{location}`
* * `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Name of parent to list custom modules, in one of the following
* formats:
*
* * `organizations/{organization}/locations/{location}`
* * `folders/{folder}/locations/{location}`
* * `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Name of parent to list custom modules, in one of the following
* formats:
*
* * `organizations/{organization}/locations/{location}`
* * `folders/{folder}/locations/{location}`
* * `projects/{project}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Optional. The maximum number of modules to return. The service may return
* fewer than this value. If unspecified, at most 10 configs will be returned.
* The maximum value is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Optional. The maximum number of modules to return. The service may return
* fewer than this value. If unspecified, at most 10 configs will be returned.
* The maximum value is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The maximum number of modules to return. The service may return
* fewer than this value. If unspecified, at most 10 configs will be returned.
* The maximum value is 1000; values above 1000 will be coerced to 1000.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Optional. A pagination token returned from a previous request. Provide this
* token to retrieve the next page of results.
*
* When paginating, the rest of the request must match the request that
* generated the page token.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. A pagination token returned from a previous request. Provide this
* token to retrieve the next page of results.
*
* When paginating, the rest of the request must match the request that
* generated the page token.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. A pagination token returned from a previous request. Provide this
* token to retrieve the next page of results.
*
* When paginating, the rest of the request must match the request that
* generated the page token.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A pagination token returned from a previous request. Provide this
* token to retrieve the next page of results.
*
* When paginating, the rest of the request must match the request that
* generated the page token.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. A pagination token returned from a previous request. Provide this
* token to retrieve the next page of results.
*
* When paginating, the rest of the request must match the request that
* generated the page token.
* </pre>
*
* <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.securitycentermanagement.v1.ListDescendantEventThreatDetectionCustomModulesRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.securitycentermanagement.v1.ListDescendantEventThreatDetectionCustomModulesRequest)
private static final com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE =
new com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest();
}
public static com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<
ListDescendantEventThreatDetectionCustomModulesRequest>
PARSER =
new com.google.protobuf.AbstractParser<
ListDescendantEventThreatDetectionCustomModulesRequest>() {
@java.lang.Override
public ListDescendantEventThreatDetectionCustomModulesRequest 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<ListDescendantEventThreatDetectionCustomModulesRequest>
parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListDescendantEventThreatDetectionCustomModulesRequest>
getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.securitycentermanagement.v1
.ListDescendantEventThreatDetectionCustomModulesRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,421 | java-infra-manager/proto-google-cloud-infra-manager-v1/src/main/java/com/google/cloud/config/v1/ResourceDriftTerraformInfo.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/config/v1/config.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.config.v1;
/**
*
*
* <pre>
* Terraform info of a ResourceChange.
* </pre>
*
* Protobuf type {@code google.cloud.config.v1.ResourceDriftTerraformInfo}
*/
public final class ResourceDriftTerraformInfo extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.config.v1.ResourceDriftTerraformInfo)
ResourceDriftTerraformInfoOrBuilder {
private static final long serialVersionUID = 0L;
// Use ResourceDriftTerraformInfo.newBuilder() to construct.
private ResourceDriftTerraformInfo(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ResourceDriftTerraformInfo() {
address_ = "";
type_ = "";
resourceName_ = "";
provider_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ResourceDriftTerraformInfo();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.config.v1.ConfigProto
.internal_static_google_cloud_config_v1_ResourceDriftTerraformInfo_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.config.v1.ConfigProto
.internal_static_google_cloud_config_v1_ResourceDriftTerraformInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.config.v1.ResourceDriftTerraformInfo.class,
com.google.cloud.config.v1.ResourceDriftTerraformInfo.Builder.class);
}
public static final int ADDRESS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object address_ = "";
/**
*
*
* <pre>
* Output only. The address of the drifted resource.
* </pre>
*
* <code>string address = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The address.
*/
@java.lang.Override
public java.lang.String getAddress() {
java.lang.Object ref = address_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
address_ = s;
return s;
}
}
/**
*
*
* <pre>
* Output only. The address of the drifted resource.
* </pre>
*
* <code>string address = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for address.
*/
@java.lang.Override
public com.google.protobuf.ByteString getAddressBytes() {
java.lang.Object ref = address_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
address_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TYPE_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object type_ = "";
/**
*
*
* <pre>
* Output only. The type of the drifted resource.
* </pre>
*
* <code>string type = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</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>
* Output only. The type of the drifted resource.
* </pre>
*
* <code>string type = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for type.
*/
@java.lang.Override
public com.google.protobuf.ByteString getTypeBytes() {
java.lang.Object ref = type_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
type_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int RESOURCE_NAME_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object resourceName_ = "";
/**
*
*
* <pre>
* Output only. TF resource name.
* </pre>
*
* <code>string resource_name = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The resourceName.
*/
@java.lang.Override
public java.lang.String getResourceName() {
java.lang.Object ref = resourceName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resourceName_ = s;
return s;
}
}
/**
*
*
* <pre>
* Output only. TF resource name.
* </pre>
*
* <code>string resource_name = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for resourceName.
*/
@java.lang.Override
public com.google.protobuf.ByteString getResourceNameBytes() {
java.lang.Object ref = resourceName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resourceName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PROVIDER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object provider_ = "";
/**
*
*
* <pre>
* Output only. The provider of the drifted resource.
* </pre>
*
* <code>string provider = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The provider.
*/
@java.lang.Override
public java.lang.String getProvider() {
java.lang.Object ref = provider_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
provider_ = s;
return s;
}
}
/**
*
*
* <pre>
* Output only. The provider of the drifted resource.
* </pre>
*
* <code>string provider = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for provider.
*/
@java.lang.Override
public com.google.protobuf.ByteString getProviderBytes() {
java.lang.Object ref = provider_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
provider_ = 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(address_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, address_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(type_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, type_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, resourceName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(provider_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, provider_);
}
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(address_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, address_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(type_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, type_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, resourceName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(provider_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, provider_);
}
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.config.v1.ResourceDriftTerraformInfo)) {
return super.equals(obj);
}
com.google.cloud.config.v1.ResourceDriftTerraformInfo other =
(com.google.cloud.config.v1.ResourceDriftTerraformInfo) obj;
if (!getAddress().equals(other.getAddress())) return false;
if (!getType().equals(other.getType())) return false;
if (!getResourceName().equals(other.getResourceName())) return false;
if (!getProvider().equals(other.getProvider())) 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) + ADDRESS_FIELD_NUMBER;
hash = (53 * hash) + getAddress().hashCode();
hash = (37 * hash) + TYPE_FIELD_NUMBER;
hash = (53 * hash) + getType().hashCode();
hash = (37 * hash) + RESOURCE_NAME_FIELD_NUMBER;
hash = (53 * hash) + getResourceName().hashCode();
hash = (37 * hash) + PROVIDER_FIELD_NUMBER;
hash = (53 * hash) + getProvider().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.config.v1.ResourceDriftTerraformInfo parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.config.v1.ResourceDriftTerraformInfo 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.config.v1.ResourceDriftTerraformInfo parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.config.v1.ResourceDriftTerraformInfo 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.config.v1.ResourceDriftTerraformInfo parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.config.v1.ResourceDriftTerraformInfo parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.config.v1.ResourceDriftTerraformInfo parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.config.v1.ResourceDriftTerraformInfo 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.config.v1.ResourceDriftTerraformInfo parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.config.v1.ResourceDriftTerraformInfo 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.config.v1.ResourceDriftTerraformInfo parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.config.v1.ResourceDriftTerraformInfo 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.config.v1.ResourceDriftTerraformInfo 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>
* Terraform info of a ResourceChange.
* </pre>
*
* Protobuf type {@code google.cloud.config.v1.ResourceDriftTerraformInfo}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.config.v1.ResourceDriftTerraformInfo)
com.google.cloud.config.v1.ResourceDriftTerraformInfoOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.config.v1.ConfigProto
.internal_static_google_cloud_config_v1_ResourceDriftTerraformInfo_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.config.v1.ConfigProto
.internal_static_google_cloud_config_v1_ResourceDriftTerraformInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.config.v1.ResourceDriftTerraformInfo.class,
com.google.cloud.config.v1.ResourceDriftTerraformInfo.Builder.class);
}
// Construct using com.google.cloud.config.v1.ResourceDriftTerraformInfo.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
address_ = "";
type_ = "";
resourceName_ = "";
provider_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.config.v1.ConfigProto
.internal_static_google_cloud_config_v1_ResourceDriftTerraformInfo_descriptor;
}
@java.lang.Override
public com.google.cloud.config.v1.ResourceDriftTerraformInfo getDefaultInstanceForType() {
return com.google.cloud.config.v1.ResourceDriftTerraformInfo.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.config.v1.ResourceDriftTerraformInfo build() {
com.google.cloud.config.v1.ResourceDriftTerraformInfo result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.config.v1.ResourceDriftTerraformInfo buildPartial() {
com.google.cloud.config.v1.ResourceDriftTerraformInfo result =
new com.google.cloud.config.v1.ResourceDriftTerraformInfo(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.config.v1.ResourceDriftTerraformInfo result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.address_ = address_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.type_ = type_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.resourceName_ = resourceName_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.provider_ = provider_;
}
}
@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.config.v1.ResourceDriftTerraformInfo) {
return mergeFrom((com.google.cloud.config.v1.ResourceDriftTerraformInfo) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.config.v1.ResourceDriftTerraformInfo other) {
if (other == com.google.cloud.config.v1.ResourceDriftTerraformInfo.getDefaultInstance())
return this;
if (!other.getAddress().isEmpty()) {
address_ = other.address_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getType().isEmpty()) {
type_ = other.type_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getResourceName().isEmpty()) {
resourceName_ = other.resourceName_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getProvider().isEmpty()) {
provider_ = other.provider_;
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:
{
address_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
type_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
resourceName_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
provider_ = 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 address_ = "";
/**
*
*
* <pre>
* Output only. The address of the drifted resource.
* </pre>
*
* <code>string address = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The address.
*/
public java.lang.String getAddress() {
java.lang.Object ref = address_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
address_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Output only. The address of the drifted resource.
* </pre>
*
* <code>string address = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for address.
*/
public com.google.protobuf.ByteString getAddressBytes() {
java.lang.Object ref = address_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
address_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Output only. The address of the drifted resource.
* </pre>
*
* <code>string address = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @param value The address to set.
* @return This builder for chaining.
*/
public Builder setAddress(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
address_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The address of the drifted resource.
* </pre>
*
* <code>string address = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return This builder for chaining.
*/
public Builder clearAddress() {
address_ = getDefaultInstance().getAddress();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The address of the drifted resource.
* </pre>
*
* <code>string address = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @param value The bytes for address to set.
* @return This builder for chaining.
*/
public Builder setAddressBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
address_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object type_ = "";
/**
*
*
* <pre>
* Output only. The type of the drifted resource.
* </pre>
*
* <code>string type = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</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>
* Output only. The type of the drifted resource.
* </pre>
*
* <code>string type = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</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>
* Output only. The type of the drifted resource.
* </pre>
*
* <code>string type = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</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_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The type of the drifted resource.
* </pre>
*
* <code>string type = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return This builder for chaining.
*/
public Builder clearType() {
type_ = getDefaultInstance().getType();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The type of the drifted resource.
* </pre>
*
* <code>string type = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</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_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object resourceName_ = "";
/**
*
*
* <pre>
* Output only. TF resource name.
* </pre>
*
* <code>string resource_name = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The resourceName.
*/
public java.lang.String getResourceName() {
java.lang.Object ref = resourceName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resourceName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Output only. TF resource name.
* </pre>
*
* <code>string resource_name = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for resourceName.
*/
public com.google.protobuf.ByteString getResourceNameBytes() {
java.lang.Object ref = resourceName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resourceName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Output only. TF resource name.
* </pre>
*
* <code>string resource_name = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @param value The resourceName to set.
* @return This builder for chaining.
*/
public Builder setResourceName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
resourceName_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. TF resource name.
* </pre>
*
* <code>string resource_name = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return This builder for chaining.
*/
public Builder clearResourceName() {
resourceName_ = getDefaultInstance().getResourceName();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. TF resource name.
* </pre>
*
* <code>string resource_name = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @param value The bytes for resourceName to set.
* @return This builder for chaining.
*/
public Builder setResourceNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
resourceName_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object provider_ = "";
/**
*
*
* <pre>
* Output only. The provider of the drifted resource.
* </pre>
*
* <code>string provider = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The provider.
*/
public java.lang.String getProvider() {
java.lang.Object ref = provider_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
provider_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Output only. The provider of the drifted resource.
* </pre>
*
* <code>string provider = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for provider.
*/
public com.google.protobuf.ByteString getProviderBytes() {
java.lang.Object ref = provider_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
provider_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Output only. The provider of the drifted resource.
* </pre>
*
* <code>string provider = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @param value The provider to set.
* @return This builder for chaining.
*/
public Builder setProvider(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
provider_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The provider of the drifted resource.
* </pre>
*
* <code>string provider = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return This builder for chaining.
*/
public Builder clearProvider() {
provider_ = getDefaultInstance().getProvider();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Output only. The provider of the drifted resource.
* </pre>
*
* <code>string provider = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @param value The bytes for provider to set.
* @return This builder for chaining.
*/
public Builder setProviderBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
provider_ = 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.config.v1.ResourceDriftTerraformInfo)
}
// @@protoc_insertion_point(class_scope:google.cloud.config.v1.ResourceDriftTerraformInfo)
private static final com.google.cloud.config.v1.ResourceDriftTerraformInfo DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.config.v1.ResourceDriftTerraformInfo();
}
public static com.google.cloud.config.v1.ResourceDriftTerraformInfo getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ResourceDriftTerraformInfo> PARSER =
new com.google.protobuf.AbstractParser<ResourceDriftTerraformInfo>() {
@java.lang.Override
public ResourceDriftTerraformInfo 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<ResourceDriftTerraformInfo> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ResourceDriftTerraformInfo> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.config.v1.ResourceDriftTerraformInfo getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 36,667 | google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/common/VideoTrueViewInStreamAdInfo.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v19/common/ad_type_infos.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v19.common;
/**
* <pre>
* Representation of video TrueView in-stream ad format (ad shown during video
* playback, often at beginning, which displays a skip button a few seconds into
* the video).
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo}
*/
public final class VideoTrueViewInStreamAdInfo extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo)
VideoTrueViewInStreamAdInfoOrBuilder {
private static final long serialVersionUID = 0L;
// Use VideoTrueViewInStreamAdInfo.newBuilder() to construct.
private VideoTrueViewInStreamAdInfo(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private VideoTrueViewInStreamAdInfo() {
actionButtonLabel_ = "";
actionHeadline_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new VideoTrueViewInStreamAdInfo();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.common.AdTypeInfosProto.internal_static_google_ads_googleads_v19_common_VideoTrueViewInStreamAdInfo_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.common.AdTypeInfosProto.internal_static_google_ads_googleads_v19_common_VideoTrueViewInStreamAdInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo.class, com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo.Builder.class);
}
private int bitField0_;
public static final int ACTION_BUTTON_LABEL_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object actionButtonLabel_ = "";
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @return The actionButtonLabel.
*/
@java.lang.Override
public java.lang.String getActionButtonLabel() {
java.lang.Object ref = actionButtonLabel_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
actionButtonLabel_ = s;
return s;
}
}
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @return The bytes for actionButtonLabel.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getActionButtonLabelBytes() {
java.lang.Object ref = actionButtonLabel_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
actionButtonLabel_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ACTION_HEADLINE_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object actionHeadline_ = "";
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @return The actionHeadline.
*/
@java.lang.Override
public java.lang.String getActionHeadline() {
java.lang.Object ref = actionHeadline_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
actionHeadline_ = s;
return s;
}
}
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @return The bytes for actionHeadline.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getActionHeadlineBytes() {
java.lang.Object ref = actionHeadline_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
actionHeadline_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int COMPANION_BANNER_FIELD_NUMBER = 7;
private com.google.ads.googleads.v19.common.AdImageAsset companionBanner_;
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v19.common.AdImageAsset companion_banner = 7;</code>
* @return Whether the companionBanner field is set.
*/
@java.lang.Override
public boolean hasCompanionBanner() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v19.common.AdImageAsset companion_banner = 7;</code>
* @return The companionBanner.
*/
@java.lang.Override
public com.google.ads.googleads.v19.common.AdImageAsset getCompanionBanner() {
return companionBanner_ == null ? com.google.ads.googleads.v19.common.AdImageAsset.getDefaultInstance() : companionBanner_;
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v19.common.AdImageAsset companion_banner = 7;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v19.common.AdImageAssetOrBuilder getCompanionBannerOrBuilder() {
return companionBanner_ == null ? com.google.ads.googleads.v19.common.AdImageAsset.getDefaultInstance() : companionBanner_;
}
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(actionButtonLabel_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, actionButtonLabel_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(actionHeadline_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, actionHeadline_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(7, getCompanionBanner());
}
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(actionButtonLabel_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, actionButtonLabel_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(actionHeadline_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, actionHeadline_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(7, getCompanionBanner());
}
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.common.VideoTrueViewInStreamAdInfo)) {
return super.equals(obj);
}
com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo other = (com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo) obj;
if (!getActionButtonLabel()
.equals(other.getActionButtonLabel())) return false;
if (!getActionHeadline()
.equals(other.getActionHeadline())) return false;
if (hasCompanionBanner() != other.hasCompanionBanner()) return false;
if (hasCompanionBanner()) {
if (!getCompanionBanner()
.equals(other.getCompanionBanner())) 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) + ACTION_BUTTON_LABEL_FIELD_NUMBER;
hash = (53 * hash) + getActionButtonLabel().hashCode();
hash = (37 * hash) + ACTION_HEADLINE_FIELD_NUMBER;
hash = (53 * hash) + getActionHeadline().hashCode();
if (hasCompanionBanner()) {
hash = (37 * hash) + COMPANION_BANNER_FIELD_NUMBER;
hash = (53 * hash) + getCompanionBanner().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo 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>
* Representation of video TrueView in-stream ad format (ad shown during video
* playback, often at beginning, which displays a skip button a few seconds into
* the video).
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo)
com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfoOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.common.AdTypeInfosProto.internal_static_google_ads_googleads_v19_common_VideoTrueViewInStreamAdInfo_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.common.AdTypeInfosProto.internal_static_google_ads_googleads_v19_common_VideoTrueViewInStreamAdInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo.class, com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo.Builder.class);
}
// Construct using com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getCompanionBannerFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
actionButtonLabel_ = "";
actionHeadline_ = "";
companionBanner_ = null;
if (companionBannerBuilder_ != null) {
companionBannerBuilder_.dispose();
companionBannerBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v19.common.AdTypeInfosProto.internal_static_google_ads_googleads_v19_common_VideoTrueViewInStreamAdInfo_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo getDefaultInstanceForType() {
return com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo build() {
com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo buildPartial() {
com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo result = new com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.actionButtonLabel_ = actionButtonLabel_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.actionHeadline_ = actionHeadline_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.companionBanner_ = companionBannerBuilder_ == null
? companionBanner_
: companionBannerBuilder_.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.common.VideoTrueViewInStreamAdInfo) {
return mergeFrom((com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo other) {
if (other == com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo.getDefaultInstance()) return this;
if (!other.getActionButtonLabel().isEmpty()) {
actionButtonLabel_ = other.actionButtonLabel_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getActionHeadline().isEmpty()) {
actionHeadline_ = other.actionHeadline_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasCompanionBanner()) {
mergeCompanionBanner(other.getCompanionBanner());
}
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 34: {
actionButtonLabel_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 34
case 42: {
actionHeadline_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 42
case 58: {
input.readMessage(
getCompanionBannerFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000004;
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 actionButtonLabel_ = "";
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @return The actionButtonLabel.
*/
public java.lang.String getActionButtonLabel() {
java.lang.Object ref = actionButtonLabel_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
actionButtonLabel_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @return The bytes for actionButtonLabel.
*/
public com.google.protobuf.ByteString
getActionButtonLabelBytes() {
java.lang.Object ref = actionButtonLabel_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
actionButtonLabel_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @param value The actionButtonLabel to set.
* @return This builder for chaining.
*/
public Builder setActionButtonLabel(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
actionButtonLabel_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @return This builder for chaining.
*/
public Builder clearActionButtonLabel() {
actionButtonLabel_ = getDefaultInstance().getActionButtonLabel();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @param value The bytes for actionButtonLabel to set.
* @return This builder for chaining.
*/
public Builder setActionButtonLabelBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
actionButtonLabel_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object actionHeadline_ = "";
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @return The actionHeadline.
*/
public java.lang.String getActionHeadline() {
java.lang.Object ref = actionHeadline_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
actionHeadline_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @return The bytes for actionHeadline.
*/
public com.google.protobuf.ByteString
getActionHeadlineBytes() {
java.lang.Object ref = actionHeadline_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
actionHeadline_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @param value The actionHeadline to set.
* @return This builder for chaining.
*/
public Builder setActionHeadline(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
actionHeadline_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @return This builder for chaining.
*/
public Builder clearActionHeadline() {
actionHeadline_ = getDefaultInstance().getActionHeadline();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @param value The bytes for actionHeadline to set.
* @return This builder for chaining.
*/
public Builder setActionHeadlineBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
actionHeadline_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.ads.googleads.v19.common.AdImageAsset companionBanner_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.common.AdImageAsset, com.google.ads.googleads.v19.common.AdImageAsset.Builder, com.google.ads.googleads.v19.common.AdImageAssetOrBuilder> companionBannerBuilder_;
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v19.common.AdImageAsset companion_banner = 7;</code>
* @return Whether the companionBanner field is set.
*/
public boolean hasCompanionBanner() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v19.common.AdImageAsset companion_banner = 7;</code>
* @return The companionBanner.
*/
public com.google.ads.googleads.v19.common.AdImageAsset getCompanionBanner() {
if (companionBannerBuilder_ == null) {
return companionBanner_ == null ? com.google.ads.googleads.v19.common.AdImageAsset.getDefaultInstance() : companionBanner_;
} else {
return companionBannerBuilder_.getMessage();
}
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v19.common.AdImageAsset companion_banner = 7;</code>
*/
public Builder setCompanionBanner(com.google.ads.googleads.v19.common.AdImageAsset value) {
if (companionBannerBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
companionBanner_ = value;
} else {
companionBannerBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v19.common.AdImageAsset companion_banner = 7;</code>
*/
public Builder setCompanionBanner(
com.google.ads.googleads.v19.common.AdImageAsset.Builder builderForValue) {
if (companionBannerBuilder_ == null) {
companionBanner_ = builderForValue.build();
} else {
companionBannerBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v19.common.AdImageAsset companion_banner = 7;</code>
*/
public Builder mergeCompanionBanner(com.google.ads.googleads.v19.common.AdImageAsset value) {
if (companionBannerBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0) &&
companionBanner_ != null &&
companionBanner_ != com.google.ads.googleads.v19.common.AdImageAsset.getDefaultInstance()) {
getCompanionBannerBuilder().mergeFrom(value);
} else {
companionBanner_ = value;
}
} else {
companionBannerBuilder_.mergeFrom(value);
}
if (companionBanner_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v19.common.AdImageAsset companion_banner = 7;</code>
*/
public Builder clearCompanionBanner() {
bitField0_ = (bitField0_ & ~0x00000004);
companionBanner_ = null;
if (companionBannerBuilder_ != null) {
companionBannerBuilder_.dispose();
companionBannerBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v19.common.AdImageAsset companion_banner = 7;</code>
*/
public com.google.ads.googleads.v19.common.AdImageAsset.Builder getCompanionBannerBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getCompanionBannerFieldBuilder().getBuilder();
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v19.common.AdImageAsset companion_banner = 7;</code>
*/
public com.google.ads.googleads.v19.common.AdImageAssetOrBuilder getCompanionBannerOrBuilder() {
if (companionBannerBuilder_ != null) {
return companionBannerBuilder_.getMessageOrBuilder();
} else {
return companionBanner_ == null ?
com.google.ads.googleads.v19.common.AdImageAsset.getDefaultInstance() : companionBanner_;
}
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v19.common.AdImageAsset companion_banner = 7;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.common.AdImageAsset, com.google.ads.googleads.v19.common.AdImageAsset.Builder, com.google.ads.googleads.v19.common.AdImageAssetOrBuilder>
getCompanionBannerFieldBuilder() {
if (companionBannerBuilder_ == null) {
companionBannerBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.common.AdImageAsset, com.google.ads.googleads.v19.common.AdImageAsset.Builder, com.google.ads.googleads.v19.common.AdImageAssetOrBuilder>(
getCompanionBanner(),
getParentForChildren(),
isClean());
companionBanner_ = null;
}
return companionBannerBuilder_;
}
@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.common.VideoTrueViewInStreamAdInfo)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo)
private static final com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo();
}
public static com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<VideoTrueViewInStreamAdInfo>
PARSER = new com.google.protobuf.AbstractParser<VideoTrueViewInStreamAdInfo>() {
@java.lang.Override
public VideoTrueViewInStreamAdInfo 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<VideoTrueViewInStreamAdInfo> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<VideoTrueViewInStreamAdInfo> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v19.common.VideoTrueViewInStreamAdInfo getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 36,667 | google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/common/VideoTrueViewInStreamAdInfo.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v20/common/ad_type_infos.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v20.common;
/**
* <pre>
* Representation of video TrueView in-stream ad format (ad shown during video
* playback, often at beginning, which displays a skip button a few seconds into
* the video).
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo}
*/
public final class VideoTrueViewInStreamAdInfo extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo)
VideoTrueViewInStreamAdInfoOrBuilder {
private static final long serialVersionUID = 0L;
// Use VideoTrueViewInStreamAdInfo.newBuilder() to construct.
private VideoTrueViewInStreamAdInfo(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private VideoTrueViewInStreamAdInfo() {
actionButtonLabel_ = "";
actionHeadline_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new VideoTrueViewInStreamAdInfo();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.common.AdTypeInfosProto.internal_static_google_ads_googleads_v20_common_VideoTrueViewInStreamAdInfo_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.common.AdTypeInfosProto.internal_static_google_ads_googleads_v20_common_VideoTrueViewInStreamAdInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo.class, com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo.Builder.class);
}
private int bitField0_;
public static final int ACTION_BUTTON_LABEL_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object actionButtonLabel_ = "";
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @return The actionButtonLabel.
*/
@java.lang.Override
public java.lang.String getActionButtonLabel() {
java.lang.Object ref = actionButtonLabel_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
actionButtonLabel_ = s;
return s;
}
}
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @return The bytes for actionButtonLabel.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getActionButtonLabelBytes() {
java.lang.Object ref = actionButtonLabel_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
actionButtonLabel_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ACTION_HEADLINE_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object actionHeadline_ = "";
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @return The actionHeadline.
*/
@java.lang.Override
public java.lang.String getActionHeadline() {
java.lang.Object ref = actionHeadline_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
actionHeadline_ = s;
return s;
}
}
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @return The bytes for actionHeadline.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getActionHeadlineBytes() {
java.lang.Object ref = actionHeadline_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
actionHeadline_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int COMPANION_BANNER_FIELD_NUMBER = 7;
private com.google.ads.googleads.v20.common.AdImageAsset companionBanner_;
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v20.common.AdImageAsset companion_banner = 7;</code>
* @return Whether the companionBanner field is set.
*/
@java.lang.Override
public boolean hasCompanionBanner() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v20.common.AdImageAsset companion_banner = 7;</code>
* @return The companionBanner.
*/
@java.lang.Override
public com.google.ads.googleads.v20.common.AdImageAsset getCompanionBanner() {
return companionBanner_ == null ? com.google.ads.googleads.v20.common.AdImageAsset.getDefaultInstance() : companionBanner_;
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v20.common.AdImageAsset companion_banner = 7;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v20.common.AdImageAssetOrBuilder getCompanionBannerOrBuilder() {
return companionBanner_ == null ? com.google.ads.googleads.v20.common.AdImageAsset.getDefaultInstance() : companionBanner_;
}
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(actionButtonLabel_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, actionButtonLabel_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(actionHeadline_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, actionHeadline_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(7, getCompanionBanner());
}
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(actionButtonLabel_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, actionButtonLabel_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(actionHeadline_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, actionHeadline_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(7, getCompanionBanner());
}
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.common.VideoTrueViewInStreamAdInfo)) {
return super.equals(obj);
}
com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo other = (com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo) obj;
if (!getActionButtonLabel()
.equals(other.getActionButtonLabel())) return false;
if (!getActionHeadline()
.equals(other.getActionHeadline())) return false;
if (hasCompanionBanner() != other.hasCompanionBanner()) return false;
if (hasCompanionBanner()) {
if (!getCompanionBanner()
.equals(other.getCompanionBanner())) 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) + ACTION_BUTTON_LABEL_FIELD_NUMBER;
hash = (53 * hash) + getActionButtonLabel().hashCode();
hash = (37 * hash) + ACTION_HEADLINE_FIELD_NUMBER;
hash = (53 * hash) + getActionHeadline().hashCode();
if (hasCompanionBanner()) {
hash = (37 * hash) + COMPANION_BANNER_FIELD_NUMBER;
hash = (53 * hash) + getCompanionBanner().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo 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>
* Representation of video TrueView in-stream ad format (ad shown during video
* playback, often at beginning, which displays a skip button a few seconds into
* the video).
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo)
com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfoOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.common.AdTypeInfosProto.internal_static_google_ads_googleads_v20_common_VideoTrueViewInStreamAdInfo_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.common.AdTypeInfosProto.internal_static_google_ads_googleads_v20_common_VideoTrueViewInStreamAdInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo.class, com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo.Builder.class);
}
// Construct using com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getCompanionBannerFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
actionButtonLabel_ = "";
actionHeadline_ = "";
companionBanner_ = null;
if (companionBannerBuilder_ != null) {
companionBannerBuilder_.dispose();
companionBannerBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v20.common.AdTypeInfosProto.internal_static_google_ads_googleads_v20_common_VideoTrueViewInStreamAdInfo_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo getDefaultInstanceForType() {
return com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo build() {
com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo buildPartial() {
com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo result = new com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.actionButtonLabel_ = actionButtonLabel_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.actionHeadline_ = actionHeadline_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.companionBanner_ = companionBannerBuilder_ == null
? companionBanner_
: companionBannerBuilder_.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.common.VideoTrueViewInStreamAdInfo) {
return mergeFrom((com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo other) {
if (other == com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo.getDefaultInstance()) return this;
if (!other.getActionButtonLabel().isEmpty()) {
actionButtonLabel_ = other.actionButtonLabel_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getActionHeadline().isEmpty()) {
actionHeadline_ = other.actionHeadline_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasCompanionBanner()) {
mergeCompanionBanner(other.getCompanionBanner());
}
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 34: {
actionButtonLabel_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 34
case 42: {
actionHeadline_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 42
case 58: {
input.readMessage(
getCompanionBannerFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000004;
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 actionButtonLabel_ = "";
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @return The actionButtonLabel.
*/
public java.lang.String getActionButtonLabel() {
java.lang.Object ref = actionButtonLabel_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
actionButtonLabel_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @return The bytes for actionButtonLabel.
*/
public com.google.protobuf.ByteString
getActionButtonLabelBytes() {
java.lang.Object ref = actionButtonLabel_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
actionButtonLabel_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @param value The actionButtonLabel to set.
* @return This builder for chaining.
*/
public Builder setActionButtonLabel(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
actionButtonLabel_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @return This builder for chaining.
*/
public Builder clearActionButtonLabel() {
actionButtonLabel_ = getDefaultInstance().getActionButtonLabel();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @param value The bytes for actionButtonLabel to set.
* @return This builder for chaining.
*/
public Builder setActionButtonLabelBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
actionButtonLabel_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object actionHeadline_ = "";
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @return The actionHeadline.
*/
public java.lang.String getActionHeadline() {
java.lang.Object ref = actionHeadline_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
actionHeadline_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @return The bytes for actionHeadline.
*/
public com.google.protobuf.ByteString
getActionHeadlineBytes() {
java.lang.Object ref = actionHeadline_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
actionHeadline_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @param value The actionHeadline to set.
* @return This builder for chaining.
*/
public Builder setActionHeadline(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
actionHeadline_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @return This builder for chaining.
*/
public Builder clearActionHeadline() {
actionHeadline_ = getDefaultInstance().getActionHeadline();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @param value The bytes for actionHeadline to set.
* @return This builder for chaining.
*/
public Builder setActionHeadlineBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
actionHeadline_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.ads.googleads.v20.common.AdImageAsset companionBanner_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.common.AdImageAsset, com.google.ads.googleads.v20.common.AdImageAsset.Builder, com.google.ads.googleads.v20.common.AdImageAssetOrBuilder> companionBannerBuilder_;
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v20.common.AdImageAsset companion_banner = 7;</code>
* @return Whether the companionBanner field is set.
*/
public boolean hasCompanionBanner() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v20.common.AdImageAsset companion_banner = 7;</code>
* @return The companionBanner.
*/
public com.google.ads.googleads.v20.common.AdImageAsset getCompanionBanner() {
if (companionBannerBuilder_ == null) {
return companionBanner_ == null ? com.google.ads.googleads.v20.common.AdImageAsset.getDefaultInstance() : companionBanner_;
} else {
return companionBannerBuilder_.getMessage();
}
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v20.common.AdImageAsset companion_banner = 7;</code>
*/
public Builder setCompanionBanner(com.google.ads.googleads.v20.common.AdImageAsset value) {
if (companionBannerBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
companionBanner_ = value;
} else {
companionBannerBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v20.common.AdImageAsset companion_banner = 7;</code>
*/
public Builder setCompanionBanner(
com.google.ads.googleads.v20.common.AdImageAsset.Builder builderForValue) {
if (companionBannerBuilder_ == null) {
companionBanner_ = builderForValue.build();
} else {
companionBannerBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v20.common.AdImageAsset companion_banner = 7;</code>
*/
public Builder mergeCompanionBanner(com.google.ads.googleads.v20.common.AdImageAsset value) {
if (companionBannerBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0) &&
companionBanner_ != null &&
companionBanner_ != com.google.ads.googleads.v20.common.AdImageAsset.getDefaultInstance()) {
getCompanionBannerBuilder().mergeFrom(value);
} else {
companionBanner_ = value;
}
} else {
companionBannerBuilder_.mergeFrom(value);
}
if (companionBanner_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v20.common.AdImageAsset companion_banner = 7;</code>
*/
public Builder clearCompanionBanner() {
bitField0_ = (bitField0_ & ~0x00000004);
companionBanner_ = null;
if (companionBannerBuilder_ != null) {
companionBannerBuilder_.dispose();
companionBannerBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v20.common.AdImageAsset companion_banner = 7;</code>
*/
public com.google.ads.googleads.v20.common.AdImageAsset.Builder getCompanionBannerBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getCompanionBannerFieldBuilder().getBuilder();
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v20.common.AdImageAsset companion_banner = 7;</code>
*/
public com.google.ads.googleads.v20.common.AdImageAssetOrBuilder getCompanionBannerOrBuilder() {
if (companionBannerBuilder_ != null) {
return companionBannerBuilder_.getMessageOrBuilder();
} else {
return companionBanner_ == null ?
com.google.ads.googleads.v20.common.AdImageAsset.getDefaultInstance() : companionBanner_;
}
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v20.common.AdImageAsset companion_banner = 7;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.common.AdImageAsset, com.google.ads.googleads.v20.common.AdImageAsset.Builder, com.google.ads.googleads.v20.common.AdImageAssetOrBuilder>
getCompanionBannerFieldBuilder() {
if (companionBannerBuilder_ == null) {
companionBannerBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.common.AdImageAsset, com.google.ads.googleads.v20.common.AdImageAsset.Builder, com.google.ads.googleads.v20.common.AdImageAssetOrBuilder>(
getCompanionBanner(),
getParentForChildren(),
isClean());
companionBanner_ = null;
}
return companionBannerBuilder_;
}
@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.common.VideoTrueViewInStreamAdInfo)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo)
private static final com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo();
}
public static com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<VideoTrueViewInStreamAdInfo>
PARSER = new com.google.protobuf.AbstractParser<VideoTrueViewInStreamAdInfo>() {
@java.lang.Override
public VideoTrueViewInStreamAdInfo 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<VideoTrueViewInStreamAdInfo> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<VideoTrueViewInStreamAdInfo> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v20.common.VideoTrueViewInStreamAdInfo getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 36,667 | google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/common/VideoTrueViewInStreamAdInfo.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v21/common/ad_type_infos.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v21.common;
/**
* <pre>
* Representation of video TrueView in-stream ad format (ad shown during video
* playback, often at beginning, which displays a skip button a few seconds into
* the video).
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo}
*/
public final class VideoTrueViewInStreamAdInfo extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo)
VideoTrueViewInStreamAdInfoOrBuilder {
private static final long serialVersionUID = 0L;
// Use VideoTrueViewInStreamAdInfo.newBuilder() to construct.
private VideoTrueViewInStreamAdInfo(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private VideoTrueViewInStreamAdInfo() {
actionButtonLabel_ = "";
actionHeadline_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new VideoTrueViewInStreamAdInfo();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.common.AdTypeInfosProto.internal_static_google_ads_googleads_v21_common_VideoTrueViewInStreamAdInfo_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.common.AdTypeInfosProto.internal_static_google_ads_googleads_v21_common_VideoTrueViewInStreamAdInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo.class, com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo.Builder.class);
}
private int bitField0_;
public static final int ACTION_BUTTON_LABEL_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object actionButtonLabel_ = "";
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @return The actionButtonLabel.
*/
@java.lang.Override
public java.lang.String getActionButtonLabel() {
java.lang.Object ref = actionButtonLabel_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
actionButtonLabel_ = s;
return s;
}
}
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @return The bytes for actionButtonLabel.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getActionButtonLabelBytes() {
java.lang.Object ref = actionButtonLabel_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
actionButtonLabel_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ACTION_HEADLINE_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object actionHeadline_ = "";
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @return The actionHeadline.
*/
@java.lang.Override
public java.lang.String getActionHeadline() {
java.lang.Object ref = actionHeadline_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
actionHeadline_ = s;
return s;
}
}
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @return The bytes for actionHeadline.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getActionHeadlineBytes() {
java.lang.Object ref = actionHeadline_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
actionHeadline_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int COMPANION_BANNER_FIELD_NUMBER = 7;
private com.google.ads.googleads.v21.common.AdImageAsset companionBanner_;
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v21.common.AdImageAsset companion_banner = 7;</code>
* @return Whether the companionBanner field is set.
*/
@java.lang.Override
public boolean hasCompanionBanner() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v21.common.AdImageAsset companion_banner = 7;</code>
* @return The companionBanner.
*/
@java.lang.Override
public com.google.ads.googleads.v21.common.AdImageAsset getCompanionBanner() {
return companionBanner_ == null ? com.google.ads.googleads.v21.common.AdImageAsset.getDefaultInstance() : companionBanner_;
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v21.common.AdImageAsset companion_banner = 7;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v21.common.AdImageAssetOrBuilder getCompanionBannerOrBuilder() {
return companionBanner_ == null ? com.google.ads.googleads.v21.common.AdImageAsset.getDefaultInstance() : companionBanner_;
}
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(actionButtonLabel_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, actionButtonLabel_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(actionHeadline_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, actionHeadline_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(7, getCompanionBanner());
}
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(actionButtonLabel_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, actionButtonLabel_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(actionHeadline_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, actionHeadline_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(7, getCompanionBanner());
}
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.common.VideoTrueViewInStreamAdInfo)) {
return super.equals(obj);
}
com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo other = (com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo) obj;
if (!getActionButtonLabel()
.equals(other.getActionButtonLabel())) return false;
if (!getActionHeadline()
.equals(other.getActionHeadline())) return false;
if (hasCompanionBanner() != other.hasCompanionBanner()) return false;
if (hasCompanionBanner()) {
if (!getCompanionBanner()
.equals(other.getCompanionBanner())) 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) + ACTION_BUTTON_LABEL_FIELD_NUMBER;
hash = (53 * hash) + getActionButtonLabel().hashCode();
hash = (37 * hash) + ACTION_HEADLINE_FIELD_NUMBER;
hash = (53 * hash) + getActionHeadline().hashCode();
if (hasCompanionBanner()) {
hash = (37 * hash) + COMPANION_BANNER_FIELD_NUMBER;
hash = (53 * hash) + getCompanionBanner().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo 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.common.VideoTrueViewInStreamAdInfo 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>
* Representation of video TrueView in-stream ad format (ad shown during video
* playback, often at beginning, which displays a skip button a few seconds into
* the video).
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo)
com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfoOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.common.AdTypeInfosProto.internal_static_google_ads_googleads_v21_common_VideoTrueViewInStreamAdInfo_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.common.AdTypeInfosProto.internal_static_google_ads_googleads_v21_common_VideoTrueViewInStreamAdInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo.class, com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo.Builder.class);
}
// Construct using com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getCompanionBannerFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
actionButtonLabel_ = "";
actionHeadline_ = "";
companionBanner_ = null;
if (companionBannerBuilder_ != null) {
companionBannerBuilder_.dispose();
companionBannerBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v21.common.AdTypeInfosProto.internal_static_google_ads_googleads_v21_common_VideoTrueViewInStreamAdInfo_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo getDefaultInstanceForType() {
return com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo build() {
com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo buildPartial() {
com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo result = new com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.actionButtonLabel_ = actionButtonLabel_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.actionHeadline_ = actionHeadline_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.companionBanner_ = companionBannerBuilder_ == null
? companionBanner_
: companionBannerBuilder_.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.common.VideoTrueViewInStreamAdInfo) {
return mergeFrom((com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo other) {
if (other == com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo.getDefaultInstance()) return this;
if (!other.getActionButtonLabel().isEmpty()) {
actionButtonLabel_ = other.actionButtonLabel_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getActionHeadline().isEmpty()) {
actionHeadline_ = other.actionHeadline_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasCompanionBanner()) {
mergeCompanionBanner(other.getCompanionBanner());
}
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 34: {
actionButtonLabel_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 34
case 42: {
actionHeadline_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 42
case 58: {
input.readMessage(
getCompanionBannerFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000004;
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 actionButtonLabel_ = "";
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @return The actionButtonLabel.
*/
public java.lang.String getActionButtonLabel() {
java.lang.Object ref = actionButtonLabel_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
actionButtonLabel_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @return The bytes for actionButtonLabel.
*/
public com.google.protobuf.ByteString
getActionButtonLabelBytes() {
java.lang.Object ref = actionButtonLabel_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
actionButtonLabel_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @param value The actionButtonLabel to set.
* @return This builder for chaining.
*/
public Builder setActionButtonLabel(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
actionButtonLabel_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @return This builder for chaining.
*/
public Builder clearActionButtonLabel() {
actionButtonLabel_ = getDefaultInstance().getActionButtonLabel();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* Label on the CTA (call-to-action) button taking the user to the video ad's
* final URL.
* Required for TrueView for action campaigns, optional otherwise.
* </pre>
*
* <code>string action_button_label = 4;</code>
* @param value The bytes for actionButtonLabel to set.
* @return This builder for chaining.
*/
public Builder setActionButtonLabelBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
actionButtonLabel_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object actionHeadline_ = "";
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @return The actionHeadline.
*/
public java.lang.String getActionHeadline() {
java.lang.Object ref = actionHeadline_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
actionHeadline_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @return The bytes for actionHeadline.
*/
public com.google.protobuf.ByteString
getActionHeadlineBytes() {
java.lang.Object ref = actionHeadline_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
actionHeadline_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @param value The actionHeadline to set.
* @return This builder for chaining.
*/
public Builder setActionHeadline(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
actionHeadline_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @return This builder for chaining.
*/
public Builder clearActionHeadline() {
actionHeadline_ = getDefaultInstance().getActionHeadline();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
* <pre>
* Additional text displayed with the CTA (call-to-action) button to give
* context and encourage clicking on the button.
* </pre>
*
* <code>string action_headline = 5;</code>
* @param value The bytes for actionHeadline to set.
* @return This builder for chaining.
*/
public Builder setActionHeadlineBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
actionHeadline_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.ads.googleads.v21.common.AdImageAsset companionBanner_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.common.AdImageAsset, com.google.ads.googleads.v21.common.AdImageAsset.Builder, com.google.ads.googleads.v21.common.AdImageAssetOrBuilder> companionBannerBuilder_;
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v21.common.AdImageAsset companion_banner = 7;</code>
* @return Whether the companionBanner field is set.
*/
public boolean hasCompanionBanner() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v21.common.AdImageAsset companion_banner = 7;</code>
* @return The companionBanner.
*/
public com.google.ads.googleads.v21.common.AdImageAsset getCompanionBanner() {
if (companionBannerBuilder_ == null) {
return companionBanner_ == null ? com.google.ads.googleads.v21.common.AdImageAsset.getDefaultInstance() : companionBanner_;
} else {
return companionBannerBuilder_.getMessage();
}
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v21.common.AdImageAsset companion_banner = 7;</code>
*/
public Builder setCompanionBanner(com.google.ads.googleads.v21.common.AdImageAsset value) {
if (companionBannerBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
companionBanner_ = value;
} else {
companionBannerBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v21.common.AdImageAsset companion_banner = 7;</code>
*/
public Builder setCompanionBanner(
com.google.ads.googleads.v21.common.AdImageAsset.Builder builderForValue) {
if (companionBannerBuilder_ == null) {
companionBanner_ = builderForValue.build();
} else {
companionBannerBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v21.common.AdImageAsset companion_banner = 7;</code>
*/
public Builder mergeCompanionBanner(com.google.ads.googleads.v21.common.AdImageAsset value) {
if (companionBannerBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0) &&
companionBanner_ != null &&
companionBanner_ != com.google.ads.googleads.v21.common.AdImageAsset.getDefaultInstance()) {
getCompanionBannerBuilder().mergeFrom(value);
} else {
companionBanner_ = value;
}
} else {
companionBannerBuilder_.mergeFrom(value);
}
if (companionBanner_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v21.common.AdImageAsset companion_banner = 7;</code>
*/
public Builder clearCompanionBanner() {
bitField0_ = (bitField0_ & ~0x00000004);
companionBanner_ = null;
if (companionBannerBuilder_ != null) {
companionBannerBuilder_.dispose();
companionBannerBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v21.common.AdImageAsset companion_banner = 7;</code>
*/
public com.google.ads.googleads.v21.common.AdImageAsset.Builder getCompanionBannerBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getCompanionBannerFieldBuilder().getBuilder();
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v21.common.AdImageAsset companion_banner = 7;</code>
*/
public com.google.ads.googleads.v21.common.AdImageAssetOrBuilder getCompanionBannerOrBuilder() {
if (companionBannerBuilder_ != null) {
return companionBannerBuilder_.getMessageOrBuilder();
} else {
return companionBanner_ == null ?
com.google.ads.googleads.v21.common.AdImageAsset.getDefaultInstance() : companionBanner_;
}
}
/**
* <pre>
* The image assets of the companion banner used with the ad.
* </pre>
*
* <code>.google.ads.googleads.v21.common.AdImageAsset companion_banner = 7;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.common.AdImageAsset, com.google.ads.googleads.v21.common.AdImageAsset.Builder, com.google.ads.googleads.v21.common.AdImageAssetOrBuilder>
getCompanionBannerFieldBuilder() {
if (companionBannerBuilder_ == null) {
companionBannerBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.common.AdImageAsset, com.google.ads.googleads.v21.common.AdImageAsset.Builder, com.google.ads.googleads.v21.common.AdImageAssetOrBuilder>(
getCompanionBanner(),
getParentForChildren(),
isClean());
companionBanner_ = null;
}
return companionBannerBuilder_;
}
@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.common.VideoTrueViewInStreamAdInfo)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo)
private static final com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo();
}
public static com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<VideoTrueViewInStreamAdInfo>
PARSER = new com.google.protobuf.AbstractParser<VideoTrueViewInStreamAdInfo>() {
@java.lang.Override
public VideoTrueViewInStreamAdInfo 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<VideoTrueViewInStreamAdInfo> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<VideoTrueViewInStreamAdInfo> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v21.common.VideoTrueViewInStreamAdInfo getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,493 | java-datacatalog/proto-google-cloud-datacatalog-v1/src/main/java/com/google/cloud/datacatalog/v1/ListEntryGroupsResponse.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/datacatalog.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.datacatalog.v1;
/**
*
*
* <pre>
* Response message for
* [ListEntryGroups][google.cloud.datacatalog.v1.DataCatalog.ListEntryGroups].
* </pre>
*
* Protobuf type {@code google.cloud.datacatalog.v1.ListEntryGroupsResponse}
*/
public final class ListEntryGroupsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.datacatalog.v1.ListEntryGroupsResponse)
ListEntryGroupsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListEntryGroupsResponse.newBuilder() to construct.
private ListEntryGroupsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListEntryGroupsResponse() {
entryGroups_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListEntryGroupsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datacatalog.v1.Datacatalog
.internal_static_google_cloud_datacatalog_v1_ListEntryGroupsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datacatalog.v1.Datacatalog
.internal_static_google_cloud_datacatalog_v1_ListEntryGroupsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datacatalog.v1.ListEntryGroupsResponse.class,
com.google.cloud.datacatalog.v1.ListEntryGroupsResponse.Builder.class);
}
public static final int ENTRY_GROUPS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.datacatalog.v1.EntryGroup> entryGroups_;
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.datacatalog.v1.EntryGroup> getEntryGroupsList() {
return entryGroups_;
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.datacatalog.v1.EntryGroupOrBuilder>
getEntryGroupsOrBuilderList() {
return entryGroups_;
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
@java.lang.Override
public int getEntryGroupsCount() {
return entryGroups_.size();
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
@java.lang.Override
public com.google.cloud.datacatalog.v1.EntryGroup getEntryGroups(int index) {
return entryGroups_.get(index);
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
@java.lang.Override
public com.google.cloud.datacatalog.v1.EntryGroupOrBuilder getEntryGroupsOrBuilder(int index) {
return entryGroups_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Pagination token to specify in the next call to retrieve the next page of
* results. Empty if there are no more items.
* </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 to specify in the next call to retrieve the next page of
* results. Empty if there are no more items.
* </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 < entryGroups_.size(); i++) {
output.writeMessage(1, entryGroups_.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 < entryGroups_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, entryGroups_.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.ListEntryGroupsResponse)) {
return super.equals(obj);
}
com.google.cloud.datacatalog.v1.ListEntryGroupsResponse other =
(com.google.cloud.datacatalog.v1.ListEntryGroupsResponse) obj;
if (!getEntryGroupsList().equals(other.getEntryGroupsList())) 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 (getEntryGroupsCount() > 0) {
hash = (37 * hash) + ENTRY_GROUPS_FIELD_NUMBER;
hash = (53 * hash) + getEntryGroupsList().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.ListEntryGroupsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1.ListEntryGroupsResponse 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.ListEntryGroupsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1.ListEntryGroupsResponse 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.ListEntryGroupsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1.ListEntryGroupsResponse 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.ListEntryGroupsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.v1.ListEntryGroupsResponse 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.ListEntryGroupsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.v1.ListEntryGroupsResponse 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.ListEntryGroupsResponse 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.ListEntryGroupsResponse 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.ListEntryGroupsResponse 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
* [ListEntryGroups][google.cloud.datacatalog.v1.DataCatalog.ListEntryGroups].
* </pre>
*
* Protobuf type {@code google.cloud.datacatalog.v1.ListEntryGroupsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.datacatalog.v1.ListEntryGroupsResponse)
com.google.cloud.datacatalog.v1.ListEntryGroupsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datacatalog.v1.Datacatalog
.internal_static_google_cloud_datacatalog_v1_ListEntryGroupsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datacatalog.v1.Datacatalog
.internal_static_google_cloud_datacatalog_v1_ListEntryGroupsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datacatalog.v1.ListEntryGroupsResponse.class,
com.google.cloud.datacatalog.v1.ListEntryGroupsResponse.Builder.class);
}
// Construct using com.google.cloud.datacatalog.v1.ListEntryGroupsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (entryGroupsBuilder_ == null) {
entryGroups_ = java.util.Collections.emptyList();
} else {
entryGroups_ = null;
entryGroupsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.datacatalog.v1.Datacatalog
.internal_static_google_cloud_datacatalog_v1_ListEntryGroupsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1.ListEntryGroupsResponse getDefaultInstanceForType() {
return com.google.cloud.datacatalog.v1.ListEntryGroupsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.datacatalog.v1.ListEntryGroupsResponse build() {
com.google.cloud.datacatalog.v1.ListEntryGroupsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1.ListEntryGroupsResponse buildPartial() {
com.google.cloud.datacatalog.v1.ListEntryGroupsResponse result =
new com.google.cloud.datacatalog.v1.ListEntryGroupsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.datacatalog.v1.ListEntryGroupsResponse result) {
if (entryGroupsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
entryGroups_ = java.util.Collections.unmodifiableList(entryGroups_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.entryGroups_ = entryGroups_;
} else {
result.entryGroups_ = entryGroupsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.datacatalog.v1.ListEntryGroupsResponse 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.ListEntryGroupsResponse) {
return mergeFrom((com.google.cloud.datacatalog.v1.ListEntryGroupsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.datacatalog.v1.ListEntryGroupsResponse other) {
if (other == com.google.cloud.datacatalog.v1.ListEntryGroupsResponse.getDefaultInstance())
return this;
if (entryGroupsBuilder_ == null) {
if (!other.entryGroups_.isEmpty()) {
if (entryGroups_.isEmpty()) {
entryGroups_ = other.entryGroups_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureEntryGroupsIsMutable();
entryGroups_.addAll(other.entryGroups_);
}
onChanged();
}
} else {
if (!other.entryGroups_.isEmpty()) {
if (entryGroupsBuilder_.isEmpty()) {
entryGroupsBuilder_.dispose();
entryGroupsBuilder_ = null;
entryGroups_ = other.entryGroups_;
bitField0_ = (bitField0_ & ~0x00000001);
entryGroupsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getEntryGroupsFieldBuilder()
: null;
} else {
entryGroupsBuilder_.addAllMessages(other.entryGroups_);
}
}
}
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.EntryGroup m =
input.readMessage(
com.google.cloud.datacatalog.v1.EntryGroup.parser(), extensionRegistry);
if (entryGroupsBuilder_ == null) {
ensureEntryGroupsIsMutable();
entryGroups_.add(m);
} else {
entryGroupsBuilder_.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.EntryGroup> entryGroups_ =
java.util.Collections.emptyList();
private void ensureEntryGroupsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
entryGroups_ =
new java.util.ArrayList<com.google.cloud.datacatalog.v1.EntryGroup>(entryGroups_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datacatalog.v1.EntryGroup,
com.google.cloud.datacatalog.v1.EntryGroup.Builder,
com.google.cloud.datacatalog.v1.EntryGroupOrBuilder>
entryGroupsBuilder_;
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public java.util.List<com.google.cloud.datacatalog.v1.EntryGroup> getEntryGroupsList() {
if (entryGroupsBuilder_ == null) {
return java.util.Collections.unmodifiableList(entryGroups_);
} else {
return entryGroupsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public int getEntryGroupsCount() {
if (entryGroupsBuilder_ == null) {
return entryGroups_.size();
} else {
return entryGroupsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public com.google.cloud.datacatalog.v1.EntryGroup getEntryGroups(int index) {
if (entryGroupsBuilder_ == null) {
return entryGroups_.get(index);
} else {
return entryGroupsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public Builder setEntryGroups(int index, com.google.cloud.datacatalog.v1.EntryGroup value) {
if (entryGroupsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureEntryGroupsIsMutable();
entryGroups_.set(index, value);
onChanged();
} else {
entryGroupsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public Builder setEntryGroups(
int index, com.google.cloud.datacatalog.v1.EntryGroup.Builder builderForValue) {
if (entryGroupsBuilder_ == null) {
ensureEntryGroupsIsMutable();
entryGroups_.set(index, builderForValue.build());
onChanged();
} else {
entryGroupsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public Builder addEntryGroups(com.google.cloud.datacatalog.v1.EntryGroup value) {
if (entryGroupsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureEntryGroupsIsMutable();
entryGroups_.add(value);
onChanged();
} else {
entryGroupsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public Builder addEntryGroups(int index, com.google.cloud.datacatalog.v1.EntryGroup value) {
if (entryGroupsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureEntryGroupsIsMutable();
entryGroups_.add(index, value);
onChanged();
} else {
entryGroupsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public Builder addEntryGroups(
com.google.cloud.datacatalog.v1.EntryGroup.Builder builderForValue) {
if (entryGroupsBuilder_ == null) {
ensureEntryGroupsIsMutable();
entryGroups_.add(builderForValue.build());
onChanged();
} else {
entryGroupsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public Builder addEntryGroups(
int index, com.google.cloud.datacatalog.v1.EntryGroup.Builder builderForValue) {
if (entryGroupsBuilder_ == null) {
ensureEntryGroupsIsMutable();
entryGroups_.add(index, builderForValue.build());
onChanged();
} else {
entryGroupsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public Builder addAllEntryGroups(
java.lang.Iterable<? extends com.google.cloud.datacatalog.v1.EntryGroup> values) {
if (entryGroupsBuilder_ == null) {
ensureEntryGroupsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, entryGroups_);
onChanged();
} else {
entryGroupsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public Builder clearEntryGroups() {
if (entryGroupsBuilder_ == null) {
entryGroups_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
entryGroupsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public Builder removeEntryGroups(int index) {
if (entryGroupsBuilder_ == null) {
ensureEntryGroupsIsMutable();
entryGroups_.remove(index);
onChanged();
} else {
entryGroupsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public com.google.cloud.datacatalog.v1.EntryGroup.Builder getEntryGroupsBuilder(int index) {
return getEntryGroupsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public com.google.cloud.datacatalog.v1.EntryGroupOrBuilder getEntryGroupsOrBuilder(int index) {
if (entryGroupsBuilder_ == null) {
return entryGroups_.get(index);
} else {
return entryGroupsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public java.util.List<? extends com.google.cloud.datacatalog.v1.EntryGroupOrBuilder>
getEntryGroupsOrBuilderList() {
if (entryGroupsBuilder_ != null) {
return entryGroupsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(entryGroups_);
}
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public com.google.cloud.datacatalog.v1.EntryGroup.Builder addEntryGroupsBuilder() {
return getEntryGroupsFieldBuilder()
.addBuilder(com.google.cloud.datacatalog.v1.EntryGroup.getDefaultInstance());
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public com.google.cloud.datacatalog.v1.EntryGroup.Builder addEntryGroupsBuilder(int index) {
return getEntryGroupsFieldBuilder()
.addBuilder(index, com.google.cloud.datacatalog.v1.EntryGroup.getDefaultInstance());
}
/**
*
*
* <pre>
* Entry group details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1.EntryGroup entry_groups = 1;</code>
*/
public java.util.List<com.google.cloud.datacatalog.v1.EntryGroup.Builder>
getEntryGroupsBuilderList() {
return getEntryGroupsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datacatalog.v1.EntryGroup,
com.google.cloud.datacatalog.v1.EntryGroup.Builder,
com.google.cloud.datacatalog.v1.EntryGroupOrBuilder>
getEntryGroupsFieldBuilder() {
if (entryGroupsBuilder_ == null) {
entryGroupsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datacatalog.v1.EntryGroup,
com.google.cloud.datacatalog.v1.EntryGroup.Builder,
com.google.cloud.datacatalog.v1.EntryGroupOrBuilder>(
entryGroups_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
entryGroups_ = null;
}
return entryGroupsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Pagination token to specify in the next call to retrieve the next page of
* results. Empty if there are no more items.
* </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 to specify in the next call to retrieve the next page of
* results. Empty if there are no more items.
* </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 to specify in the next call to retrieve the next page of
* results. Empty if there are no more items.
* </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 to specify in the next call to retrieve the next page of
* results. Empty if there are no more items.
* </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 to specify in the next call to retrieve the next page of
* results. Empty if there are no more items.
* </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.ListEntryGroupsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.datacatalog.v1.ListEntryGroupsResponse)
private static final com.google.cloud.datacatalog.v1.ListEntryGroupsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.datacatalog.v1.ListEntryGroupsResponse();
}
public static com.google.cloud.datacatalog.v1.ListEntryGroupsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListEntryGroupsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListEntryGroupsResponse>() {
@java.lang.Override
public ListEntryGroupsResponse 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<ListEntryGroupsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListEntryGroupsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1.ListEntryGroupsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/mina | 36,393 | codec/src/test/java/org/apache/mina/codec/IoBufferTest.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.mina.codec;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.InputStream;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.InvalidMarkException;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
/**
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class IoBufferTest {
/**
* Test the addition of 3 heap buffers with data
*/
@Test
public void testAddHeapBuffers() {
ByteBuffer bb1 = ByteBuffer.allocate(5);
bb1.put("012".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(5);
bb2.put("345".getBytes());
bb2.flip();
ByteBuffer bb3 = ByteBuffer.allocate(5);
bb3.put("6789".getBytes());
bb3.flip();
IoBuffer ioBuffer = IoBuffer.newInstance();
ioBuffer.add(bb1, bb2).add(bb3);
assertEquals(0, ioBuffer.position());
assertEquals(10, ioBuffer.limit());
assertEquals(10, ioBuffer.capacity());
assertTrue(ioBuffer.hasRemaining());
for (int i = 0; i < 10; i++) {
assertTrue(ioBuffer.hasRemaining());
assertEquals("0123456789".charAt(i), ioBuffer.get());
}
try {
assertFalse(ioBuffer.hasRemaining());
ioBuffer.get();
fail();
} catch (BufferUnderflowException bufe) {
assertTrue(true);
}
}
/**
* Test the addition of 3 heap buffers, one being empty
*/
@Test
public void testAddHeapBuffersOneEmpty() {
ByteBuffer bb1 = ByteBuffer.allocate(5);
bb1.put("012".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(0);
ByteBuffer bb3 = ByteBuffer.allocate(5);
bb3.put("3456".getBytes());
bb3.flip();
IoBuffer ioBuffer = IoBuffer.newInstance();
ioBuffer.add(bb1, bb2).add(bb3);
assertEquals(0, ioBuffer.position());
assertEquals(7, ioBuffer.limit());
assertEquals(7, ioBuffer.capacity());
for (int i = 0; i < 7; i++) {
assertTrue(ioBuffer.hasRemaining());
assertEquals("0123456".charAt(i), ioBuffer.get());
}
try {
ioBuffer.get();
fail();
} catch (BufferUnderflowException bufe) {
assertTrue(true);
}
}
/**
* Test the addition of mixed type buffers
*/
@Test
public void testAddMixedTypeBuffers() {
ByteBuffer bb1 = ByteBuffer.allocate(5);
bb1.put("012".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocateDirect(5);
bb2.put("3456".getBytes());
bb2.flip();
IoBuffer ioBuffer = IoBuffer.newInstance();
ioBuffer.add(bb1, bb2);
}
/**
* Test the addition of mixed order buffers
*/
@Test
public void testAddMixedOrderBuffers() {
ByteBuffer bb1 = ByteBuffer.allocate(5);
bb1.order(ByteOrder.LITTLE_ENDIAN);
bb1.put("012".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocateDirect(5);
bb1.order(ByteOrder.BIG_ENDIAN);
bb2.put("3456".getBytes());
bb2.flip();
IoBuffer ioBuffer = IoBuffer.newInstance();
ioBuffer.add(bb1, bb2);
}
// -------------------------------------------------------------------------
// Test the allocate(int) method
// 1) allocation with a negative value
// 2) allocation with a 0 length
// 3) allocation with a 1024 value
// -------------------------------------------------------------------------
/**
* Test the allocation of a new heap IoBuffer with a negative value
*/
@Test(expected = IllegalArgumentException.class)
public void testAllocateNegative() {
IoBuffer.allocate(-1);
}
/**
* Test the allocation of a new heap IoBuffer with no byte in it
*/
@Test
public void testAllocate0() {
IoBuffer ioBuffer = IoBuffer.allocate(0);
assertFalse(ioBuffer.isDirect());
assertEquals(0, ioBuffer.capacity());
assertEquals(0, ioBuffer.limit());
assertEquals(0, ioBuffer.position());
assertFalse(ioBuffer.hasRemaining());
}
/**
* Test the allocation of a new heap IoBuffer with 1024 bytes
*/
@Test
public void testAllocate1024() {
IoBuffer ioBuffer = IoBuffer.allocate(1024);
assertFalse(ioBuffer.isDirect());
assertEquals(1024, ioBuffer.capacity());
assertEquals(1024, ioBuffer.limit());
assertEquals(0, ioBuffer.position());
assertTrue(ioBuffer.hasRemaining());
}
// -------------------------------------------------------------------------
// Test the allocateDirect(int) method. We check :
// 1) allocation with a negative value
// 2) allocation with a 0 length
// 3) allocation with a 1024 value
// -------------------------------------------------------------------------
/**
* Test the allocation of a new heap IoBuffer with a negative value
*/
@Test(expected = IllegalArgumentException.class)
public void testAllocateDirectNegative() {
IoBuffer.allocate(-1);
}
/**
* Test the allocation of a new direct IoBuffer with no byte in it
*/
@Test
public void testAllocateDirect0() {
IoBuffer ioBuffer = IoBuffer.allocateDirect(0);
assertTrue(ioBuffer.isDirect());
assertEquals(0, ioBuffer.capacity());
assertEquals(0, ioBuffer.limit());
assertEquals(0, ioBuffer.position());
assertFalse(ioBuffer.hasRemaining());
}
/**
* Test the allocation of a new direct IoBuffer with 1024 bytes
*/
@Test
public void testAllocateDirect1024() {
IoBuffer ioBuffer = IoBuffer.allocateDirect(1024);
assertTrue(ioBuffer.isDirect());
assertEquals(1024, ioBuffer.capacity());
assertEquals(1024, ioBuffer.limit());
assertEquals(0, ioBuffer.position());
assertTrue(ioBuffer.hasRemaining());
}
/**
* Test the get() method on a IoBuffer containing one ByteBuffer with 3
* bytes
*/
@Test
public void testGetOneBuffer3Bytes() {
ByteBuffer bb = ByteBuffer.allocate(5);
bb.put("012".getBytes());
bb.flip();
IoBuffer ioBuffer = IoBuffer.wrap(bb);
assertEquals(0, ioBuffer.position());
assertEquals(3, ioBuffer.limit());
assertTrue(ioBuffer.hasRemaining());
assertEquals('0', ioBuffer.get());
assertTrue(ioBuffer.hasRemaining());
assertEquals('1', ioBuffer.get());
assertTrue(ioBuffer.hasRemaining());
assertEquals('2', ioBuffer.get());
try {
assertFalse(ioBuffer.hasRemaining());
ioBuffer.get();
fail();
} catch (BufferUnderflowException bufe) {
// expected
assertEquals(3, ioBuffer.position());
}
}
/**
* Test the get() method on a IoBuffer containing one ByteBuffer with 0
* bytes
*/
@Test
public void testGetOneBuffer0Bytes() {
ByteBuffer bb = ByteBuffer.allocate(0);
IoBuffer ioBuffer = IoBuffer.wrap(bb);
assertEquals(0, ioBuffer.position());
assertEquals(0, ioBuffer.limit());
try {
assertFalse(ioBuffer.hasRemaining());
ioBuffer.get();
fail();
} catch (BufferUnderflowException bufe) {
// expected
assertEquals(0, ioBuffer.position());
}
}
/**
* Test the get() method on a IoBuffer containing two ByteBuffer with 3
* bytes
*/
@Test
public void testGetTwoBuffer3Bytes() {
ByteBuffer bb1 = ByteBuffer.allocate(5);
bb1.put("012".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(5);
bb2.put("345".getBytes());
bb2.flip();
IoBuffer ioBuffer = IoBuffer.wrap(bb1, bb2);
assertEquals(0, ioBuffer.position());
assertEquals(6, ioBuffer.limit());
assertTrue(ioBuffer.hasRemaining());
assertEquals('0', ioBuffer.get());
assertTrue(ioBuffer.hasRemaining());
assertEquals('1', ioBuffer.get());
assertTrue(ioBuffer.hasRemaining());
assertEquals('2', ioBuffer.get());
assertTrue(ioBuffer.hasRemaining());
assertEquals('3', ioBuffer.get());
assertTrue(ioBuffer.hasRemaining());
assertEquals('4', ioBuffer.get());
assertTrue(ioBuffer.hasRemaining());
assertEquals('5', ioBuffer.get());
try {
assertFalse(ioBuffer.hasRemaining());
ioBuffer.get();
fail();
} catch (BufferUnderflowException bufe) {
// expected
assertEquals(6, ioBuffer.position());
}
}
// -------------------------------------------------------------------------
// Test the array() method. We will check those cases :
// 1) array over an empty buffer: we should get an empty byte array
// 2) array over a buffer with one single empty ByteBuffer
// 3) array over a buffer with one single ByteBuffer with data
// 4) array over a buffer containing many ByteBuffers
// -------------------------------------------------------------------------
/**
* Test the array method for a IoBuffer containing one empty ByteBuffer
*/
@Test
public void testArrayEmptyByteBuffer() {
IoBuffer ioBuffer = IoBuffer.newInstance();
byte[] array = ioBuffer.array();
assertNotNull(array);
assertEquals(0, array.length);
assertTrue(Arrays.equals(new byte[] {}, array));
}
/**
* Test the array method for a IoBuffer containing one ByteBuffer (cases 2
* and 3)
*/
@Test
public void testArrayOneByteBuffer() {
ByteBuffer bb1 = ByteBuffer.allocate(5);
IoBuffer ioBuffer = IoBuffer.wrap(bb1);
// Empty buffer first
byte[] array = ioBuffer.array();
assertNotNull(array);
assertEquals(5, array.length);
assertTrue(Arrays.equals(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00 }, array));
// Buffer with data
bb1.put("012".getBytes());
bb1.flip();
ioBuffer = IoBuffer.wrap(bb1);
assertNotNull(array);
assertEquals(5, array.length);
assertTrue(Arrays.equals(new byte[] { '0', '1', '2', 0, 0 }, array));
}
/**
* Test the array method for a IoBuffer containing one ByteBuffer not
* initialized
*/
@Test
public void testArrayByteBufferNotInitialized() {
ByteBuffer bb = ByteBuffer.allocate(3);
IoBuffer ioBuffer = IoBuffer.wrap(bb);
byte[] array = ioBuffer.array();
assertNotNull(array);
assertEquals(3, array.length);
assertTrue(Arrays.equals(new byte[] { 0x00, 0x00, 0x00 }, array));
}
/**
* Test the getInt() method, on a buffer containing 2 ints in one ByteBuffer
*/
@Test
public void testGetInt2IntsOneBB() {
ByteBuffer bb = ByteBuffer.allocate(8);
bb.putInt(12345);
bb.putInt(67890);
bb.flip();
IoBuffer ioBuffer = IoBuffer.wrap(bb);
assertEquals(12345, ioBuffer.getInt());
assertEquals(67890, ioBuffer.getInt());
}
/**
* Test the getInt() method, on a buffer containing 2 ints in two
* ByteBuffers
*/
@Test
public void testGetInt2Ints2BBs() {
ByteBuffer bb1 = ByteBuffer.allocate(4);
bb1.putInt(12345);
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(4);
bb2.putInt(67890);
bb2.flip();
IoBuffer ioBuffer = IoBuffer.wrap(bb1, bb2);
assertEquals(12345, ioBuffer.getInt());
assertEquals(67890, ioBuffer.getInt());
}
/**
* Test the getInt() method, on a buffer containing 2 ints in two
* ByteBuffers with LittleInidan order
*/
@Test
public void testGetInt2Ints2BBsLittleIndian() {
ByteBuffer bb1 = ByteBuffer.allocate(4);
bb1.order(ByteOrder.LITTLE_ENDIAN);
bb1.putInt(12345);
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(4);
bb2.order(ByteOrder.LITTLE_ENDIAN);
bb2.putInt(67890);
bb2.flip();
IoBuffer ioBuffer = IoBuffer.wrap(bb1, bb2);
ioBuffer.order(ByteOrder.LITTLE_ENDIAN);
assertEquals(12345, ioBuffer.getInt());
assertEquals(67890, ioBuffer.getInt());
}
/**
* Test the getInt() method, on a buffer containing 1 int spread in two
* ByteBuffers
*/
@Test
public void testGetInt1Int2BBs() {
ByteBuffer bb1 = ByteBuffer.allocate(1);
bb1.put((byte) 0x01);
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(3);
bb2.put(new byte[] { 0x02, 0x03, 0x04 });
bb2.flip();
IoBuffer ioBuffer = IoBuffer.wrap(bb1, bb2);
assertEquals(0x01020304, ioBuffer.getInt());
}
/**
* Test the getInt() method, on a buffer containing 1 incomplet int spread
* in two ByteBuffers
*/
@Test(expected = BufferUnderflowException.class)
public void testGetIntIncompletInt2BBs() {
ByteBuffer bb1 = ByteBuffer.allocate(1);
bb1.put((byte) 0x01);
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(2);
bb2.put(new byte[] { 0x02, 0x03 });
bb2.flip();
IoBuffer ioBuffer = IoBuffer.wrap(bb1, bb2);
ioBuffer.getInt();
}
/**
* test the get(int) method on one buffer
*/
@Test
public void testGetIntOneBuffer() {
ByteBuffer bb = ByteBuffer.allocate(4);
bb.put("0123".getBytes());
bb.flip();
IoBuffer ioBuffer = IoBuffer.wrap(bb);
assertEquals('0', ioBuffer.get());
assertEquals('1', ioBuffer.get());
assertEquals('0', ioBuffer.get(0));
assertEquals('3', ioBuffer.get(3));
assertEquals('1', ioBuffer.get(1));
assertEquals('2', ioBuffer.get(2));
assertEquals('2', ioBuffer.get());
try {
ioBuffer.get(4);
fail();
} catch (IndexOutOfBoundsException ioobe) {
// expected
assertTrue(true);
}
}
/**
* test the get(int) method on two buffers
*/
@Test
public void testGetIntTwoBuffer() {
ByteBuffer bb1 = ByteBuffer.allocate(4);
bb1.put("0123".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(4);
bb2.put("4567".getBytes());
bb2.flip();
IoBuffer ioBuffer = IoBuffer.wrap(bb1, bb2);
assertEquals('0', ioBuffer.get());
assertEquals('1', ioBuffer.get());
assertEquals('0', ioBuffer.get(0));
assertEquals('4', ioBuffer.get(4));
assertEquals('7', ioBuffer.get(7));
assertEquals('2', ioBuffer.get(2));
assertEquals('2', ioBuffer.get());
assertEquals('3', ioBuffer.get());
assertEquals('4', ioBuffer.get());
try {
ioBuffer.get(8);
fail();
} catch (IndexOutOfBoundsException ioobe) {
// expected
assertTrue(true);
}
}
// -------------------------------------------------------------------------
// The the clear method. It will erase all the data in all the inner
// ByteBuffer, thus the buffer size might increase.
// We will check those case :
// 1) clear an empty buffer
// 2) clear a buffer with one ByteBuffer
// 3) clear a buffer with numerous ByteBuffers
// -------------------------------------------------------------------------
/**
* Test the clear() method
*/
@Test
public void testClearEmptyBuffer() {
ByteBuffer bb1 = ByteBuffer.allocate(4);
bb1.put("012".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(4);
bb2.put("345".getBytes());
bb2.flip();
IoBuffer ioBuffer = IoBuffer.wrap(bb1, bb2);
assertEquals(6, ioBuffer.limit());
// Move forward a bit
ioBuffer.get();
ioBuffer.get();
ioBuffer.limit(3);
// Clear
ioBuffer.clear();
// We should be back to the origin
assertEquals(0, ioBuffer.position());
// The limit must back to the available size
assertEquals(6, ioBuffer.limit());
}
/**
* Test the mark() method
*/
@Test
public void testMark() {
ByteBuffer bb1 = ByteBuffer.allocate(4);
bb1.put("0123".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(4);
bb2.put("4567".getBytes());
bb2.flip();
IoBuffer ioBuffer = IoBuffer.wrap(bb1, bb2);
ioBuffer.position(3);
ioBuffer.mark();
// check that we are at the right position
byte b = ioBuffer.get();
assertEquals(b, '3');
b = ioBuffer.get();
assertEquals(b, '4');
// Now reset to the mark
ioBuffer.reset();
b = ioBuffer.get();
assertEquals(b, '3');
ioBuffer.position(6);
ioBuffer.reset();
ioBuffer.position(6);
ioBuffer.mark();
// we go backward, the mark should be discarded
ioBuffer.position(3);
try {
ioBuffer.reset();
fail("An InvalidMarkException should have been thrown");
} catch (InvalidMarkException ime) {
//
}
}
/**
* Test the flip() method
*/
@Test
public void testFlip() {
ByteBuffer bb1 = ByteBuffer.allocate(4);
bb1.put("0123".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(4);
bb2.put("4567".getBytes());
bb2.flip();
IoBuffer ioBuffer = IoBuffer.wrap(bb1, bb2);
// Move forward a bit
ioBuffer.get();
ioBuffer.get();
// Clear
ioBuffer.clear();
// We should be back to the origin
assertEquals(0, ioBuffer.position());
assertEquals(8, ioBuffer.limit());
}
// -------------------------------------------------------------------------
// Test the position() method
// We will test that the position() metho returns the correct result in
// those cases :
// 1) the buffer is empty : must return 0
// 2) must return a value between 0 and limit()
// -------------------------------------------------------------------------
/**
* Test the position method over an emptyIoBuffer
*/
@Test
public void testPositionEmptyBuffer() {
IoBuffer ioBuffer = IoBuffer.newInstance();
assertEquals(0, ioBuffer.position());
}
/**
* Test the position method over a buffer
*/
@Test
public void testPositionBuffer() {
ByteBuffer bb1 = ByteBuffer.allocate(4);
bb1.put("012".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(4);
bb2.put("3456".getBytes());
bb2.flip();
ByteBuffer bb3 = ByteBuffer.allocate(4);
bb3.put("789".getBytes());
bb3.flip();
// The resulting buffer will be seen as "0123456789"
IoBuffer ioBuffer = IoBuffer.wrap(bb1, bb2, bb3);
// Iterate and check the position
for (int i = 0; i < ioBuffer.limit(); i++) {
assertEquals(i, ioBuffer.position());
ioBuffer.get();
}
}
/**
* Test set position method over a buffer
*/
@Test
public void testSetPositionBuffer() {
ByteBuffer bb1 = ByteBuffer.allocate(4);
bb1.put("012".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(4);
bb2.put("3456".getBytes());
bb2.flip();
ByteBuffer bb3 = ByteBuffer.allocate(4);
bb3.put("789".getBytes());
bb3.flip();
// The resulting buffer will be seen as "0123456789"
IoBuffer ioBuffer = IoBuffer.wrap(bb1, bb2, bb3);
// Check with random positions
for (int i : new int[] { 4, 6, 7, 8, 3, 9, 1, 5, 0, 2 }) {
ioBuffer.position(i);
assertEquals('0' + i, ioBuffer.get());
}
}
// -------------------------------------------------------------------------
// Test the position(int) method
// We will test many different cases
// 1) a position() in an empty buffer
// 2) a position() with a negative value
// 3) a position() with a value above the limit
// 4) a position() within the current buffer
// 4-1) at the beginning of the current buffer
// 4-2) at the end of the current buffer
// 4-3) in the middle of the current buffer
// 5) a position() before the current buffer
// 6) a position() after the current buffer
// -------------------------------------------------------------------------
/**
* Test the position method over an emptyIoBuffer
*/
@Test
public void testPositionIntEmptyBuffer() {
IoBuffer ioBuffer = IoBuffer.newInstance();
ioBuffer.position(0);
}
/**
* Test the position method with a negative value
*/
@Test(expected = IllegalArgumentException.class)
public void testPositionNegativeValue() {
ByteBuffer bb1 = ByteBuffer.allocate(4);
bb1.put("0123".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(4);
bb2.put("4567".getBytes());
bb2.flip();
ByteBuffer bb3 = ByteBuffer.allocate(4);
bb3.put("89".getBytes());
bb3.flip();
IoBuffer ioBuffer = IoBuffer.wrap(bb1, bb2, bb3);
ioBuffer.position(-1);
}
/**
* Test the position method with a value above the buffer size
*/
@Test(expected = IllegalArgumentException.class)
public void testPositionAboveValue() {
ByteBuffer bb1 = ByteBuffer.allocate(4);
bb1.put("012".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(4);
bb2.put("3456".getBytes());
bb2.flip();
ByteBuffer bb3 = ByteBuffer.allocate(4);
bb3.put("789".getBytes());
bb3.flip();
// The resulting buffer will be seen as "0123456789"
IoBuffer ioBuffer = IoBuffer.wrap(bb1, bb2, bb3);
ioBuffer.position(11);
}
/**
* Test the position method in the current buffer
*/
@Test
public void testPositionCurrentBuffer() {
ByteBuffer bb1 = ByteBuffer.allocate(4);
bb1.put("012".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(4);
bb2.put("3456".getBytes());
bb2.flip();
ByteBuffer bb3 = ByteBuffer.allocate(4);
bb3.put("789".getBytes());
bb3.flip();
// The resulting buffer will be seen as "0123456789"
IoBuffer ioBuffer = IoBuffer.wrap(bb1, bb2, bb3);
// Set the position in the middle of bb2 (4-3)
ioBuffer.position(5);
assertEquals('5', ioBuffer.get());
// Set the position at the beginning of bb2 (4-1)
ioBuffer.position(3);
assertEquals('3', ioBuffer.get());
// Set the position at the end of bb2 (4-2)
ioBuffer.position(6);
assertEquals('6', ioBuffer.get());
// Set a position before the current buffer (5)
ioBuffer.position(2);
assertEquals('2', ioBuffer.get());
// Set a position after the current buffer (6)
ioBuffer.position(7);
assertEquals('7', ioBuffer.get());
// Now, let's see if we can get all the elements correctly
// if we set the position from 0 to end
for (int i = 0; i < ioBuffer.limit(); i++) {
ioBuffer.position(i);
assertEquals('0' + i, ioBuffer.get());
}
// Same, in revert order
for (int i = ioBuffer.limit() - 1; i >= 0; i--) {
ioBuffer.position(i);
assertEquals('0' + i, ioBuffer.get());
}
}
@Test
public void testSlice() {
ByteBuffer bb1 = ByteBuffer.allocate(5);
bb1.put("012".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(5);
bb2.put("345".getBytes());
bb2.flip();
ByteBuffer bb3 = ByteBuffer.allocate(5);
bb3.put("6789".getBytes());
bb3.flip();
IoBuffer ioBuffer = IoBuffer.newInstance();
ioBuffer.add(bb1, bb2).add(bb3);
ioBuffer.position(2);
ioBuffer.limit(8);
IoBuffer slice = ioBuffer.slice();
assertEquals(6, slice.remaining());
assertEquals(0, slice.position());
assertEquals(6, slice.limit());
byte seg[] = "234567".getBytes();
for (int i = 0; i < 6; i++) {
assertEquals(seg[i], slice.get(i));
}
}
@Test
public void testShort() {
for (ByteOrder bo : new ByteOrder[] { ByteOrder.BIG_ENDIAN, ByteOrder.LITTLE_ENDIAN }) {
ByteBuffer bb = (ByteBuffer) ByteBuffer.allocate(3).order(bo).putShort((short) 12345).rewind();
IoBuffer ioBuffer = IoBuffer.wrap(bb).order(bo);
assertEquals(3, ioBuffer.capacity());
ioBuffer.extend(1);
ioBuffer.position(2);
assertEquals(4, ioBuffer.capacity());
ioBuffer.putShort((short) -23456);
ioBuffer.rewind();
assertEquals(12345, ioBuffer.getShort());
assertEquals(-23456, ioBuffer.getShort());
ioBuffer.rewind();
ioBuffer.putShort(1, (short) 12345);
assertEquals((short) 12345, ioBuffer.getShort(1));
try {
ioBuffer.putShort(3, (short) 1);
fail("Not enough place on the buffer");
} catch (BufferUnderflowException e) {
// Should come here
}
try {
ioBuffer.getShort(3);
fail("Not enough place on the buffer");
} catch (BufferUnderflowException e) {
// Should come here
}
}
}
@Test
public void testInt() {
for (ByteOrder bo : new ByteOrder[] { ByteOrder.BIG_ENDIAN, ByteOrder.LITTLE_ENDIAN }) {
ByteBuffer bb = (ByteBuffer) ByteBuffer.allocate(5).order(bo).putInt(123456).rewind();
IoBuffer ioBuffer = IoBuffer.wrap(bb).order(bo);
assertEquals(5, ioBuffer.capacity());
ioBuffer.extend(3);
ioBuffer.position(4);
assertEquals(8, ioBuffer.capacity());
ioBuffer.putInt(-23456789);
ioBuffer.rewind();
assertEquals(123456, ioBuffer.getInt());
assertEquals(-23456789, ioBuffer.getInt());
ioBuffer.rewind();
ioBuffer.putInt(2, 1234567890);
assertEquals(1234567890, ioBuffer.getInt(2));
try {
ioBuffer.putInt(5, 1);
fail("Not enough place on the buffer");
} catch (BufferUnderflowException e) {
// Should come here
}
try {
ioBuffer.getInt(5);
fail("Not enough place on the buffer");
} catch (BufferUnderflowException e) {
// Should come here
}
}
}
@Test
public void testLong() {
for (ByteOrder bo : new ByteOrder[] { ByteOrder.BIG_ENDIAN, ByteOrder.LITTLE_ENDIAN }) {
ByteBuffer bb = (ByteBuffer) ByteBuffer.allocate(9).order(bo).putLong(123456789012l).rewind();
IoBuffer ioBuffer = IoBuffer.wrap(bb).order(bo);
assertEquals(9, ioBuffer.capacity());
ioBuffer.extend(7);
ioBuffer.position(8);
assertEquals(16, ioBuffer.capacity());
ioBuffer.putLong(-23456789023l);
ioBuffer.rewind();
assertEquals(123456789012l, ioBuffer.getLong());
assertEquals(-23456789023l, ioBuffer.getLong());
ioBuffer.rewind();
ioBuffer.putLong(4, 1234567890);
assertEquals(1234567890, ioBuffer.getLong(4));
try {
ioBuffer.putLong(9, 1);
fail("Not enough place on the buffer");
} catch (BufferUnderflowException e) {
// Should come here
}
try {
ioBuffer.getLong(9);
fail("Not enough place on the buffer");
} catch (BufferUnderflowException e) {
// Should come here
}
}
}
@Test
public void testFloat() {
for (ByteOrder bo : new ByteOrder[] { ByteOrder.BIG_ENDIAN, ByteOrder.LITTLE_ENDIAN }) {
ByteBuffer bb = (ByteBuffer) ByteBuffer.allocate(5).order(bo).putFloat(-0.68f).rewind();
IoBuffer ioBuffer = IoBuffer.wrap(bb).order(bo);
assertEquals(5, ioBuffer.capacity());
ioBuffer.extend(3);
ioBuffer.position(4);
assertEquals(8, ioBuffer.capacity());
ioBuffer.putFloat(3.14f);
ioBuffer.rewind();
assertEquals(-0.68f, ioBuffer.getFloat(), 0.001f);
assertEquals(3.14f, ioBuffer.getFloat(), 0.001f);
ioBuffer.rewind();
ioBuffer.putFloat(2, -12.34f);
assertEquals(-12.34f, ioBuffer.getFloat(2), 0.001f);
}
}
@Test
public void testDouble() {
for (ByteOrder bo : new ByteOrder[] { ByteOrder.BIG_ENDIAN, ByteOrder.LITTLE_ENDIAN }) {
ByteBuffer bb = (ByteBuffer) ByteBuffer.allocate(9).order(bo).putDouble(Math.PI).rewind();
IoBuffer ioBuffer = IoBuffer.wrap(bb).order(bo);
assertEquals(9, ioBuffer.capacity());
ioBuffer.extend(7);
ioBuffer.position(8);
assertEquals(16, ioBuffer.capacity());
ioBuffer.putDouble(-Math.E);
ioBuffer.rewind();
assertEquals(Math.PI, ioBuffer.getDouble(), 1E-10);
assertEquals(-Math.E, ioBuffer.getDouble(), 1E-10);
ioBuffer.rewind();
ioBuffer.putDouble(4, 12.34);
assertEquals(12.34, ioBuffer.getDouble(4), 1E-10);
}
}
@Test
public void testChar() {
for (ByteOrder bo : new ByteOrder[] { ByteOrder.BIG_ENDIAN, ByteOrder.LITTLE_ENDIAN }) {
ByteBuffer bb = (ByteBuffer) ByteBuffer.allocate(3).order(bo).putChar('\u00EB').rewind();
IoBuffer ioBuffer = IoBuffer.wrap(bb).order(bo);
assertEquals(3, ioBuffer.capacity());
ioBuffer.extend(1);
ioBuffer.order(bo);
ioBuffer.position(2);
assertEquals(4, ioBuffer.capacity());
ioBuffer.putChar('\u00FC');
ioBuffer.rewind();
assertEquals('\u00EB', ioBuffer.getChar());
assertEquals('\u00FC', ioBuffer.getChar());
ioBuffer.rewind();
ioBuffer.putChar(1, '\u00E7');
assertEquals('\u00E7', ioBuffer.getChar(1));
try {
ioBuffer.putChar(3, '\u00F1');
fail("Not enough place on the buffer");
} catch (BufferUnderflowException e) {
// Should come here
}
try {
ioBuffer.getChar(3);
fail("Not enough place on the buffer");
} catch (BufferUnderflowException e) {
// Should come here
}
}
}
@Test
public void testGet() {
ByteBuffer bb1 = ByteBuffer.allocate(5);
bb1.put("012".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(5);
bb2.put("345".getBytes());
bb2.flip();
ByteBuffer bb3 = ByteBuffer.allocate(5);
bb3.put("6789".getBytes());
bb3.flip();
IoBuffer ioBuffer = IoBuffer.newInstance();
ioBuffer.add(bb1, bb2).add(bb3);
ioBuffer.position(2);
ioBuffer.limit(8);
byte block[] = new byte[6];
ioBuffer.get(block);
byte seg[] = "234567".getBytes();
for (int i = 0; i < 6; i++) {
assertEquals(seg[i], block[i]);
}
}
@Test
public void testPut() {
ByteBuffer bb1 = ByteBuffer.allocate(5);
bb1.put("012".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(5);
bb2.put("345".getBytes());
bb2.flip();
ByteBuffer bb3 = ByteBuffer.allocate(5);
bb3.put("6789".getBytes());
bb3.flip();
IoBuffer ioBuffer = IoBuffer.newInstance();
ioBuffer.add(bb1, bb2).add(bb3);
byte seq[] = "abcdefghij".getBytes();
ioBuffer.position(2);
ioBuffer.put(seq, 3, 3);
ioBuffer.rewind();
byte expected[] = "01def56789".getBytes();
for (int i = 0; i < 6; i++) {
assertEquals(expected[i], ioBuffer.get(i));
}
}
@Test
public void testCompact() {
ByteBuffer bb1 = ByteBuffer.allocate(5);
bb1.put("012".getBytes());
bb1.flip();
ByteBuffer bb2 = ByteBuffer.allocate(5);
bb2.put("345".getBytes());
bb2.flip();
ByteBuffer bb3 = ByteBuffer.allocate(5);
bb3.put("6789".getBytes());
bb3.flip();
IoBuffer ioBuffer = IoBuffer.newInstance();
ioBuffer.add(bb1, bb2).add(bb3);
ioBuffer.position(2);
ioBuffer.limit(8);
ioBuffer.compact();
assertEquals(ioBuffer.capacity(), ioBuffer.limit());
assertEquals(6, ioBuffer.position());
byte seg[] = "234567".getBytes();
for (int i = 0; i < 6; i++) {
assertEquals(seg[i], ioBuffer.get(i));
}
}
@Test
public void testInputStreamGetByte() throws IOException {
String hw = "HelloWorld";
IoBuffer bb = IoBuffer.wrap(hw.getBytes());
InputStream is = bb.asInputStream();
for (int i = 0; i < 10; i++) {
assertEquals(i, bb.position());
assertEquals(hw.getBytes()[i], is.read());
}
assertEquals(-1, is.read());
}
@Test
public void testInputStreamGetByteArray() throws IOException {
String hw = "HelloWorld";
IoBuffer bb = IoBuffer.wrap(hw.getBytes());
InputStream is = bb.asInputStream();
byte array[] = new byte[15];
assertEquals(5, is.read(array, 0, 5));
assertEquals(5, bb.position());
assertEquals(5, is.read(array, 5, 10));
assertEquals(10, bb.position());
for (int i = 0; i < 10; i++) {
assertEquals(hw.getBytes()[i], array[i]);
}
}
@Test
public void testEquals() {
String h = "Hello";
String w = "World";
IoBuffer hw1b = IoBuffer.wrap((h + w).getBytes());
IoBuffer wh1b = IoBuffer.wrap((w + h).getBytes());
IoBuffer hw2b = IoBuffer.newInstance();
hw2b.add(ByteBuffer.wrap(h.getBytes()));
hw2b.add(ByteBuffer.wrap(w.getBytes()));
assertEquals(hw2b, hw1b);
Assert.assertThat(wh1b, is(not(hw1b)));
}
}
|
apache/systemds | 35,181 | src/main/java/org/apache/sysds/runtime/instructions/cp/DnnCPInstruction.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sysds.runtime.instructions.cp;
import java.util.ArrayList;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.sysds.api.DMLScript;
import org.apache.sysds.common.Opcodes;
import org.apache.sysds.hops.OptimizerUtils;
import org.apache.sysds.runtime.DMLRuntimeException;
import org.apache.sysds.runtime.controlprogram.context.ExecutionContext;
import org.apache.sysds.runtime.instructions.InstructionUtils;
import org.apache.sysds.runtime.lineage.LineageItem;
import org.apache.sysds.runtime.lineage.LineageItemUtils;
import org.apache.sysds.runtime.matrix.data.DnnParameters;
import org.apache.sysds.runtime.matrix.data.LibMatrixDNN;
import org.apache.sysds.runtime.matrix.data.LibMatrixDNN.PoolingType;
import org.apache.sysds.runtime.matrix.data.LibMatrixNative;
import org.apache.sysds.runtime.matrix.data.MatrixBlock;
import org.apache.sysds.runtime.util.DnnUtils;
import org.apache.sysds.utils.NativeHelper;
public class DnnCPInstruction extends UnaryCPInstruction {
private static final Log LOG = LogFactory.getLog(DnnCPInstruction.class.getName());
private static boolean warnedUnderUtilitization = false;
private final CPOperand _in2;
private final CPOperand _in3;
private final CPOperand _in4;
private final CPOperand _in5;
private final CPOperand _in6;
private final CPOperand _in7;
private final CPOperand _in8;
private final CPOperand _in9;
private final CPOperand _in10;
private final CPOperand _in11;
private final CPOperand _out2;
private final CPOperand _out3;
private final CPOperand _out4;
private final CPOperand _out5;
private final ArrayList<CPOperand> _input_shape;
private final ArrayList<CPOperand> _filter_shape;
private final ArrayList<CPOperand> _stride;
private final ArrayList<CPOperand> _padding;
private final int _numThreads;
private final double _intermediateMemoryBudget;
public DnnCPInstruction(CPOperand in, CPOperand in2, CPOperand in3, CPOperand out,
ArrayList<CPOperand> stride, ArrayList<CPOperand> padding, ArrayList<CPOperand> input_shape,
ArrayList<CPOperand> filter_shape, int numThreads, double intermediateMemoryBudget, String opcode, String istr) {
super(CPType.Dnn, null, in, out, opcode, istr);
_in2 = in2;
_in3 = in3;
_in4 = null; _in5 = null; _in6 = null; _in7 = null; _in8 = null;
_in9 = null; _in10 = null; _in11 = null;
_out2 = null; _out3 = null; _out4 = null; _out5 = null;
_stride = stride;
_padding = padding;
_input_shape = input_shape;
_filter_shape = filter_shape;
_numThreads = numThreads;
_intermediateMemoryBudget = intermediateMemoryBudget;
}
public DnnCPInstruction(CPOperand in, CPOperand in2, CPOperand out, String opcode, String istr, int numThreads, double intermediateMemoryBudget) {
this(in, in2, null, out, null, null, null, null, numThreads, intermediateMemoryBudget, opcode, istr);
if( !(opcode.equals(Opcodes.BIAS_ADD.toString()) || opcode.equals(Opcodes.RELU_BACKWARD.toString()) || opcode.equals(Opcodes.BIAS_MULTIPLY.toString()) ) ) {
throw new DMLRuntimeException("Incorrect usage. Expected the opcode to be bias_add or bias_multiply or relu_backward, but found " + opcode);
}
}
private DnnCPInstruction(CPOperand in, CPOperand out, String opcode, String istr,
ArrayList<CPOperand> stride, ArrayList<CPOperand> padding, ArrayList<CPOperand> input_shape,
ArrayList<CPOperand> filter_shape, int numThreads, double intermediateMemoryBudget) {
this(in, null, null, out, stride, padding, input_shape, filter_shape, numThreads, intermediateMemoryBudget, opcode, istr);
}
public DnnCPInstruction(CPOperand in, CPOperand in2, CPOperand out, String opcode,
String istr, ArrayList<CPOperand> stride,
ArrayList<CPOperand> padding, ArrayList<CPOperand> input_shape,
ArrayList<CPOperand> filter_shape, int numThreads, double intermediateMemoryBudget) {
this(in, in2, null, out, stride, padding, input_shape, filter_shape, numThreads, intermediateMemoryBudget, opcode, istr);
}
public DnnCPInstruction(CPOperand in, CPOperand in2, CPOperand in3, CPOperand out, String opcode,
String istr, ArrayList<CPOperand> stride,
ArrayList<CPOperand> padding, ArrayList<CPOperand> input_shape,
ArrayList<CPOperand> filter_shape, int numThreads, double intermediateMemoryBudget) {
this(in, in2, in3, out, stride, padding, input_shape, filter_shape, numThreads, intermediateMemoryBudget, opcode, istr);
}
public DnnCPInstruction(CPOperand in1, CPOperand in2, CPOperand in3, CPOperand in4, CPOperand in5, CPOperand in6, CPOperand in7, CPOperand in8, CPOperand out1, CPOperand out2, CPOperand out3, CPOperand out4, CPOperand out5, String opcode, String str, int i) {
this(in1, in2, in3, in4, in5, in6, in7, in8,null, null, null, out1, out2, out3, out4, out5, opcode, str, 0);
}
public DnnCPInstruction(CPOperand in1, CPOperand in2, CPOperand in3, CPOperand in4, CPOperand in5,
CPOperand in6, CPOperand in7, CPOperand in8, CPOperand in9, CPOperand in10, CPOperand in11,
CPOperand out, CPOperand out2, CPOperand out3, CPOperand out4, CPOperand out5, String opcode, String istr,
double intermediateMemoryBudget) throws DMLRuntimeException {
super(CPType.Dnn, null, in1, out, opcode, istr);
_in2 = in2;
_in3 = in3;
_in4 = in4;
_in5 = in5;
_in6 = in6;
_in7 = in7;
_in8 = in8;
_in9 = in9;
_in10 = in10;
_in11 = in11;
_out2 = out2;
_out3 = out3;
_out4 = out4;
_out5 = out5;
_stride = null;
_padding = null;
_input_shape = null;
_filter_shape = null;
_numThreads = 0;
_intermediateMemoryBudget = intermediateMemoryBudget;
}
public static DnnCPInstruction parseInstruction(String str) {
String[] parts = InstructionUtils.getInstructionPartsWithValueType(str);
String opcode = parts[0];
if (opcode.equalsIgnoreCase(Opcodes.MAXPOOLING.toString()) || opcode.equalsIgnoreCase(Opcodes.RELU_MAXPOOLING.toString()) ||
opcode.equalsIgnoreCase(Opcodes.AVGPOOLING.toString())) {
InstructionUtils.checkNumFields(parts, 16);
// stride1, stride2, padding1, padding2
// input_shape1, input_shape2, input_shape3, input_shape4,
// filter_shape1, filter_shape2, filter_shape3, filter_shape4, k
CPOperand in = new CPOperand(parts[1]);
CPOperand out = new CPOperand(parts[14]);
ArrayList<CPOperand> stride = new ArrayList<>();
ArrayList<CPOperand> padding = new ArrayList<>();
ArrayList<CPOperand> input_shape = new ArrayList<>();
ArrayList<CPOperand> filter_shape = new ArrayList<>();
stride.add(new CPOperand(parts[2]));
stride.add(new CPOperand(parts[3]));
padding.add(new CPOperand(parts[4]));
padding.add(new CPOperand(parts[5]));
input_shape.add(new CPOperand(parts[6]));
input_shape.add(new CPOperand(parts[7]));
input_shape.add(new CPOperand(parts[8]));
input_shape.add(new CPOperand(parts[9]));
filter_shape.add(new CPOperand(parts[10]));
filter_shape.add(new CPOperand(parts[11]));
filter_shape.add(new CPOperand(parts[12]));
filter_shape.add(new CPOperand(parts[13]));
int k = Integer.parseInt(parts[15]);
return new DnnCPInstruction(in, out, opcode, str, stride,
padding, input_shape, filter_shape, k, Double.parseDouble(parts[16]));
}
else if (opcode.equalsIgnoreCase(Opcodes.MAXPOOLING_BACKWARD.toString()) || opcode.equalsIgnoreCase(Opcodes.RELU_MAXPOOLING_BACKWARD.toString())
|| opcode.equalsIgnoreCase(Opcodes.AVGPOOLING_BACKWARD.toString())
|| opcode.equalsIgnoreCase(Opcodes.CONV2D.toString())
|| opcode.equalsIgnoreCase(Opcodes.CONV2D_BACKWARD_FILTER.toString())
|| opcode.equalsIgnoreCase(Opcodes.CONV2D_BACKWARD_DATA.toString())) {
InstructionUtils.checkNumFields(parts, 17);
// dout, stride1, stride2, padding1, padding2
// input_shape1, input_shape2, input_shape3, input_shape4,
// filter_shape1, filter_shape2, filter_shape3, filter_shape4, k
CPOperand in = new CPOperand(parts[1]);
CPOperand in2 = new CPOperand(parts[2]);
CPOperand out = new CPOperand(parts[15]);
ArrayList<CPOperand> stride = new ArrayList<>();
ArrayList<CPOperand> padding = new ArrayList<>();
ArrayList<CPOperand> input_shape = new ArrayList<>();
ArrayList<CPOperand> filter_shape = new ArrayList<>();
stride.add(new CPOperand(parts[3]));
stride.add(new CPOperand(parts[4]));
padding.add(new CPOperand(parts[5]));
padding.add(new CPOperand(parts[6]));
input_shape.add(new CPOperand(parts[7]));
input_shape.add(new CPOperand(parts[8]));
input_shape.add(new CPOperand(parts[9]));
input_shape.add(new CPOperand(parts[10]));
filter_shape.add(new CPOperand(parts[11]));
filter_shape.add(new CPOperand(parts[12]));
filter_shape.add(new CPOperand(parts[13]));
filter_shape.add(new CPOperand(parts[14]));
int k = Integer.parseInt(parts[16]);
return new DnnCPInstruction(in, in2, out, opcode, str, stride,
padding, input_shape, filter_shape, k, Double.parseDouble(parts[17]));
}
else if (opcode.equalsIgnoreCase(Opcodes.CONV2D_BIAS_ADD.toString())) {
InstructionUtils.checkNumFields(parts, 18);
// dout, stride1, stride2, padding1, padding2
// input_shape1, input_shape2, input_shape3, input_shape4,
// filter_shape1, filter_shape2, filter_shape3, filter_shape4, k
CPOperand in = new CPOperand(parts[1]);
CPOperand in2 = new CPOperand(parts[2]);
CPOperand in3 = new CPOperand(parts[3]);
CPOperand out = new CPOperand(parts[16]);
ArrayList<CPOperand> stride = new ArrayList<>();
ArrayList<CPOperand> padding = new ArrayList<>();
ArrayList<CPOperand> input_shape = new ArrayList<>();
ArrayList<CPOperand> filter_shape = new ArrayList<>();
stride.add(new CPOperand(parts[4]));
stride.add(new CPOperand(parts[5]));
padding.add(new CPOperand(parts[6]));
padding.add(new CPOperand(parts[7]));
input_shape.add(new CPOperand(parts[8]));
input_shape.add(new CPOperand(parts[9]));
input_shape.add(new CPOperand(parts[10]));
input_shape.add(new CPOperand(parts[11]));
filter_shape.add(new CPOperand(parts[12]));
filter_shape.add(new CPOperand(parts[13]));
filter_shape.add(new CPOperand(parts[14]));
filter_shape.add(new CPOperand(parts[15]));
int k = Integer.parseInt(parts[17]);
return new DnnCPInstruction(in, in2, in3, out, opcode, str, stride,
padding, input_shape, filter_shape, k, Double.parseDouble(parts[18]));
}
else if (opcode.equalsIgnoreCase(Opcodes.BIAS_ADD.toString()) || opcode.equals(Opcodes.RELU_BACKWARD.toString()) || opcode.equalsIgnoreCase(Opcodes.BIAS_MULTIPLY.toString()) ) {
InstructionUtils.checkNumFields(parts, 5);
CPOperand in = new CPOperand(parts[1]);
CPOperand in2 = new CPOperand(parts[2]);
CPOperand out = new CPOperand(parts[3]);
int k = Integer.parseInt(parts[4]);
return new DnnCPInstruction(in, in2, out, opcode, str, k, Double.parseDouble(parts[5]));
}
else if (opcode.equalsIgnoreCase(Opcodes.BATCH_NORM2D.toString())) {
InstructionUtils.checkNumFields(parts, 14);
CPOperand in1 = new CPOperand(parts[1]); // image
CPOperand in2 = new CPOperand(parts[2]); // scale
CPOperand in3 = new CPOperand(parts[3]); // bias
CPOperand in4 = new CPOperand(parts[4]); // runningMean
CPOperand in5 = new CPOperand(parts[5]); // runningVar
CPOperand in6 = new CPOperand(parts[6]); // mode
CPOperand in7 = new CPOperand(parts[7]); // epsilon
CPOperand in8 = new CPOperand(parts[8]); // exponentialAverageFactor
CPOperand out = new CPOperand(parts[9]); // ret
CPOperand out2 = new CPOperand(parts[10]); // retRunningMean
CPOperand out3 = new CPOperand(parts[11]); // retRunningVar
CPOperand out4 = new CPOperand(parts[12]); // resultSaveMean
CPOperand out5 = new CPOperand(parts[13]); // resultSaveInvVariance
// int threads = Integer.parseInt(parts[14]);
return new DnnCPInstruction(in1, in2, in3, in4, in5, in6, in7, in8, out, out2, out3, out4, out5, opcode, str, 0);
}
else if (opcode.equalsIgnoreCase(Opcodes.BATCH_NORM2D_BACKWARD.toString())) {
InstructionUtils.checkNumFields(parts, 10);
CPOperand in1 = new CPOperand(parts[1]); // image
CPOperand in2 = new CPOperand(parts[2]); // dout
CPOperand in3 = new CPOperand(parts[3]); // scale
CPOperand in4 = new CPOperand(parts[4]); // epsilon
CPOperand in5 = new CPOperand(parts[5]); // resultSaveMean
CPOperand in6 = new CPOperand(parts[6]); // resultSaveInvVariance
CPOperand out = new CPOperand(parts[7]); // dX
CPOperand out2 = new CPOperand(parts[8]); // dScale
CPOperand out3 = new CPOperand(parts[9]); // dBias
// int threads = Integer.parseInt(parts[10]);
return new DnnCPInstruction(in1, in2, in3, in4, in5, in6, null, null, out, out2, out3, null, null, opcode, str, 0);
}
else if (opcode.equalsIgnoreCase(Opcodes.LSTM.toString())) {
InstructionUtils.checkNumFields(parts, 12);
CPOperand in1 = new CPOperand(parts[1]);
CPOperand in2 = new CPOperand(parts[2]);
CPOperand in3 = new CPOperand(parts[3]);
CPOperand in4 = new CPOperand(parts[4]);
CPOperand in5 = new CPOperand(parts[5]);
CPOperand in6 = new CPOperand(parts[6]);
CPOperand out1 = new CPOperand(parts[7]);
CPOperand out2 = new CPOperand(parts[8]);
CPOperand out3 = new CPOperand(parts[9]);
CPOperand out4 = new CPOperand(parts[10]);
CPOperand out5 = new CPOperand(parts[11]);
// int threads = Integer.parseInt(parts[12]);
return new DnnCPInstruction(in1, in2, in3, in4, in5, in6, null, null, out1, out2, out3, out4, out5, opcode, str, 0);
} if(opcode.equalsIgnoreCase(Opcodes.LSTM_BACKWARD.toString())){
InstructionUtils.checkNumFields(parts, 17);
CPOperand in1 = new CPOperand(parts[1]);
CPOperand in2 = new CPOperand(parts[2]);
CPOperand in3 = new CPOperand(parts[3]);
CPOperand in4 = new CPOperand(parts[4]);
CPOperand in5 = new CPOperand(parts[5]);
CPOperand in6 = new CPOperand(parts[6]);
CPOperand in7 = new CPOperand(parts[7]);
CPOperand in8 = new CPOperand(parts[8]);
CPOperand in9 = new CPOperand(parts[9]);
CPOperand in10 = new CPOperand(parts[10]);
CPOperand in11 = new CPOperand(parts[11]);
CPOperand out1 = new CPOperand(parts[12]);
CPOperand out2 = new CPOperand(parts[13]);
CPOperand out3 = new CPOperand(parts[14]);
CPOperand out4 = new CPOperand(parts[15]);
CPOperand out5 = new CPOperand(parts[16]);
// int threads = Integer.parseInt(parts[17]);
return new DnnCPInstruction(in1, in2, in3, in4, in5, in6, in7, in8, in9, in10, in11, out1, out2, out3, out4, out5, opcode, str, 0);
}
else {
throw new DMLRuntimeException("Unknown opcode while parsing a DnnCPInstruction: " + str);
}
}
private static int getScalarInput(ExecutionContext ec, ArrayList<CPOperand> aL, int index) {
return (int) ec.getScalarInput(aL.get(index)).getLongValue();
}
public void processReluBackwardInstruction(ExecutionContext ec) {
// (X > 0) * dout
MatrixBlock input = ec.getMatrixInput(input1.getName());
MatrixBlock dout = ec.getMatrixInput(_in2.getName());
MatrixBlock outputBlock = new MatrixBlock(input.getNumRows(), input.getNumColumns(),
input.isInSparseFormat() || dout.isInSparseFormat() );
if( !input.isEmpty() && !dout.isEmpty() ) { //sparse-safe
outputBlock.allocateBlock();
LibMatrixDNN.reluBackward(input, dout, outputBlock, _numThreads);
}
// release inputs/outputs
ec.releaseMatrixInput(input1.getName());
ec.releaseMatrixInput(_in2.getName());
ec.setMatrixOutput(getOutputVariableName(), outputBlock);
}
public void processBiasAddInstruction(ExecutionContext ec) {
MatrixBlock input = ec.getMatrixInput(input1.getName());
MatrixBlock bias = ec.getMatrixInput(_in2.getName());
MatrixBlock outputBlock = null;
if(bias.getNumColumns() != 1) {
throw new DMLRuntimeException("Expected the number of columns of bias matrix to be 1, but found " + bias.getNumColumns());
}
if(input.isEmpty() && bias.isEmpty()) {
outputBlock = new MatrixBlock(input.getNumRows(), input.getNumColumns(), true);
}
else if(bias.isEmpty()) {
outputBlock = new MatrixBlock(input);
}
else {
// As we always fill the output first with bias
outputBlock = new MatrixBlock(input.getNumRows(), input.getNumColumns(), false);
outputBlock.allocateDenseBlock();
LibMatrixDNN.biasAdd(input, bias, outputBlock, _numThreads);
}
// release inputs/outputs
ec.releaseMatrixInput(input1.getName());
ec.releaseMatrixInput(_in2.getName());
ec.setMatrixOutput(getOutputVariableName(), outputBlock);
}
public void processBiasMultiplyInstruction(ExecutionContext ec) {
MatrixBlock input = ec.getMatrixInput(input1.getName());
MatrixBlock bias = ec.getMatrixInput(_in2.getName());
MatrixBlock outputBlock = null;
if(bias.getNumColumns() != 1) {
throw new DMLRuntimeException("Expected the number of columns of bias matrix to be 1, but found " + bias.getNumColumns());
}
if(bias.isEmpty()) {
// Anything multiplied by zero is zero
outputBlock = new MatrixBlock(input.getNumRows(), input.getNumColumns(), true);
}
else {
// As we always fill the output first with bias
outputBlock = new MatrixBlock(input.getNumRows(), input.getNumColumns(),
input.isInSparseFormat()).allocateBlock();
LibMatrixDNN.biasMultiply(input, bias, outputBlock, _numThreads);
}
// release inputs/outputs
ec.releaseMatrixInput(input1.getName());
ec.releaseMatrixInput(_in2.getName());
ec.setMatrixOutput(getOutputVariableName(), outputBlock);
}
public void processBatchNorm2dInstruction(ExecutionContext ec) {
MatrixBlock image = ec.getMatrixInput(input1.getName());
MatrixBlock scale = ec.getMatrixInput(_in2.getName());
MatrixBlock bias = ec.getMatrixInput(_in3.getName());
MatrixBlock runningMean = ec.getMatrixInput(_in4.getName());
MatrixBlock runningVar = ec.getMatrixInput(_in5.getName());
String phase = ec.getScalarInput(_in6).getStringValue();
double epsilon = ec.getScalarInput(_in7).getDoubleValue();
double mu = ec.getScalarInput(_in8).getDoubleValue();
MatrixBlock ret = new MatrixBlock(image.getNumRows(), image.getNumColumns(), false).allocateBlock();
MatrixBlock retRunningMean = new MatrixBlock(runningMean.getNumRows(), runningMean.getNumColumns(), false).allocateBlock();
MatrixBlock retRunningVar = new MatrixBlock(runningVar.getNumRows(), runningVar.getNumColumns(), false).allocateBlock();
MatrixBlock resultSaveMean = new MatrixBlock(runningMean.getNumRows(), runningMean.getNumColumns(), false).allocateBlock();
MatrixBlock resultSaveInvVariance = new MatrixBlock(runningVar.getNumRows(), runningVar.getNumColumns(), false).allocateBlock();
LibMatrixDNN.batchNorm2D(image, scale, bias, runningMean, runningVar, phase, epsilon, mu, ret,
retRunningMean, retRunningVar, resultSaveMean, resultSaveInvVariance);
// release inputs/outputs
ec.releaseMatrixInput(input1.getName(), _in2.getName(),
_in3.getName(), _in4.getName(), _in5.getName());
ec.setMatrixOutput(output.getName(), ret);
ec.setMatrixOutput(_out2.getName(), retRunningMean);
ec.setMatrixOutput(_out3.getName(), retRunningVar);
ec.setMatrixOutput(_out4.getName(), resultSaveMean);
ec.setMatrixOutput(_out5.getName(), resultSaveInvVariance);
}
public void processBatchNorm2dBackwardInstruction(ExecutionContext ec) {
MatrixBlock image = ec.getMatrixInput(input1.getName());
MatrixBlock dout = ec.getMatrixInput(_in2.getName());
MatrixBlock scale = ec.getMatrixInput(_in3.getName());
double epsilon = ec.getScalarInput(_in4).getDoubleValue();
MatrixBlock resultSaveMean = ec.getMatrixInput(_in5.getName());
MatrixBlock resultSaveInvVariance = ec.getMatrixInput(_in6.getName());
MatrixBlock dX = new MatrixBlock(image.getNumRows(), image.getNumColumns(), false).allocateBlock();
MatrixBlock dScale = new MatrixBlock(scale.getNumRows(), scale.getNumColumns(), false).allocateBlock();
MatrixBlock dBias = new MatrixBlock(scale.getNumRows(), scale.getNumColumns(), false).allocateBlock();
LibMatrixDNN.batchNorm2DBackward(image, dout, scale, epsilon, resultSaveMean, resultSaveInvVariance, dX, dScale, dBias);
// release inputs/outputs
ec.releaseMatrixInput(input1.getName(), _in2.getName(),
_in3.getName(), _in5.getName(), _in6.getName());
ec.setMatrixOutput(output.getName(), dX);
ec.setMatrixOutput(_out2.getName(), dScale);
ec.setMatrixOutput(_out3.getName(), dBias);
}
// Assumption: enableNative && NativeHelper.isNativeLibraryLoaded() is true
// This increases the number of native calls. For example:the cases where filter is sparse but input is dense
private static boolean isFilterSparse(MatrixBlock filter) {
long numElems = filter.getNumRows()*filter.getNumColumns();
// if filter is less than 10 MB in dense format (which handles almost all the cases).
// In fact, using threshold of 1 MB is still sufficient for common CNNs.
if(filter.isInSparseFormat() && numElems < 10e+6)
filter.sparseToDense();
return filter.isInSparseFormat();
}
private void processLSTMInstruction(ExecutionContext ec, boolean backward) {
// batchSize=N, seqLength=T, numFeatures=D and hiddenSize=M
// input X:(N, T*D), ==> (T, D, N)
// weight W:(D+M+2, 4M)
// previous output input3 (also represented by hx)
// and cell state input4 (also represented by cx): (N, M) ==> (1, M, N)
MatrixBlock X = ec.getMatrixInput(input1.getName());
MatrixBlock W = ec.getMatrixInput(_in2.getName());
MatrixBlock bias = ec.getMatrixInput(_in3.getName());
MatrixBlock out0 = ec.getMatrixInput(_in4.getName());
MatrixBlock c0 = ec.getMatrixInput(_in5.getName());
boolean return_sequences = ec.getScalarInput(_in6).getBooleanValue();
MatrixBlock dout = null, dc = null, cache_out = null, cache_c = null, cache_ifog = null;
if(backward){
dout = ec.getMatrixInput(_in7.getName());
dc = ec.getMatrixInput(_in8.getName());
cache_out = ec.getMatrixInput(_in9.getName());
cache_c = ec.getMatrixInput(_in10.getName());
cache_ifog = ec.getMatrixInput(_in11.getName());
}
//Check input dimensions
int M = out0.getNumColumns(); // hiddenSize .. since input3: (N, M)
int N = out0.getNumRows();
int numRowsW = W.getNumRows();
int numColsW = W.getNumColumns();
int D = numRowsW - M; // since W:(D+M, 4M) ... numFeatures
int T = X.getNumColumns() / D;
if(c0.getNumColumns() != out0.getNumColumns() || out0.getNumRows() != c0.getNumRows()){
throw new DMLRuntimeException("Incorrect input dimension for LSTM. Expected input4 and input3 Matrix to be of "+
"the same Dimension (N, M), but got ("+c0.getNumRows()+", " +c0.getNumColumns()+") and ("+
out0.getNumRows()+", "+out0.getNumColumns()+")");
}
if(W.getNumColumns() != 4*M){
throw new DMLRuntimeException("Incorrect input dimension for LSTM. Expected Weight Matrix to be of "+
"Dimension (D+M, 4M) = ("+numRowsW+", "+4*M+"), but got ("+numRowsW+", "+numColsW+")");
}
if(bias.getNumColumns() != 4*M || bias.getNumRows() != 1){
throw new DMLRuntimeException("Incorrect input dimension for LSTM. Expected bias Matrix to be of "+
"Dimension (1, 4M) = (1, "+4*M+"), but got ("+bias.getNumRows()+", "+bias.getNumColumns()+")");
}
//prepare output matrices
// out = backward / forward
// -------------------------
// out1 = dX / out
// out2 = dW / c
// out3 = db / cache_out
// out4 = dout0 / cache_c
// out5 = dc0 / cache_ifog
MatrixBlock out1 = new MatrixBlock(N, backward ? T*D : return_sequences ? T*M : M,false);
MatrixBlock out2 = new MatrixBlock(backward ? D + M : N, backward ? 4*M : M,false);
MatrixBlock out3 = new MatrixBlock(backward ? 1 : T, backward ? 4*M : N*M,false);
MatrixBlock out4 = new MatrixBlock(backward ? N : T, backward ? M : N*M,false);
MatrixBlock out5 = new MatrixBlock(backward ? N : T, backward ? M : N*4*M,false);
//
DnnParameters params = new DnnParameters(N,D,T,M,X, W, bias, out0, c0, cache_out, cache_c, cache_ifog, return_sequences, dout, dc,out1, out2, out3, out4, out5, _numThreads);
if(backward)
LibMatrixDNN.lstmBackward(params);
else
LibMatrixDNN.lstm(params);
// release inputs/outputs
ec.releaseMatrixInput(input1.getName(), _in2.getName(), _in3.getName(), _in4.getName(), _in5.getName());
if(backward)
ec.releaseMatrixInput(_in7.getName(), _in8.getName(), _in9.getName(), _in10.getName(), _in11.getName());
ec.setMatrixOutput(output.getName(), out1);
ec.setMatrixOutput(_out2.getName(), out2);
ec.setMatrixOutput(_out3.getName(), out3);
ec.setMatrixOutput(_out4.getName(), out4);
ec.setMatrixOutput(_out5.getName(), out5);
}
@Override
public void processInstruction(ExecutionContext ec) {
if (instOpcode.equalsIgnoreCase(Opcodes.BIAS_ADD.toString())) {
processBiasAddInstruction(ec);
return;
}
else if (instOpcode.equalsIgnoreCase(Opcodes.BIAS_MULTIPLY.toString())) {
processBiasMultiplyInstruction(ec);
return;
}
else if (instOpcode.equalsIgnoreCase(Opcodes.RELU_BACKWARD.toString())) {
processReluBackwardInstruction(ec);
return;
}
else if (instOpcode.equalsIgnoreCase(Opcodes.BATCH_NORM2D.toString())) {
processBatchNorm2dInstruction(ec);
return;
}
else if (instOpcode.equalsIgnoreCase(Opcodes.BATCH_NORM2D_BACKWARD.toString())) {
processBatchNorm2dBackwardInstruction(ec);
return;
}
else if (instOpcode.equalsIgnoreCase(Opcodes.LSTM.toString())) {
processLSTMInstruction(ec, false);
return;
}
else if (instOpcode.equalsIgnoreCase(Opcodes.LSTM_BACKWARD.toString())) {
processLSTMInstruction(ec, true);
return;
}
// acquire inputs
MatrixBlock outputBlock = null;
MatrixBlock matBlock = instOpcode.equalsIgnoreCase(Opcodes.AVGPOOLING_BACKWARD.toString()) ? null : ec.getMatrixInput(input1.getName());
int pad_h = getScalarInput(ec, _padding, 0);
int pad_w = getScalarInput(ec, _padding, 1);
int stride_h = getScalarInput(ec, _stride, 0);
int stride_w = getScalarInput(ec, _stride, 1);
int N = getScalarInput(ec, _input_shape, 0);
int C = getScalarInput(ec, _input_shape, 1);
int H = getScalarInput(ec, _input_shape, 2);
int W = getScalarInput(ec, _input_shape, 3);
int K = getScalarInput(ec, _filter_shape, 0);
int R = getScalarInput(ec, _filter_shape, 2);
int S = getScalarInput(ec, _filter_shape, 3);
int P = (int) DnnUtils.getP(H, R, stride_h, pad_h);
int Q = (int) DnnUtils.getQ(W, S, stride_w, pad_w);
DnnParameters params = new DnnParameters(N, C, H, W, K, R, S, stride_h, stride_w, pad_h, pad_w, _numThreads);
params.enableNative = NativeHelper.isNativeLibraryLoaded();
if (instOpcode.equalsIgnoreCase(Opcodes.MAXPOOLING.toString()) || instOpcode.equalsIgnoreCase(Opcodes.RELU_MAXPOOLING.toString()) ||
instOpcode.equalsIgnoreCase(Opcodes.AVGPOOLING.toString())) {
if(matBlock.isEmpty()) {
outputBlock = new MatrixBlock(N, C*P*Q, true);
}
else {
outputBlock = new MatrixBlock(N, C*P*Q, false).allocateBlock();
PoolingType poolType = (instOpcode.equalsIgnoreCase(Opcodes.MAXPOOLING.toString()) || instOpcode.equalsIgnoreCase(Opcodes.RELU_MAXPOOLING.toString())) ? PoolingType.MAX : PoolingType.AVG;
if(instOpcode.equalsIgnoreCase(Opcodes.RELU_MAXPOOLING.toString()))
params.minValForMaxPoolOperations = 0;
LibMatrixDNN.pooling(matBlock, outputBlock, params, poolType);
}
}
else if (instOpcode.equalsIgnoreCase(Opcodes.MAXPOOLING_BACKWARD.toString()) || instOpcode.equalsIgnoreCase(Opcodes.RELU_MAXPOOLING_BACKWARD.toString()) ||
instOpcode.equalsIgnoreCase(Opcodes.AVGPOOLING_BACKWARD.toString())) {
MatrixBlock dout = ec.getMatrixInput(_in2.getName());
boolean isEmpty = instOpcode.equalsIgnoreCase(Opcodes.AVGPOOLING_BACKWARD.toString()) ? dout.isEmpty() : (matBlock.isEmpty() || dout.isEmpty());
if(isEmpty) {
outputBlock = new MatrixBlock(N, C*H*W, true);
}
else {
PoolingType poolType = (instOpcode.equalsIgnoreCase(Opcodes.MAXPOOLING_BACKWARD.toString()) || instOpcode.equalsIgnoreCase(Opcodes.RELU_MAXPOOLING_BACKWARD.toString())) ? PoolingType.MAX : PoolingType.AVG;
outputBlock = (poolType == PoolingType.MAX ) ? new MatrixBlock(N, C*H*W, true).allocateBlock() : new MatrixBlock(N, C*H*W, false).allocateBlock();
boolean performReLUBackward = instOpcode.equalsIgnoreCase(Opcodes.RELU_MAXPOOLING_BACKWARD.toString());
if(performReLUBackward)
params.minValForMaxPoolOperations = 0;
LibMatrixDNN.poolingBackward(matBlock, dout, outputBlock, params, performReLUBackward, poolType);
}
ec.releaseMatrixInput(_in2.getName());
}
else if (instOpcode.equalsIgnoreCase(Opcodes.CONV2D.toString())) {
resetNumThreads(params, C*R*S, P*Q, matBlock.getNonZeros() / (matBlock.getNumRows()*matBlock.getNumColumns()));
MatrixBlock filter = ec.getMatrixInput(_in2.getName());
if(filter.isEmpty() || matBlock.isEmpty()) {
outputBlock = new MatrixBlock(N, K*P*Q, true);
}
else {
boolean sparse = matBlock.isUltraSparse(false) && params.bias == null
&& matBlock.getInMemorySize() < MatrixBlock.estimateSizeDenseInMemory(N, K*P*Q);
outputBlock = new MatrixBlock(N, K*P*Q, sparse).allocateBlock();
if(params.enableNative && matBlock.isInSparseFormat())
matBlock.sparseToDense();
if(params.enableNative && !isFilterSparse(filter) && !matBlock.isInSparseFormat())
LibMatrixNative.conv2d(matBlock, filter, outputBlock, params);
else
LibMatrixDNN.conv2d(matBlock, filter, outputBlock, params);
}
ec.releaseMatrixInput(_in2.getName());
}
else if (instOpcode.equalsIgnoreCase(Opcodes.CONV2D_BIAS_ADD.toString())) {
resetNumThreads(params, C*R*S, P*Q, matBlock.getNonZeros() / (matBlock.getNumRows()*matBlock.getNumColumns()));
MatrixBlock filter = ec.getMatrixInput(_in3.getName());
MatrixBlock bias = ec.getMatrixInput(_in2.getName());
if(bias.getNumRows() != params.K || bias.getNumColumns() != 1) {
throw new DMLRuntimeException("Incorrect shape of bias matrix: [" + bias.getNumRows() + " " + bias.getNumColumns() + "]. "
+ "Expected: [" + params.K + ", 1]");
}
boolean isOutputConvEmpty = filter.isEmpty() || matBlock.isEmpty();
if(isOutputConvEmpty && bias.isEmpty()) {
// bias_add(empty mb, empty mb) = empty mb
outputBlock = new MatrixBlock(N, K*P*Q, true);
}
else if(isOutputConvEmpty && !bias.isEmpty()) {
// Add bias to empty output block
// bias_add(empty mb, bias)
outputBlock = new MatrixBlock(N, K*P*Q, false).allocateBlock();
for(int n = 0; n < params.N; n++)
DnnUtils.fillBias(bias, outputBlock.getDenseBlockValues(),
n, n+1, params.N, params.K, params.P*params.Q);
}
else {
outputBlock = new MatrixBlock(N, K*P*Q, false).allocateBlock();
if(!bias.isEmpty()) {
// Handle situation where both input and filter are non empty, but bias is empty
params.bias = bias;
}
if(params.enableNative && matBlock.isInSparseFormat())
matBlock.sparseToDense();
if(params.enableNative && !isFilterSparse(filter) && !matBlock.isInSparseFormat())
LibMatrixNative.conv2d(matBlock, filter, outputBlock, params);
else
LibMatrixDNN.conv2d(matBlock, filter, outputBlock, params);
}
ec.releaseMatrixInput(_in3.getName(), _in2.getName());
}
else if (instOpcode.equalsIgnoreCase(Opcodes.CONV2D_BACKWARD_FILTER.toString())) {
MatrixBlock dout = ec.getMatrixInput(_in2.getName());
if(dout.isEmpty() || matBlock.isEmpty()) {
outputBlock = new MatrixBlock(K, C*R*S, true);
}
else {
outputBlock = new MatrixBlock(K, C*R*S, false).allocateBlock();
if(params.enableNative && !matBlock.isInSparseFormat() && !dout.isInSparseFormat())
LibMatrixNative.conv2dBackwardFilter(matBlock, dout, outputBlock, params);
else
LibMatrixDNN.conv2dBackwardFilter(matBlock, dout, outputBlock, params);
}
ec.releaseMatrixInput(_in2.getName());
}
else if (instOpcode.equalsIgnoreCase(Opcodes.CONV2D_BACKWARD_DATA.toString())) {
MatrixBlock dout = ec.getMatrixInput(_in2.getName());
if(dout.isEmpty() || matBlock.isEmpty()) {
outputBlock = new MatrixBlock(N, C * H * W, true);
}
else {
outputBlock = new MatrixBlock(N, C * H * W, false).allocateBlock();
if(params.enableNative && !isFilterSparse(matBlock) && !dout.isInSparseFormat())
LibMatrixNative.conv2dBackwardData(matBlock, dout, outputBlock, params);
else
LibMatrixDNN.conv2dBackwardData(matBlock, dout, outputBlock, params);
}
ec.releaseMatrixInput(_in2.getName());
}
else {
throw new DMLRuntimeException("Unsupported op code " + instOpcode);
}
// release inputs/outputs
if(!instOpcode.equalsIgnoreCase(Opcodes.AVGPOOLING_BACKWARD.toString()))
ec.releaseMatrixInput(input1.getName());
ec.setMatrixOutput(getOutputVariableName(), outputBlock);
}
/**
* Reset the number of thread to respect the intermediate CP memory budget
*
* @param params convolution parameters
* @param numRows number of rows of intermediate matrix used per thread
* @param numCols number of rows of intermediate matrix used per thread
* @param sparsity sparsity of intermediate matrix used per thread
*/
private void resetNumThreads(DnnParameters params, int numRows, int numCols, double sparsity) {
if(DMLScript.USE_ACCELERATOR) {
double memBudget1Thread = OptimizerUtils.estimateSizeExactSparsity(numRows, numCols, sparsity);
int limitedDegreeOfParallelism = (int) Math.floor(_intermediateMemoryBudget / memBudget1Thread);
if(params.numThreads > limitedDegreeOfParallelism) {
params.numThreads = limitedDegreeOfParallelism;
if(!warnedUnderUtilitization)
LOG.warn("CPU Under-utilization to respect the intermediate memory budget. To avoid this, please try reducing the mini-batch or forcing gpu execution.");
warnedUnderUtilitization = true;
}
}
}
@Override
public Pair<String, LineageItem> getLineageItem(ExecutionContext ec) {
ArrayList<CPOperand> inputs = new ArrayList<>();
inputs.add(input1);
inputs.add(_in2);
inputs.add(_in3);
inputs.add(_in4);
inputs.add(_in5);
inputs.add(_in6);
inputs.add(_in7);
inputs.add(_in8);
inputs.addAll(_input_shape);
inputs.addAll(_filter_shape);
inputs.addAll(_stride);
inputs.addAll(_padding);
return Pair.of(output.getName(),
new LineageItem(getOpcode(), LineageItemUtils.getLineage(ec, inputs.toArray(new CPOperand[0]))));
}
}
|
apache/flex-blazeds | 36,796 | core/src/main/java/flex/messaging/config/MessagingConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package flex.messaging.config;
import flex.management.ManageableComponent;
import flex.management.runtime.messaging.endpoints.EndpointControl;
import flex.messaging.Destination;
import flex.messaging.FlexComponent;
import flex.messaging.FlexContext;
import flex.messaging.MessageBroker;
import flex.messaging.Server;
import flex.messaging.client.FlexClientManager;
import flex.messaging.cluster.ClusterManager;
import flex.messaging.endpoints.AbstractEndpoint;
import flex.messaging.endpoints.Endpoint;
import flex.messaging.endpoints.Endpoint2;
import flex.messaging.log.Log;
import flex.messaging.log.Target;
import flex.messaging.security.LoginCommand;
import flex.messaging.security.LoginManager;
import flex.messaging.services.AuthenticationService;
import flex.messaging.services.Service;
import flex.messaging.services.ServiceAdapter;
import flex.messaging.util.ClassUtil;
import flex.messaging.util.RedeployManager;
import flex.messaging.util.StringUtils;
import flex.messaging.util.ToStringPrettyPrinter;
import flex.messaging.util.UUIDGenerator;
import flex.messaging.validators.DeserializationValidator;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* This object encapsulates settings for a MessageBroker instance.
* The MessageBroker itself has no knowledge of configuration specifics;
* instead, this object sets the relevant values on the broker using
* information which a ConfigurationParser has provided for it.
*/
public class MessagingConfiguration implements ServicesConfiguration {
private final String asyncMessageBrokerType = "flex.messaging.AsyncMessageBroker";
private final String asyncFlexClientManagerType = "flex.messaging.client.AsyncFlexClientManager";
private final Map<String, ChannelSettings> channelSettings;
private final List<String> defaultChannels;
private final SecuritySettings securitySettings;
private final List<ServiceSettings> serviceSettings;
private final List<SharedServerSettings> sharedServerSettings;
private LoggingSettings loggingSettings;
private SystemSettings systemSettings;
private FlexClientSettings flexClientSettings;
private final Map<String, ClusterSettings> clusterSettings;
private final Map<String, FactorySettings> factorySettings;
private final List<MessageFilterSettings> messageFilterSettings;
private final Map<String, ValidatorSettings> validatorSettings;
/**
* Constructor.
* Construct a MessagingConfiguration object
*/
public MessagingConfiguration() {
channelSettings = new HashMap<String, ChannelSettings>();
defaultChannels = new ArrayList<String>(4);
clusterSettings = new HashMap<String, ClusterSettings>();
factorySettings = new HashMap<String, FactorySettings>();
serviceSettings = new ArrayList<ServiceSettings>();
sharedServerSettings = new ArrayList<SharedServerSettings>();
securitySettings = new SecuritySettings();
messageFilterSettings = new ArrayList<MessageFilterSettings>();
validatorSettings = new HashMap<String, ValidatorSettings>();
}
/**
* Configure the MessageBroker.
*
* @param broker current MessageBroker object
*/
public void configureBroker(MessageBroker broker) {
boolean async = (broker.getClass().getName().equals(asyncMessageBrokerType));
broker.setChannelSettings(channelSettings);
broker.setSecuritySettings(securitySettings);
broker.setSystemSettings(systemSettings);
broker.setFlexClientSettings(flexClientSettings);
// validators need to come first so that the other code can use them
createValidators(broker);
createAuthorizationManager(broker);
createFlexClientManager(broker);
createRedeployManager(broker);
createFactories(broker);
if (async)
createSharedServers(broker);
createEndpoints(broker);
// Default channels have to be set after endpoints are created.
broker.setDefaultChannels(defaultChannels);
prepareClusters(broker);
createServices(broker);
if (async)
createMessageFilters(broker);
createUUIDGenerator(broker);
}
/**
* Create a MessageBroker object with the Id.
*
* @param id String the MessageBroker Id
* @param loader the ClassLoader used to load the MessageBroker class
* @return the created MessageBroker object
*/
public MessageBroker createBroker(String id, ClassLoader loader) {
// Construct MessageBroker with manageable constructor to avoid loading
// any JMX classes in case manageable is set to false.
MessageBroker broker;
try // Use the AsyncMessageBroker, if possible.
{
@SuppressWarnings("unchecked")
Class<? extends MessageBroker> messageBrokerClass = ClassUtil.createClass(asyncMessageBrokerType, loader);
Constructor constructor = messageBrokerClass.getConstructor(boolean.class);
broker = (MessageBroker) constructor.newInstance(systemSettings.isManageable());
} catch (Throwable t) // Otherwise, use the default MessageBroker.
{
broker = new MessageBroker(systemSettings.isManageable());
}
// Initialize MessageBroker.
broker.setEnforceEndpointValidation(systemSettings.isEnforceEndpointValidation());
//broker.setManaged(systemSettings.isManageable());
broker.setId(id);
broker.setClassLoader(loader);
return broker;
}
private void createFactories(MessageBroker broker) {
for (Iterator<Map.Entry<String, FactorySettings>> iter = factorySettings.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry<String, FactorySettings> entry = iter.next();
String id = entry.getKey();
FactorySettings factorySetting = entry.getValue();
broker.addFactory(id, factorySetting.createFactory(broker.getClassLoader()));
}
}
private void createFlexClientManager(MessageBroker broker) {
FlexClientManager flexClientManager = null;
try // Use the async version, if possible.
{
@SuppressWarnings("unchecked")
Class<? extends FlexClientManager> flexClientManagerClass = ClassUtil.createClass(asyncFlexClientManagerType, broker.getClassLoader());
Constructor ctor = flexClientManagerClass.getConstructor(broker.getClass());
flexClientManager = (FlexClientManager) ctor.newInstance(broker);
} catch (Throwable t) // Otherwise, use the default FlexClientManager.
{
flexClientManager = new FlexClientManager(broker.isManaged(), broker);
}
broker.setFlexClientManager(flexClientManager);
}
private void createRedeployManager(MessageBroker broker) {
RedeployManager redeployManager = new RedeployManager();
redeployManager.setEnabled(systemSettings.getRedeployEnabled());
redeployManager.setWatchInterval(systemSettings.getWatchInterval());
redeployManager.setTouchFiles(systemSettings.getTouchFiles());
redeployManager.setWatchFiles(systemSettings.getWatchFiles());
broker.setRedeployManager(redeployManager);
}
private void createAuthorizationManager(MessageBroker broker) {
LoginManager loginManager = new LoginManager();
// Create a Login Command for the LoginManager.
LoginCommand loginCommand = null;
Map loginCommands = securitySettings.getLoginCommands();
// If default Login Command is enabled, use it.
LoginCommandSettings loginCommandSettings = (LoginCommandSettings) loginCommands.get(LoginCommandSettings.SERVER_MATCH_OVERRIDE);
if (loginCommandSettings != null) {
loginCommand = initLoginCommand(loginCommandSettings);
}
// Otherwise, try a server specific Login Command.
else {
String serverInfo = securitySettings.getServerInfo();
loginCommandSettings = (LoginCommandSettings) loginCommands.get(serverInfo);
if (loginCommandSettings != null) {
loginCommand = initLoginCommand(loginCommandSettings);
} else {
// Try a partial match of serverInfo
serverInfo = serverInfo.toLowerCase();
for (Iterator iterator = loginCommands.keySet().iterator(); iterator.hasNext(); ) {
String serverMatch = (String) iterator.next();
loginCommandSettings = (LoginCommandSettings) loginCommands.get(serverMatch);
if (serverInfo.indexOf(serverMatch.toLowerCase()) != -1) {
// add this match for easier lookup next time around
loginCommands.put(serverInfo, loginCommandSettings);
loginCommand = initLoginCommand(loginCommandSettings);
break;
}
}
}
}
if (loginCommand == null) {
if (Log.isWarn())
Log.getLogger(ConfigurationManager.LOG_CATEGORY).warn
("No login command was found for '" + securitySettings.getServerInfo()
+ "'. Please ensure that the login-command tag has the correct server attribute value"
+ ", or use 'all' to use the login command regardless of the server.");
} else {
loginManager.setLoginCommand(loginCommand);
}
if (loginCommandSettings != null)
loginManager.setPerClientAuthentication(loginCommandSettings.isPerClientAuthentication());
broker.setLoginManager(loginManager);
}
private LoginCommand initLoginCommand(LoginCommandSettings loginCommandSettings) {
String loginClass = loginCommandSettings.getClassName();
Class c = ClassUtil.createClass(loginClass,
FlexContext.getMessageBroker() == null ? null :
FlexContext.getMessageBroker().getClassLoader());
LoginCommand loginCommand = (LoginCommand) ClassUtil.createDefaultInstance(c, LoginCommand.class);
return loginCommand;
}
private void createSharedServers(MessageBroker broker) {
for (SharedServerSettings settings : sharedServerSettings) {
String id = settings.getId();
String className = settings.getClassName();
Class serverClass = ClassUtil.createClass(className, broker.getClassLoader());
FlexComponent server = (FlexComponent) ClassUtil.createDefaultInstance(serverClass, serverClass);
server.initialize(id, settings.getProperties());
if (broker.isManaged() && (server instanceof ManageableComponent)) {
ManageableComponent manageableServer = (ManageableComponent) server;
manageableServer.setManaged(true);
manageableServer.setParent(broker);
}
// TODO: move this to only AsyncMessageBroker.
broker.addServer((Server) server);
if (Log.isInfo()) {
Log.getLogger(ConfigurationManager.LOG_CATEGORY).info
("Server '" + id + "' of type '" + className + "' created.");
}
}
}
private void createEndpoints(MessageBroker broker) {
for (Iterator<String> iter = channelSettings.keySet().iterator(); iter.hasNext(); ) {
String id = iter.next();
ChannelSettings chanSettings = channelSettings.get(id);
String url = chanSettings.getUri();
String endpointClassName = chanSettings.getEndpointType();
// Create the Endpoint
Endpoint endpoint = broker.createEndpoint(id, url, endpointClassName);
// Cast to AbstractEndpoint - these are newer properties that post-date the locked Endpoint interface.
if (endpoint instanceof AbstractEndpoint) {
AbstractEndpoint abstractEndpoint = (AbstractEndpoint) endpoint;
abstractEndpoint.setRemote(chanSettings.isRemote());
abstractEndpoint.setServerOnly(chanSettings.getServerOnly());
}
endpoint.setSecurityConstraint(chanSettings.getConstraint());
endpoint.setClientType(chanSettings.getClientType());
// Assign referenced server
String referencedServerId = chanSettings.getServerId();
if ((referencedServerId != null) && (endpoint instanceof Endpoint2)) {
Server server = broker.getServer(referencedServerId);
if (server == null) {
ConfigurationException ce = new ConfigurationException();
ce.setMessage(11128, new Object[]{chanSettings.getId(), referencedServerId});
throw ce;
}
((Endpoint2) endpoint).setServer(broker.getServer(referencedServerId));
}
// Initialize with endpoint properties
endpoint.initialize(id, chanSettings.getProperties());
if (Log.isInfo()) {
String endpointURL = endpoint.getUrl();
String endpointSecurity = EndpointControl.getSecurityConstraintOf(endpoint);
if (StringUtils.isEmpty(endpointSecurity))
endpointSecurity = "None";
Log.getLogger(ConfigurationManager.LOG_CATEGORY).info
("Endpoint '" + id + "' created with security: " +
endpointSecurity + StringUtils.NEWLINE +
"at URL: " + endpointURL);
}
}
}
private void createServices(MessageBroker broker) {
//the broker needs its AuthenticationService always
AuthenticationService authService = new AuthenticationService();
authService.setMessageBroker(broker);
for (Iterator<ServiceSettings> iter = serviceSettings.iterator(); iter.hasNext(); ) {
ServiceSettings svcSettings = iter.next();
String svcId = svcSettings.getId();
String svcClassName = svcSettings.getClassName();
// Create the Service
Service service = broker.createService(svcId, svcClassName);
// Service Class Name - not needed in AbstractService
// Initialize with service properties
service.initialize(svcId, svcSettings.getProperties());
// Default Channels
for (Iterator chanIter = svcSettings.getDefaultChannels().iterator(); chanIter.hasNext(); ) {
ChannelSettings chanSettings = (ChannelSettings) chanIter.next();
service.addDefaultChannel(chanSettings.getId());
}
// Adapter Definitions
Map svcAdapterSettings = svcSettings.getAllAdapterSettings();
for (Iterator asIter = svcAdapterSettings.values().iterator(); asIter.hasNext(); ) {
AdapterSettings as = (AdapterSettings) asIter.next();
service.registerAdapter(as.getId(), as.getClassName());
if (as.isDefault()) {
service.setDefaultAdapter(as.getId());
}
}
// Destinations
Map destinationSettings = svcSettings.getDestinationSettings();
for (Iterator destSettingsIter = destinationSettings.keySet().iterator(); destSettingsIter.hasNext(); ) {
String destName = (String) destSettingsIter.next();
DestinationSettings destSettings = (DestinationSettings) destinationSettings.get(destName);
createDestination(destSettings, service, svcSettings);
}
}
}
private void createDestination(DestinationSettings destSettings, Service service, ServiceSettings svcSettings) {
String destId = destSettings.getId();
Destination destination = service.createDestination(destId);
// Channels
List chanSettings = destSettings.getChannelSettings();
if (chanSettings.size() > 0) {
List<String> channelIds = new ArrayList<String>(2);
for (Iterator iter = chanSettings.iterator(); iter.hasNext(); ) {
ChannelSettings cs = (ChannelSettings) iter.next();
channelIds.add(cs.getId());
}
destination.setChannels(channelIds);
}
// Security
SecurityConstraint constraint = destSettings.getConstraint();
destination.setSecurityConstraint(constraint);
// Initialize with service, adapter and destination properties
destination.initialize(destId, svcSettings.getProperties());
destination.initialize(destId, destSettings.getAdapterSettings().getProperties());
destination.initialize(destId, destSettings.getProperties());
// Service Adapter
createAdapter(destination, destSettings, svcSettings);
}
private void createAdapter(Destination destination, DestinationSettings destSettings, ServiceSettings svcSettings) {
AdapterSettings adapterSettings = destSettings.getAdapterSettings();
String adapterId = adapterSettings.getId();
ServiceAdapter adapter = destination.createAdapter(adapterId);
// Initialize with service, adapter and then destination properties
adapter.initialize(adapterId, svcSettings.getProperties());
adapter.initialize(adapterId, adapterSettings.getProperties());
adapter.initialize(adapterId, destSettings.getProperties());
}
/**
* Used by the MessageBrokerServlet to set up the singleton Log instance
* and add any targets defined in the logging configuration.
* This needs to be invoked ahead of creating and bootstrapping a MessageBroker
* instance so we're sure to have the logging system running in case the bootstrap
* process needs to log anything out.
*/
public void createLogAndTargets() {
if (loggingSettings == null) {
Log.setPrettyPrinterClass(ToStringPrettyPrinter.class.getName());
return;
}
Log.createLog();
ConfigMap properties = loggingSettings.getProperties();
// Override default pretty printer for FDS to traverse deep Object graphs
if (properties.getPropertyAsString("pretty-printer", null) == null) {
Log.setPrettyPrinterClass(ToStringPrettyPrinter.class.getName());
}
Log.initialize(null, properties);
// Targets
List targets = loggingSettings.getTargets();
Iterator it = targets.iterator();
while (it.hasNext()) {
TargetSettings targetSettings = (TargetSettings) it.next();
String className = targetSettings.getClassName();
Class c = ClassUtil.createClass(className,
FlexContext.getMessageBroker() == null ? null :
FlexContext.getMessageBroker().getClassLoader());
try {
Target target = (Target) c.newInstance();
target.setLevel(Log.readLevel(targetSettings.getLevel()));
target.setFilters(targetSettings.getFilters());
target.initialize(null, targetSettings.getProperties());
Log.addTarget(target);
} catch (Throwable t) {
// Unwrap to get to the interesting exception
if (t instanceof InvocationTargetException)
t = t.getCause();
System.err.println("*** Error setting up logging system");
t.printStackTrace();
ConfigurationException cx = new ConfigurationException();
cx.setMessage(10126, new Object[]{className});
cx.setRootCause(t);
throw cx;
}
}
}
private void createMessageFilters(MessageBroker broker) {
Class asyncFilterClass = ClassUtil.createClass("flex.messaging.filters.BaseAsyncMessageFilter");
Class syncFilterClass = ClassUtil.createClass("flex.messaging.filters.BaseSyncMessageFilter");
for (MessageFilterSettings settings : messageFilterSettings) {
String id = settings.getId();
String className = settings.getClassName();
Class filterClass = ClassUtil.createClass(className, broker.getClassLoader());
FlexComponent filter = (FlexComponent) ClassUtil.createDefaultInstance(filterClass, null);
MessageFilterSettings.FilterType filterType = settings.getFilterType();
boolean filterIsAsync = filterType == MessageFilterSettings.FilterType.ASYNC;
// Validate filter is assignable to proper base class.
if ((filterIsAsync && !asyncFilterClass.isAssignableFrom(filterClass)) ||
(!filterIsAsync && !syncFilterClass.isAssignableFrom(filterClass))) {
// Filter class is not a valid subclass of either supported base filter type.
ConfigurationException cx = new ConfigurationException();
int errorCode = filterIsAsync ? 11144 : 11145;
cx.setMessage(errorCode, new Object[]{settings.getId()});
throw cx;
}
filter.initialize(id, settings.getProperties());
if (broker.isManaged() && (filter instanceof ManageableComponent)) {
ManageableComponent manageableFilter = (ManageableComponent) filter;
manageableFilter.setManaged(true);
manageableFilter.setParent(broker);
}
try {
String methodName = filterIsAsync ? "getAsyncMessageFilterChain" : "getSyncMessageFilterChain";
Method getMessageFilterChain = broker.getClass().getDeclaredMethod(methodName);
Object filterChain = getMessageFilterChain.invoke(broker, (Object[]) null);
Class arg = filterIsAsync ? asyncFilterClass : syncFilterClass;
Method addFilter = filterChain.getClass().getDeclaredMethod("add", arg);
addFilter.invoke(filterChain, filter);
} catch (Exception e) {
// Hit an unexpected problem adding the filter instance to the broker's async or sync chain.
ConfigurationException cx = new ConfigurationException();
int errorCode = filterType == MessageFilterSettings.FilterType.ASYNC ? 11138 : 11143;
cx.setMessage(errorCode, new Object[]{settings.getId()});
cx.setRootCause(e);
throw cx;
}
if (Log.isInfo()) {
Log.getLogger(ConfigurationManager.LOG_CATEGORY).info
("MessageFilter '" + id + "' of type '" + className + "' created.");
}
}
}
private void createValidators(MessageBroker broker) {
for (Iterator<ValidatorSettings> iter = validatorSettings.values().iterator(); iter.hasNext(); ) {
ValidatorSettings settings = iter.next();
String className = settings.getClassName();
String type = settings.getType();
Class<?> validatorClass = ClassUtil.createClass(className, broker.getClassLoader());
Class<?> expectedClass = ClassUtil.createClass(type, broker.getClassLoader());
Object validator = ClassUtil.createDefaultInstance(validatorClass, expectedClass);
// Only set the DeserializationValidator types for now.
if (validator instanceof DeserializationValidator) {
DeserializationValidator deserializationValidator = (DeserializationValidator) validator;
deserializationValidator.initialize(null, settings.getProperties());
broker.setDeserializationValidator(deserializationValidator);
if (Log.isInfo()) {
Log.getLogger(ConfigurationManager.LOG_CATEGORY).info
("DeserializationValidator of type '" + className + "' created.");
}
}
}
}
private void createUUIDGenerator(MessageBroker broker) {
String className = systemSettings.getUUIDGeneratorClassName();
if (className == null || className.length() == 0)
return;
Class uuidGeneratorClass = ClassUtil.createClass(className, broker.getClassLoader());
if (!UUIDGenerator.class.isAssignableFrom(uuidGeneratorClass)) {
// UUID Generator class is not a valid subclass of ''{0}''
ConfigurationException cx = new ConfigurationException();
cx.setMessage(11148, new Object[]{UUIDGenerator.class.getName()});
throw cx;
}
Object uuidGenerator = ClassUtil.createDefaultInstance(uuidGeneratorClass, UUIDGenerator.class);
broker.setUUIDGenerator((UUIDGenerator) uuidGenerator);
}
private void prepareClusters(MessageBroker broker) {
ClusterManager clusterManager = broker.getClusterManager();
for (Iterator<String> iter = clusterSettings.keySet().iterator(); iter.hasNext(); ) {
String clusterId = iter.next();
ClusterSettings cs = clusterSettings.get(clusterId);
clusterManager.prepareCluster(cs);
}
}
/**
* Add Shared Server configurations.
*
* @param settings the SharedServerSettings object
**/
public void addSharedServerSettings(SharedServerSettings settings) {
sharedServerSettings.add(settings);
}
/**
* Add the Channel configurations.
*
* @param id the ChannelSetting Id
* @param settings the ChannelSettings
**/
public void addChannelSettings(String id, ChannelSettings settings) {
channelSettings.put(id, settings);
}
/**
* Get the ChannelSettings by Id.
*
* @param id the ChannelSettings Id
* @return ChannelSettings the Channel settings
**/
public ChannelSettings getChannelSettings(String id) {
return channelSettings.get(id);
}
/**
* Get all the ChannelSettings.
*
* @return Map the Map of all the ChannelSettings, maped by Id
**/
public Map getAllChannelSettings() {
return channelSettings;
}
/**
* Add the default Channel by Id.
*
* @param id the Channel Id
**/
public void addDefaultChannel(String id) {
defaultChannels.add(id);
}
/**
* Get the default Channel List.
*
* @return List, the list of default Channels
**/
public List getDefaultChannels() {
return defaultChannels;
}
/**
* Get the Security Configurations.
*
* @return SecuritySettings current SecuritySettings
**/
public SecuritySettings getSecuritySettings() {
return securitySettings;
}
/**
* Add Service Configurations.
*
* @param settings the ServiceSettings object
**/
public void addServiceSettings(ServiceSettings settings) {
serviceSettings.add(settings);
}
/**
* Get ServiceSettings by Id.
*
* @param id the ServiceSettings Id
* @return ServiceSettings the ServiceSettings object
**/
public ServiceSettings getServiceSettings(String id) {
for (Iterator<ServiceSettings> iter = serviceSettings.iterator(); iter.hasNext(); ) {
ServiceSettings serviceSettings = iter.next();
if (serviceSettings.getId().equals(id))
return serviceSettings;
}
return null;
}
/**
* Get all ServiceSettings.
*
* @return List all the service settings
**/
public List getAllServiceSettings() {
return serviceSettings;
}
/**
* Get LoggingSettings.
*
* @return LoggingSettings the LoggingSettings object
**/
public LoggingSettings getLoggingSettings() {
return loggingSettings;
}
/**
* Set LoggingSettings.
*
* @param loggingSettings the LoggingSettings object
**/
public void setLoggingSettings(LoggingSettings loggingSettings) {
this.loggingSettings = loggingSettings;
}
/**
* Set SystemSettings.
*
* @param ss the SystemSettings object
**/
public void setSystemSettings(SystemSettings ss) {
systemSettings = ss;
}
/**
* Get SystemSettings.
*
* @return SystemSettings the LoggingSettings object
**/
public SystemSettings getSystemSettings() {
return systemSettings;
}
/**
* Set FlexClientSettings.
*
* @param value the FlexClientSettings object
**/
public void setFlexClientSettings(FlexClientSettings value) {
flexClientSettings = value;
}
/**
* Get FlexClientSettings.
*
* @return FlexClientSettings the FlexClientSettings object
**/
public FlexClientSettings getFlexClientSettings() {
return flexClientSettings;
}
/**
* Add the ClusterSettings.
*
* @param settings the ClusterSettings object
**/
public void addClusterSettings(ClusterSettings settings) {
if (settings.isDefault()) {
for (Iterator<ClusterSettings> it = clusterSettings.values().iterator(); it.hasNext(); ) {
ClusterSettings cs = it.next();
if (cs.isDefault()) {
ConfigurationException cx = new ConfigurationException();
cx.setMessage(10214, new Object[]{settings.getClusterName(), cs.getClusterName()});
throw cx;
}
}
}
if (clusterSettings.containsKey(settings.getClusterName())) {
ConfigurationException cx = new ConfigurationException();
cx.setMessage(10206, new Object[]{settings.getClusterName()});
throw cx;
}
clusterSettings.put(settings.getClusterName(), settings);
}
/**
* Get the ClusterSettings object by Id.
*
* @param clusterId the ClusterSettings Id
* @return ClusterSettings the ClusterSettings object
**/
public ClusterSettings getClusterSettings(String clusterId) {
for (Iterator<ClusterSettings> it = clusterSettings.values().iterator(); it.hasNext(); ) {
ClusterSettings cs = it.next();
if (cs.getClusterName() == clusterId)
return cs; // handle null case
if (cs.getClusterName() != null && cs.getClusterName().equals(clusterId))
return cs;
}
return null;
}
/**
* Get the default ClusterSettings.
*
* @return ClusterSettings the default ClusterSetting object
**/
public ClusterSettings getDefaultCluster() {
for (Iterator<ClusterSettings> it = clusterSettings.values().iterator(); it.hasNext(); ) {
ClusterSettings cs = it.next();
if (cs.isDefault())
return cs;
}
return null;
}
/**
* Add FactorySettings by Id.
*
* @param id the FactorySettings Id
* @param settings the FactorySettings object
**/
public void addFactorySettings(String id, FactorySettings settings) {
factorySettings.put(id, settings);
}
/**
* Add MessageFilterSettings.
*
* @param settings the MessageFilterSettings object
**/
public void addMessageFilterSettings(MessageFilterSettings settings) {
messageFilterSettings.add(settings);
}
/**
* Add ValidatorSettings.
*
* @param settings the ValidatorSettings object
**/
public void addValidatorSettings(ValidatorSettings settings) {
String type = settings.getType();
if (validatorSettings.containsKey(type)) {
// Cannot add multiple validators with the same type ''{0}''
ConfigurationException ce = new ConfigurationException();
ce.setMessage(11136, new Object[]{type});
throw ce;
}
validatorSettings.put(type, settings);
}
/**
* Report unused properties.
**/
public void reportUnusedProperties() {
ArrayList<Object[]> findings = new ArrayList<Object[]>();
Iterator<ServiceSettings> serviceItr = serviceSettings.iterator();
while (serviceItr.hasNext()) {
ServiceSettings serviceSettings = serviceItr.next();
gatherUnusedProperties(serviceSettings.getId(), serviceSettings.getSourceFile(),
ConfigurationConstants.SERVICE_ELEMENT, serviceSettings, findings);
Iterator destinationItr = serviceSettings.getDestinationSettings().values().iterator();
while (destinationItr.hasNext()) {
DestinationSettings destinationSettings = (DestinationSettings) destinationItr.next();
gatherUnusedProperties(destinationSettings.getId(), destinationSettings.getSourceFile(),
ConfigurationConstants.DESTINATION_ELEMENT,
destinationSettings, findings);
AdapterSettings adapterSettings = destinationSettings.getAdapterSettings();
if (adapterSettings != null) {
gatherUnusedProperties(adapterSettings.getId(), adapterSettings.getSourceFile(),
ConfigurationConstants.ADAPTER_ELEMENT,
adapterSettings, findings);
}
}
}
Iterator<ChannelSettings> channelItr = channelSettings.values().iterator();
while (channelItr.hasNext()) {
ChannelSettings channelSettings = channelItr.next();
// Skip property validation for remote channel-definitions
if (channelSettings.isRemote())
continue;
gatherUnusedProperties(channelSettings.getId(), channelSettings.getSourceFile(),
ConfigurationConstants.CHANNEL_ELEMENT, channelSettings, findings);
}
Iterator<SharedServerSettings> serverItr = sharedServerSettings.iterator();
while (serverItr.hasNext()) {
SharedServerSettings serverSettings = serverItr.next();
gatherUnusedProperties(serverSettings.getId(), serverSettings.getSourceFile(),
ConfigurationConstants.SERVER_ELEMENT, serverSettings, findings);
}
if (!findings.isEmpty()) {
int errorNumber = 10149;
ConfigurationException exception = new ConfigurationException();
StringBuffer allDetails = new StringBuffer();
for (int i = 0; i < findings.size(); i++) {
allDetails.append(StringUtils.NEWLINE);
allDetails.append(" ");
exception.setDetails(errorNumber, "pattern", findings.get(i));
allDetails.append(exception.getDetails());
exception.setDetails(null);
}
exception.setMessage(errorNumber, new Object[]{allDetails});
throw exception;
}
}
private void gatherUnusedProperties
(String settingsId, String settingsSource, String settingsType,
PropertiesSettings settings, Collection<Object[]> result) {
List unusedProperties = settings.getProperties().findAllUnusedProperties();
int size = unusedProperties.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
String path = (String) unusedProperties.get(i);
result.add(new Object[]{path, settingsType, settingsId, settingsSource});
}
}
}
}
|
apache/freemarker | 36,620 | freemarker-core/src/main/java/freemarker/template/utility/DateUtil.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 freemarker.template.utility;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Date and time related utilities.
*/
public class DateUtil {
/**
* Show hours (24h); always 2 digits, like {@code 00}, {@code 05}, etc.
*/
public static final int ACCURACY_HOURS = 4;
/**
* Show hours and minutes (even if minutes is 00).
*/
public static final int ACCURACY_MINUTES = 5;
/**
* Show hours, minutes and seconds (even if seconds is 00).
*/
public static final int ACCURACY_SECONDS = 6;
/**
* Show hours, minutes and seconds and up to 3 fraction second digits, without trailing 0-s in the fraction part.
*/
public static final int ACCURACY_MILLISECONDS = 7;
/**
* Show hours, minutes and seconds and exactly 3 fraction second digits (even if it's 000)
*/
public static final int ACCURACY_MILLISECONDS_FORCED = 8;
public static final TimeZone UTC = TimeZone.getTimeZone("UTC");
private static final String REGEX_XS_TIME_ZONE
= "Z|(?:[-+][0-9]{2}:[0-9]{2})";
private static final String REGEX_ISO8601_BASIC_TIME_ZONE
= "Z|(?:[-+][0-9]{2}(?:[0-9]{2})?)";
private static final String REGEX_ISO8601_EXTENDED_TIME_ZONE
= "Z|(?:[-+][0-9]{2}(?::[0-9]{2})?)";
private static final String REGEX_XS_OPTIONAL_TIME_ZONE
= "(" + REGEX_XS_TIME_ZONE + ")?";
private static final String REGEX_ISO8601_BASIC_OPTIONAL_TIME_ZONE
= "(" + REGEX_ISO8601_BASIC_TIME_ZONE + ")?";
private static final String REGEX_ISO8601_EXTENDED_OPTIONAL_TIME_ZONE
= "(" + REGEX_ISO8601_EXTENDED_TIME_ZONE + ")?";
private static final String REGEX_XS_DATE_BASE
= "(-?[0-9]+)-([0-9]{2})-([0-9]{2})";
private static final String REGEX_ISO8601_BASIC_DATE_BASE
= "(-?[0-9]{4,}?)([0-9]{2})([0-9]{2})";
private static final String REGEX_ISO8601_EXTENDED_DATE_BASE
= "(-?[0-9]{4,})-([0-9]{2})-([0-9]{2})";
private static final String REGEX_XS_TIME_BASE
= "([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\\.([0-9]+))?";
private static final String REGEX_ISO8601_BASIC_TIME_BASE
= "([0-9]{2})(?:([0-9]{2})(?:([0-9]{2})(?:[\\.,]([0-9]+))?)?)?";
private static final String REGEX_ISO8601_EXTENDED_TIME_BASE
= "([0-9]{2})(?::([0-9]{2})(?::([0-9]{2})(?:[\\.,]([0-9]+))?)?)?";
private static final Pattern PATTERN_XS_DATE = Pattern.compile(
REGEX_XS_DATE_BASE + REGEX_XS_OPTIONAL_TIME_ZONE);
private static final Pattern PATTERN_ISO8601_BASIC_DATE = Pattern.compile(
REGEX_ISO8601_BASIC_DATE_BASE); // No time zone allowed here
private static final Pattern PATTERN_ISO8601_EXTENDED_DATE = Pattern.compile(
REGEX_ISO8601_EXTENDED_DATE_BASE); // No time zone allowed here
private static final Pattern PATTERN_XS_TIME = Pattern.compile(
REGEX_XS_TIME_BASE + REGEX_XS_OPTIONAL_TIME_ZONE);
private static final Pattern PATTERN_ISO8601_BASIC_TIME = Pattern.compile(
REGEX_ISO8601_BASIC_TIME_BASE + REGEX_ISO8601_BASIC_OPTIONAL_TIME_ZONE);
private static final Pattern PATTERN_ISO8601_EXTENDED_TIME = Pattern.compile(
REGEX_ISO8601_EXTENDED_TIME_BASE + REGEX_ISO8601_EXTENDED_OPTIONAL_TIME_ZONE);
private static final Pattern PATTERN_XS_DATE_TIME = Pattern.compile(
REGEX_XS_DATE_BASE
+ "T" + REGEX_XS_TIME_BASE
+ REGEX_XS_OPTIONAL_TIME_ZONE);
private static final Pattern PATTERN_ISO8601_BASIC_DATE_TIME = Pattern.compile(
REGEX_ISO8601_BASIC_DATE_BASE
+ "T" + REGEX_ISO8601_BASIC_TIME_BASE
+ REGEX_ISO8601_BASIC_OPTIONAL_TIME_ZONE);
private static final Pattern PATTERN_ISO8601_EXTENDED_DATE_TIME = Pattern.compile(
REGEX_ISO8601_EXTENDED_DATE_BASE
+ "T" + REGEX_ISO8601_EXTENDED_TIME_BASE
+ REGEX_ISO8601_EXTENDED_OPTIONAL_TIME_ZONE);
private static final Pattern PATTERN_XS_TIME_ZONE = Pattern.compile(
REGEX_XS_TIME_ZONE);
private static final String MSG_YEAR_0_NOT_ALLOWED
= "Year 0 is not allowed in XML schema dates. BC 1 is -1, AD 1 is 1.";
private DateUtil() {
// can't be instantiated
}
/**
* Returns the time zone object for the name (or ID). This differs from
* {@link TimeZone#getTimeZone(String)} in that the latest returns GMT
* if it doesn't recognize the name, while this throws an
* {@link UnrecognizedTimeZoneException}.
*
* @throws UnrecognizedTimeZoneException If the time zone name wasn't understood
*/
public static TimeZone getTimeZone(String name)
throws UnrecognizedTimeZoneException {
if (isGMTish(name)) {
if (name.equalsIgnoreCase("UTC")) {
return UTC;
}
return TimeZone.getTimeZone(name);
}
TimeZone tz = TimeZone.getTimeZone(name);
if (isGMTish(tz.getID())) {
throw new UnrecognizedTimeZoneException(name);
}
return tz;
}
/**
* Tells if a offset or time zone is GMT. GMT is a fuzzy term, it used to
* referred both to UTC and UT1.
*/
private static boolean isGMTish(String name) {
if (name.length() < 3) {
return false;
}
char c1 = name.charAt(0);
char c2 = name.charAt(1);
char c3 = name.charAt(2);
if (
!(
(c1 == 'G' || c1 == 'g')
&& (c2 == 'M' || c2 == 'm')
&& (c3 == 'T' || c3 == 't')
)
&&
!(
(c1 == 'U' || c1 == 'u')
&& (c2 == 'T' || c2 == 't')
&& (c3 == 'C' || c3 == 'c')
)
&&
!(
(c1 == 'U' || c1 == 'u')
&& (c2 == 'T' || c2 == 't')
&& (c3 == '1')
)
) {
return false;
}
if (name.length() == 3) {
return true;
}
String offset = name.substring(3);
if (offset.startsWith("+")) {
return offset.equals("+0") || offset.equals("+00")
|| offset.equals("+00:00");
} else {
return offset.equals("-0") || offset.equals("-00")
|| offset.equals("-00:00");
}
}
/**
* Format a date, time or dateTime with one of the ISO 8601 extended
* formats that is also compatible with the XML Schema format (as far as you
* don't have dates in the BC era). Examples of possible outputs:
* {@code "2005-11-27T15:30:00+02:00"}, {@code "2005-11-27"},
* {@code "15:30:00Z"}. Note the {@code ":00"} in the time zone offset;
* this is not required by ISO 8601, but included for compatibility with
* the XML Schema format. Regarding the B.C. issue, those dates will be
* one year off when read back according the XML Schema format, because of a
* mismatch between that format and ISO 8601:2000 Second Edition.
*
* <p>This method is thread-safe.
*
* @param date the date to convert to ISO 8601 string
* @param datePart whether the date part (year, month, day) will be included
* or not
* @param timePart whether the time part (hours, minutes, seconds,
* milliseconds) will be included or not
* @param offsetPart whether the time zone offset part will be included or
* not. This will be shown as an offset to UTC (examples:
* {@code "+01"}, {@code "-02"}, {@code "+04:30"}) or as {@code "Z"}
* for UTC (and for UT1 and for GMT+00, since the Java platform
* doesn't really care about the difference).
* Note that this can't be {@code true} when {@code timePart} is
* {@code false}, because ISO 8601 (2004) doesn't mention such
* patterns.
* @param accuracy tells which parts of the date/time to drop. The
* {@code datePart} and {@code timePart} parameters are stronger than
* this. Note that when {@link #ACCURACY_MILLISECONDS} is specified,
* the milliseconds part will be displayed as fraction seconds
* (like {@code "15:30.00.25"}) with the minimum number of
* digits needed to show the milliseconds without precision lose.
* Thus, if the milliseconds happen to be exactly 0, no fraction
* seconds will be shown at all.
* @param timeZone the time zone in which the date/time will be shown. (You
* may find {@link DateUtil#UTC} handy here.) Note
* that although date-only formats has no time zone offset part,
* the result still depends on the time zone, as days start and end
* at different points on the time line in different zones.
* @param calendarFactory the factory that will create the calendar used
* internally for calculations. The point of this parameter is that
* creating a new calendar is relatively expensive, so it's desirable
* to reuse calendars and only set their time and zone. (This was
* tested on Sun JDK 1.6 x86 Win, where it gave 2x-3x speedup.)
*/
public static String dateToISO8601String(
Date date,
boolean datePart, boolean timePart, boolean offsetPart,
int accuracy,
TimeZone timeZone,
DateToISO8601CalendarFactory calendarFactory) {
return dateToString(date, datePart, timePart, offsetPart, accuracy, timeZone, false, calendarFactory);
}
/**
* Same as {@link #dateToISO8601String}, but gives XML Schema compliant format.
*/
public static String dateToXSString(
Date date,
boolean datePart, boolean timePart, boolean offsetPart,
int accuracy,
TimeZone timeZone,
DateToISO8601CalendarFactory calendarFactory) {
return dateToString(date, datePart, timePart, offsetPart, accuracy, timeZone, true, calendarFactory);
}
private static String dateToString(
Date date,
boolean datePart, boolean timePart, boolean offsetPart,
int accuracy,
TimeZone timeZone, boolean xsMode,
DateToISO8601CalendarFactory calendarFactory) {
if (!xsMode && !timePart && offsetPart) {
throw new IllegalArgumentException(
"ISO 8601:2004 doesn't specify any formats where the "
+ "offset is shown but the time isn't.");
}
if (timeZone == null) {
timeZone = UTC;
}
GregorianCalendar cal = calendarFactory.get(timeZone, date);
int maxLength;
if (!timePart) {
maxLength = 10 + (xsMode ? 6 : 0); // YYYY-MM-DD+00:00
} else {
if (!datePart) {
maxLength = 12 + 6; // HH:MM:SS.mmm+00:00
} else {
maxLength = 10 + 1 + 12 + 6;
}
}
char[] res = new char[maxLength];
int dstIdx = 0;
if (datePart) {
int x = cal.get(Calendar.YEAR);
if (x > 0 && cal.get(Calendar.ERA) == GregorianCalendar.BC) {
x = -x + (xsMode ? 0 : 1);
}
if (x >= 0 && x < 9999) {
res[dstIdx++] = (char) ('0' + x / 1000);
res[dstIdx++] = (char) ('0' + x % 1000 / 100);
res[dstIdx++] = (char) ('0' + x % 100 / 10);
res[dstIdx++] = (char) ('0' + x % 10);
} else {
String yearString = String.valueOf(x);
// Re-allocate buffer:
maxLength = maxLength - 4 + yearString.length();
res = new char[maxLength];
for (int i = 0; i < yearString.length(); i++) {
res[dstIdx++] = yearString.charAt(i);
}
}
res[dstIdx++] = '-';
x = cal.get(Calendar.MONTH) + 1;
dstIdx = append00(res, dstIdx, x);
res[dstIdx++] = '-';
x = cal.get(Calendar.DAY_OF_MONTH);
dstIdx = append00(res, dstIdx, x);
if (timePart) {
res[dstIdx++] = 'T';
}
}
if (timePart) {
int x = cal.get(Calendar.HOUR_OF_DAY);
dstIdx = append00(res, dstIdx, x);
if (accuracy >= ACCURACY_MINUTES) {
res[dstIdx++] = ':';
x = cal.get(Calendar.MINUTE);
dstIdx = append00(res, dstIdx, x);
if (accuracy >= ACCURACY_SECONDS) {
res[dstIdx++] = ':';
x = cal.get(Calendar.SECOND);
dstIdx = append00(res, dstIdx, x);
if (accuracy >= ACCURACY_MILLISECONDS) {
x = cal.get(Calendar.MILLISECOND);
int forcedDigits = accuracy == ACCURACY_MILLISECONDS_FORCED ? 3 : 0;
if (x != 0 || forcedDigits != 0) {
if (x > 999) {
// Shouldn't ever happen...
throw new RuntimeException(
"Calendar.MILLISECOND > 999");
}
res[dstIdx++] = '.';
do {
res[dstIdx++] = (char) ('0' + (x / 100));
forcedDigits--;
x = x % 100 * 10;
} while (x != 0 || forcedDigits > 0);
}
}
}
}
}
if (offsetPart) {
if (timeZone == UTC) {
res[dstIdx++] = 'Z';
} else {
int dt = timeZone.getOffset(date.getTime());
boolean positive;
if (dt < 0) {
positive = false;
dt = -dt;
} else {
positive = true;
}
dt /= 1000;
int offS = dt % 60;
dt /= 60;
int offM = dt % 60;
dt /= 60;
int offH = dt;
if (offS == 0 && offM == 0 && offH == 0) {
res[dstIdx++] = 'Z';
} else {
res[dstIdx++] = positive ? '+' : '-';
dstIdx = append00(res, dstIdx, offH);
res[dstIdx++] = ':';
dstIdx = append00(res, dstIdx, offM);
if (offS != 0) {
res[dstIdx++] = ':';
dstIdx = append00(res, dstIdx, offS);
}
}
}
}
return new String(res, 0, dstIdx);
}
/**
* Appends a number between 0 and 99 padded to 2 digits.
*/
private static int append00(char[] res, int dstIdx, int x) {
res[dstIdx++] = (char) ('0' + x / 10);
res[dstIdx++] = (char) ('0' + x % 10);
return dstIdx;
}
/**
* Parses an W3C XML Schema date string (not time or date-time).
* Unlike in ISO 8601:2000 Second Edition, year -1 means B.C 1, and year 0 is invalid.
*
* @param dateStr the string to parse.
* @param defaultTimeZone used if the date doesn't specify the
* time zone offset explicitly. Can't be {@code null}.
* @param calToDateConverter Used internally to calculate the result from the calendar field values.
* If you don't have a such object around, you can just use
* {@code new }{@link TrivialCalendarFieldsToDateConverter}{@code ()}.
*
* @throws DateParseException if the date is malformed, or if the time
* zone offset is unspecified and the {@code defaultTimeZone} is
* {@code null}.
*/
public static Date parseXSDate(
String dateStr, TimeZone defaultTimeZone,
CalendarFieldsToDateConverter calToDateConverter)
throws DateParseException {
Matcher m = PATTERN_XS_DATE.matcher(dateStr);
if (!m.matches()) {
throw new DateParseException("The value didn't match the expected pattern: " + PATTERN_XS_DATE);
}
return parseDate_parseMatcher(
m, defaultTimeZone, true, calToDateConverter);
}
/**
* Same as {@link #parseXSDate(String, TimeZone, CalendarFieldsToDateConverter)}, but for ISO 8601 dates.
*/
public static Date parseISO8601Date(
String dateStr, TimeZone defaultTimeZone,
CalendarFieldsToDateConverter calToDateConverter)
throws DateParseException {
Matcher m = PATTERN_ISO8601_EXTENDED_DATE.matcher(dateStr);
if (!m.matches()) {
m = PATTERN_ISO8601_BASIC_DATE.matcher(dateStr);
if (!m.matches()) {
throw new DateParseException("The value didn't match the expected pattern: "
+ PATTERN_ISO8601_EXTENDED_DATE + " or "
+ PATTERN_ISO8601_BASIC_DATE);
}
}
return parseDate_parseMatcher(
m, defaultTimeZone, false, calToDateConverter);
}
private static Date parseDate_parseMatcher(
Matcher m, TimeZone defaultTZ,
boolean xsMode,
CalendarFieldsToDateConverter calToDateConverter)
throws DateParseException {
NullArgumentException.check("defaultTZ", defaultTZ);
try {
int year = groupToInt(m.group(1), "year", Integer.MIN_VALUE, Integer.MAX_VALUE);
int era;
// Starting from ISO 8601:2000 Second Edition, 0001 is AD 1, 0000 is BC 1, -0001 is BC 2.
// However, according to http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/, XML schemas are based
// on the earlier version where 0000 didn't exist, and year -1 is BC 1.
if (year <= 0) {
era = GregorianCalendar.BC;
year = -year + (xsMode ? 0 : 1);
if (year == 0) {
throw new DateParseException(MSG_YEAR_0_NOT_ALLOWED);
}
} else {
era = GregorianCalendar.AD;
}
int month = groupToInt(m.group(2), "month", 1, 12) - 1;
int day = groupToInt(m.group(3), "day-of-month", 1, 31);
TimeZone tz = xsMode ? parseMatchingTimeZone(m.group(4), defaultTZ) : defaultTZ;
return calToDateConverter.calculate(era, year, month, day, 0, 0, 0, 0, false, tz);
} catch (IllegalArgumentException e) {
// Calendar methods used to throw this for illegal dates.
throw new DateParseException(
"Date calculation faliure. "
+ "Probably the date is formally correct, but refers "
+ "to an unexistent date (like February 30).");
}
}
/**
* Parses an W3C XML Schema time string (not date or date-time).
* If the time string doesn't specify the time zone offset explicitly,
* the value of the {@code defaultTZ} paramter will be used.
*/
public static Date parseXSTime(
String timeStr, TimeZone defaultTZ, CalendarFieldsToDateConverter calToDateConverter)
throws DateParseException {
Matcher m = PATTERN_XS_TIME.matcher(timeStr);
if (!m.matches()) {
throw new DateParseException("The value didn't match the expected pattern: " + PATTERN_XS_TIME);
}
return parseTime_parseMatcher(m, defaultTZ, calToDateConverter);
}
/**
* Same as {@link #parseXSTime(String, TimeZone, CalendarFieldsToDateConverter)} but for ISO 8601 times.
*/
public static Date parseISO8601Time(
String timeStr, TimeZone defaultTZ, CalendarFieldsToDateConverter calToDateConverter)
throws DateParseException {
Matcher m = PATTERN_ISO8601_EXTENDED_TIME.matcher(timeStr);
if (!m.matches()) {
m = PATTERN_ISO8601_BASIC_TIME.matcher(timeStr);
if (!m.matches()) {
throw new DateParseException("The value didn't match the expected pattern: "
+ PATTERN_ISO8601_EXTENDED_TIME + " or "
+ PATTERN_ISO8601_BASIC_TIME);
}
}
return parseTime_parseMatcher(m, defaultTZ, calToDateConverter);
}
private static Date parseTime_parseMatcher(
Matcher m, TimeZone defaultTZ,
CalendarFieldsToDateConverter calToDateConverter)
throws DateParseException {
NullArgumentException.check("defaultTZ", defaultTZ);
try {
// ISO 8601 allows both 00:00 and 24:00,
// but Calendar.set(...) doesn't if the Calendar is not lenient.
int hours = groupToInt(m.group(1), "hour-of-day", 0, 24);
boolean hourWas24;
if (hours == 24) {
hours = 0;
hourWas24 = true;
// And a day will be added later...
} else {
hourWas24 = false;
}
final String minutesStr = m.group(2);
int minutes = minutesStr != null ? groupToInt(minutesStr, "minute", 0, 59) : 0;
final String secsStr = m.group(3);
// Allow 60 because of leap seconds
int secs = secsStr != null ? groupToInt(secsStr, "second", 0, 60) : 0;
int millisecs = groupToMillisecond(m.group(4));
// As a time is just the distance from the beginning of the day,
// the time-zone offest should be 0 usually.
TimeZone tz = parseMatchingTimeZone(m.group(5), defaultTZ);
// Continue handling the 24:00 special case
int day;
if (hourWas24) {
if (minutes == 0 && secs == 0 && millisecs == 0) {
day = 2;
} else {
throw new DateParseException(
"Hour 24 is only allowed in the case of "
+ "midnight.");
}
} else {
day = 1;
}
return calToDateConverter.calculate(
GregorianCalendar.AD, 1970, 0, day, hours, minutes, secs, millisecs, false, tz);
} catch (IllegalArgumentException e) {
// Calendar methods used to throw this for illegal dates.
throw new DateParseException(
"Unexpected time calculation faliure.");
}
}
/**
* Parses an W3C XML Schema date-time string (not date or time).
* Unlike in ISO 8601:2000 Second Edition, year -1 means B.C 1, and year 0 is invalid.
*
* @param dateTimeStr the string to parse.
* @param defaultTZ used if the dateTime doesn't specify the
* time zone offset explicitly. Can't be {@code null}.
*
* @throws DateParseException if the dateTime is malformed.
*/
public static Date parseXSDateTime(
String dateTimeStr, TimeZone defaultTZ, CalendarFieldsToDateConverter calToDateConverter)
throws DateParseException {
Matcher m = PATTERN_XS_DATE_TIME.matcher(dateTimeStr);
if (!m.matches()) {
throw new DateParseException(
"The value didn't match the expected pattern: " + PATTERN_XS_DATE_TIME);
}
return parseDateTime_parseMatcher(
m, defaultTZ, true, calToDateConverter);
}
/**
* Same as {@link #parseXSDateTime(String, TimeZone, CalendarFieldsToDateConverter)} but for ISO 8601 format.
*/
public static Date parseISO8601DateTime(
String dateTimeStr, TimeZone defaultTZ, CalendarFieldsToDateConverter calToDateConverter)
throws DateParseException {
Matcher m = PATTERN_ISO8601_EXTENDED_DATE_TIME.matcher(dateTimeStr);
if (!m.matches()) {
m = PATTERN_ISO8601_BASIC_DATE_TIME.matcher(dateTimeStr);
if (!m.matches()) {
throw new DateParseException("The value (" + dateTimeStr + ") didn't match the expected pattern: "
+ PATTERN_ISO8601_EXTENDED_DATE_TIME + " or "
+ PATTERN_ISO8601_BASIC_DATE_TIME);
}
}
return parseDateTime_parseMatcher(
m, defaultTZ, false, calToDateConverter);
}
private static Date parseDateTime_parseMatcher(
Matcher m, TimeZone defaultTZ,
boolean xsMode,
CalendarFieldsToDateConverter calToDateConverter)
throws DateParseException {
NullArgumentException.check("defaultTZ", defaultTZ);
try {
int year = groupToInt(m.group(1), "year", Integer.MIN_VALUE, Integer.MAX_VALUE);
int era;
// Starting from ISO 8601:2000 Second Edition, 0001 is AD 1, 0000 is BC 1, -0001 is BC 2.
// However, according to http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/, XML schemas are based
// on the earlier version where 0000 didn't exist, and year -1 is BC 1.
if (year <= 0) {
era = GregorianCalendar.BC;
year = -year + (xsMode ? 0 : 1);
if (year == 0) {
throw new DateParseException(MSG_YEAR_0_NOT_ALLOWED);
}
} else {
era = GregorianCalendar.AD;
}
int month = groupToInt(m.group(2), "month", 1, 12) - 1;
int day = groupToInt(m.group(3), "day-of-month", 1, 31);
// ISO 8601 allows both 00:00 and 24:00,
// but cal.set(...) doesn't if the Calendar is not lenient.
int hours = groupToInt(m.group(4), "hour-of-day", 0, 24);
boolean hourWas24;
if (hours == 24) {
hours = 0;
hourWas24 = true;
// And a day will be added later...
} else {
hourWas24 = false;
}
final String minutesStr = m.group(5);
int minutes = minutesStr != null ? groupToInt(minutesStr, "minute", 0, 59) : 0;
final String secsStr = m.group(6);
// Allow 60 because of leap seconds
int secs = secsStr != null ? groupToInt(secsStr, "second", 0, 60) : 0;
int millisecs = groupToMillisecond(m.group(7));
// As a time is just the distance from the beginning of the day,
// the time-zone offest should be 0 usually.
TimeZone tz = parseMatchingTimeZone(m.group(8), defaultTZ);
// Continue handling the 24:00 specail case
if (hourWas24) {
if (minutes != 0 || secs != 0 || millisecs != 0) {
throw new DateParseException(
"Hour 24 is only allowed in the case of "
+ "midnight.");
}
}
return calToDateConverter.calculate(
era, year, month, day, hours, minutes, secs, millisecs, hourWas24, tz);
} catch (IllegalArgumentException e) {
// Calendar methods used to throw this for illegal dates.
throw new DateParseException(
"Date-time calculation faliure. "
+ "Probably the date-time is formally correct, but "
+ "refers to an unexistent date-time "
+ "(like February 30).");
}
}
/**
* Parses the time zone part from a W3C XML Schema date/time/dateTime.
* @throws DateParseException if the zone is malformed.
*/
public static TimeZone parseXSTimeZone(String timeZoneStr)
throws DateParseException {
Matcher m = PATTERN_XS_TIME_ZONE.matcher(timeZoneStr);
if (!m.matches()) {
throw new DateParseException(
"The time zone offset didn't match the expected pattern: " + PATTERN_XS_TIME_ZONE);
}
return parseMatchingTimeZone(timeZoneStr, null);
}
private static int groupToInt(String g, String gName,
int min, int max)
throws DateParseException {
if (g == null) {
throw new DateParseException("The " + gName + " part "
+ "is missing.");
}
int start;
// Remove minus sign, so we can remove the 0-s later:
boolean negative;
if (g.startsWith("-")) {
negative = true;
start = 1;
} else {
negative = false;
start = 0;
}
// Remove leading 0-s:
while (start < g.length() - 1 && g.charAt(start) == '0') {
start++;
}
if (start != 0) {
g = g.substring(start);
}
try {
int r = Integer.parseInt(g);
if (negative) {
r = -r;
}
if (r < min) {
throw new DateParseException("The " + gName + " part "
+ "must be at least " + min + ".");
}
if (r > max) {
throw new DateParseException("The " + gName + " part "
+ "can't be more than " + max + ".");
}
return r;
} catch (NumberFormatException e) {
throw new DateParseException("The " + gName + " part "
+ "is a malformed integer.");
}
}
private static TimeZone parseMatchingTimeZone(
String s, TimeZone defaultZone)
throws DateParseException {
if (s == null) {
return defaultZone;
}
if (s.equals("Z")) {
return DateUtil.UTC;
}
StringBuilder sb = new StringBuilder(9);
sb.append("GMT");
sb.append(s.charAt(0));
String h = s.substring(1, 3);
groupToInt(h, "offset-hours", 0, 23);
sb.append(h);
String m;
int ln = s.length();
if (ln > 3) {
int startIdx = s.charAt(3) == ':' ? 4 : 3;
m = s.substring(startIdx, startIdx + 2);
groupToInt(m, "offset-minutes", 0, 59);
sb.append(':');
sb.append(m);
}
return TimeZone.getTimeZone(sb.toString());
}
private static int groupToMillisecond(String g)
throws DateParseException {
if (g == null) {
return 0;
}
if (g.length() > 3) {
g = g.substring(0, 3);
}
int i = groupToInt(g, "partial-seconds", 0, Integer.MAX_VALUE);
return g.length() == 1 ? i * 100 : (g.length() == 2 ? i * 10 : i);
}
/**
* Used internally by {@link DateUtil}; don't use its implementations for
* anything else.
*/
public interface DateToISO8601CalendarFactory {
/**
* Returns a {@link GregorianCalendar} with the desired time zone and
* time and US locale. The returned calendar is used as read-only.
* It must be guaranteed that within a thread the instance returned last time
* is not in use anymore when this method is called again.
*/
GregorianCalendar get(TimeZone tz, Date date);
}
/**
* Used internally by {@link DateUtil}; don't use its implementations for anything else.
*/
public interface CalendarFieldsToDateConverter {
/**
* Calculates the {@link Date} from the specified calendar fields.
*/
Date calculate(int era, int year, int month, int day, int hours, int minutes, int secs, int millisecs,
boolean addOneDay,
TimeZone tz);
}
/**
* Non-thread-safe factory that hard-references a calendar internally.
*/
public static final class TrivialDateToISO8601CalendarFactory
implements DateToISO8601CalendarFactory {
private GregorianCalendar calendar;
private TimeZone lastlySetTimeZone;
@Override
public GregorianCalendar get(TimeZone tz, Date date) {
if (calendar == null) {
calendar = new GregorianCalendar(tz, Locale.US);
calendar.setGregorianChange(new Date(Long.MIN_VALUE)); // never use Julian calendar
} else {
// At least on Java 6, calendar.getTimeZone is slow due to a bug, so we need lastlySetTimeZone.
if (lastlySetTimeZone != tz) { // Deliberately `!=` instead of `!<...>.equals()`
calendar.setTimeZone(tz);
lastlySetTimeZone = tz;
}
}
calendar.setTime(date);
return calendar;
}
}
/**
* Non-thread-safe implementation that hard-references a calendar internally.
*/
public static final class TrivialCalendarFieldsToDateConverter
implements CalendarFieldsToDateConverter {
private GregorianCalendar calendar;
private TimeZone lastlySetTimeZone;
@Override
public Date calculate(int era, int year, int month, int day, int hours, int minutes, int secs, int millisecs,
boolean addOneDay, TimeZone tz) {
if (calendar == null) {
calendar = new GregorianCalendar(tz, Locale.US);
calendar.setLenient(false);
calendar.setGregorianChange(new Date(Long.MIN_VALUE)); // never use Julian calendar
} else {
// At least on Java 6, calendar.getTimeZone is slow due to a bug, so we need lastlySetTimeZone.
if (lastlySetTimeZone != tz) { // Deliberately `!=` instead of `!<...>.equals()`
calendar.setTimeZone(tz);
lastlySetTimeZone = tz;
}
}
calendar.set(Calendar.ERA, era);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.HOUR_OF_DAY, hours);
calendar.set(Calendar.MINUTE, minutes);
calendar.set(Calendar.SECOND, secs);
calendar.set(Calendar.MILLISECOND, millisecs);
if (addOneDay) {
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
return calendar.getTime();
}
}
public static final class DateParseException extends ParseException {
public DateParseException(String message) {
super(message, 0);
}
}
}
|
googleapis/google-cloud-java | 36,481 | java-websecurityscanner/proto-google-cloud-websecurityscanner-v1/src/main/java/com/google/cloud/websecurityscanner/v1/ListScanRunsResponse.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/websecurityscanner/v1/web_security_scanner.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.websecurityscanner.v1;
/**
*
*
* <pre>
* Response for the `ListScanRuns` method.
* </pre>
*
* Protobuf type {@code google.cloud.websecurityscanner.v1.ListScanRunsResponse}
*/
public final class ListScanRunsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.websecurityscanner.v1.ListScanRunsResponse)
ListScanRunsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListScanRunsResponse.newBuilder() to construct.
private ListScanRunsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListScanRunsResponse() {
scanRuns_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListScanRunsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.websecurityscanner.v1.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1_ListScanRunsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.websecurityscanner.v1.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1_ListScanRunsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.websecurityscanner.v1.ListScanRunsResponse.class,
com.google.cloud.websecurityscanner.v1.ListScanRunsResponse.Builder.class);
}
public static final int SCAN_RUNS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.websecurityscanner.v1.ScanRun> scanRuns_;
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.websecurityscanner.v1.ScanRun> getScanRunsList() {
return scanRuns_;
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.websecurityscanner.v1.ScanRunOrBuilder>
getScanRunsOrBuilderList() {
return scanRuns_;
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
@java.lang.Override
public int getScanRunsCount() {
return scanRuns_.size();
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
@java.lang.Override
public com.google.cloud.websecurityscanner.v1.ScanRun getScanRuns(int index) {
return scanRuns_.get(index);
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
@java.lang.Override
public com.google.cloud.websecurityscanner.v1.ScanRunOrBuilder getScanRunsOrBuilder(int index) {
return scanRuns_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < scanRuns_.size(); i++) {
output.writeMessage(1, scanRuns_.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 < scanRuns_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, scanRuns_.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.websecurityscanner.v1.ListScanRunsResponse)) {
return super.equals(obj);
}
com.google.cloud.websecurityscanner.v1.ListScanRunsResponse other =
(com.google.cloud.websecurityscanner.v1.ListScanRunsResponse) obj;
if (!getScanRunsList().equals(other.getScanRunsList())) 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 (getScanRunsCount() > 0) {
hash = (37 * hash) + SCAN_RUNS_FIELD_NUMBER;
hash = (53 * hash) + getScanRunsList().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.websecurityscanner.v1.ListScanRunsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.websecurityscanner.v1.ListScanRunsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1.ListScanRunsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.websecurityscanner.v1.ListScanRunsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1.ListScanRunsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.websecurityscanner.v1.ListScanRunsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1.ListScanRunsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.websecurityscanner.v1.ListScanRunsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1.ListScanRunsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.websecurityscanner.v1.ListScanRunsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1.ListScanRunsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.websecurityscanner.v1.ListScanRunsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.websecurityscanner.v1.ListScanRunsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response for the `ListScanRuns` method.
* </pre>
*
* Protobuf type {@code google.cloud.websecurityscanner.v1.ListScanRunsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.websecurityscanner.v1.ListScanRunsResponse)
com.google.cloud.websecurityscanner.v1.ListScanRunsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.websecurityscanner.v1.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1_ListScanRunsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.websecurityscanner.v1.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1_ListScanRunsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.websecurityscanner.v1.ListScanRunsResponse.class,
com.google.cloud.websecurityscanner.v1.ListScanRunsResponse.Builder.class);
}
// Construct using com.google.cloud.websecurityscanner.v1.ListScanRunsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (scanRunsBuilder_ == null) {
scanRuns_ = java.util.Collections.emptyList();
} else {
scanRuns_ = null;
scanRunsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.websecurityscanner.v1.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1_ListScanRunsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1.ListScanRunsResponse getDefaultInstanceForType() {
return com.google.cloud.websecurityscanner.v1.ListScanRunsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1.ListScanRunsResponse build() {
com.google.cloud.websecurityscanner.v1.ListScanRunsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1.ListScanRunsResponse buildPartial() {
com.google.cloud.websecurityscanner.v1.ListScanRunsResponse result =
new com.google.cloud.websecurityscanner.v1.ListScanRunsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.websecurityscanner.v1.ListScanRunsResponse result) {
if (scanRunsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
scanRuns_ = java.util.Collections.unmodifiableList(scanRuns_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.scanRuns_ = scanRuns_;
} else {
result.scanRuns_ = scanRunsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.websecurityscanner.v1.ListScanRunsResponse 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.websecurityscanner.v1.ListScanRunsResponse) {
return mergeFrom((com.google.cloud.websecurityscanner.v1.ListScanRunsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.websecurityscanner.v1.ListScanRunsResponse other) {
if (other == com.google.cloud.websecurityscanner.v1.ListScanRunsResponse.getDefaultInstance())
return this;
if (scanRunsBuilder_ == null) {
if (!other.scanRuns_.isEmpty()) {
if (scanRuns_.isEmpty()) {
scanRuns_ = other.scanRuns_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureScanRunsIsMutable();
scanRuns_.addAll(other.scanRuns_);
}
onChanged();
}
} else {
if (!other.scanRuns_.isEmpty()) {
if (scanRunsBuilder_.isEmpty()) {
scanRunsBuilder_.dispose();
scanRunsBuilder_ = null;
scanRuns_ = other.scanRuns_;
bitField0_ = (bitField0_ & ~0x00000001);
scanRunsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getScanRunsFieldBuilder()
: null;
} else {
scanRunsBuilder_.addAllMessages(other.scanRuns_);
}
}
}
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.websecurityscanner.v1.ScanRun m =
input.readMessage(
com.google.cloud.websecurityscanner.v1.ScanRun.parser(), extensionRegistry);
if (scanRunsBuilder_ == null) {
ensureScanRunsIsMutable();
scanRuns_.add(m);
} else {
scanRunsBuilder_.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.websecurityscanner.v1.ScanRun> scanRuns_ =
java.util.Collections.emptyList();
private void ensureScanRunsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
scanRuns_ =
new java.util.ArrayList<com.google.cloud.websecurityscanner.v1.ScanRun>(scanRuns_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.websecurityscanner.v1.ScanRun,
com.google.cloud.websecurityscanner.v1.ScanRun.Builder,
com.google.cloud.websecurityscanner.v1.ScanRunOrBuilder>
scanRunsBuilder_;
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public java.util.List<com.google.cloud.websecurityscanner.v1.ScanRun> getScanRunsList() {
if (scanRunsBuilder_ == null) {
return java.util.Collections.unmodifiableList(scanRuns_);
} else {
return scanRunsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public int getScanRunsCount() {
if (scanRunsBuilder_ == null) {
return scanRuns_.size();
} else {
return scanRunsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1.ScanRun getScanRuns(int index) {
if (scanRunsBuilder_ == null) {
return scanRuns_.get(index);
} else {
return scanRunsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public Builder setScanRuns(int index, com.google.cloud.websecurityscanner.v1.ScanRun value) {
if (scanRunsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureScanRunsIsMutable();
scanRuns_.set(index, value);
onChanged();
} else {
scanRunsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public Builder setScanRuns(
int index, com.google.cloud.websecurityscanner.v1.ScanRun.Builder builderForValue) {
if (scanRunsBuilder_ == null) {
ensureScanRunsIsMutable();
scanRuns_.set(index, builderForValue.build());
onChanged();
} else {
scanRunsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public Builder addScanRuns(com.google.cloud.websecurityscanner.v1.ScanRun value) {
if (scanRunsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureScanRunsIsMutable();
scanRuns_.add(value);
onChanged();
} else {
scanRunsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public Builder addScanRuns(int index, com.google.cloud.websecurityscanner.v1.ScanRun value) {
if (scanRunsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureScanRunsIsMutable();
scanRuns_.add(index, value);
onChanged();
} else {
scanRunsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public Builder addScanRuns(
com.google.cloud.websecurityscanner.v1.ScanRun.Builder builderForValue) {
if (scanRunsBuilder_ == null) {
ensureScanRunsIsMutable();
scanRuns_.add(builderForValue.build());
onChanged();
} else {
scanRunsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public Builder addScanRuns(
int index, com.google.cloud.websecurityscanner.v1.ScanRun.Builder builderForValue) {
if (scanRunsBuilder_ == null) {
ensureScanRunsIsMutable();
scanRuns_.add(index, builderForValue.build());
onChanged();
} else {
scanRunsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public Builder addAllScanRuns(
java.lang.Iterable<? extends com.google.cloud.websecurityscanner.v1.ScanRun> values) {
if (scanRunsBuilder_ == null) {
ensureScanRunsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, scanRuns_);
onChanged();
} else {
scanRunsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public Builder clearScanRuns() {
if (scanRunsBuilder_ == null) {
scanRuns_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
scanRunsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public Builder removeScanRuns(int index) {
if (scanRunsBuilder_ == null) {
ensureScanRunsIsMutable();
scanRuns_.remove(index);
onChanged();
} else {
scanRunsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1.ScanRun.Builder getScanRunsBuilder(int index) {
return getScanRunsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1.ScanRunOrBuilder getScanRunsOrBuilder(int index) {
if (scanRunsBuilder_ == null) {
return scanRuns_.get(index);
} else {
return scanRunsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public java.util.List<? extends com.google.cloud.websecurityscanner.v1.ScanRunOrBuilder>
getScanRunsOrBuilderList() {
if (scanRunsBuilder_ != null) {
return scanRunsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(scanRuns_);
}
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1.ScanRun.Builder addScanRunsBuilder() {
return getScanRunsFieldBuilder()
.addBuilder(com.google.cloud.websecurityscanner.v1.ScanRun.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1.ScanRun.Builder addScanRunsBuilder(int index) {
return getScanRunsFieldBuilder()
.addBuilder(index, com.google.cloud.websecurityscanner.v1.ScanRun.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of ScanRuns returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1.ScanRun scan_runs = 1;</code>
*/
public java.util.List<com.google.cloud.websecurityscanner.v1.ScanRun.Builder>
getScanRunsBuilderList() {
return getScanRunsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.websecurityscanner.v1.ScanRun,
com.google.cloud.websecurityscanner.v1.ScanRun.Builder,
com.google.cloud.websecurityscanner.v1.ScanRunOrBuilder>
getScanRunsFieldBuilder() {
if (scanRunsBuilder_ == null) {
scanRunsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.websecurityscanner.v1.ScanRun,
com.google.cloud.websecurityscanner.v1.ScanRun.Builder,
com.google.cloud.websecurityscanner.v1.ScanRunOrBuilder>(
scanRuns_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
scanRuns_ = null;
}
return scanRunsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.websecurityscanner.v1.ListScanRunsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.websecurityscanner.v1.ListScanRunsResponse)
private static final com.google.cloud.websecurityscanner.v1.ListScanRunsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.websecurityscanner.v1.ListScanRunsResponse();
}
public static com.google.cloud.websecurityscanner.v1.ListScanRunsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListScanRunsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListScanRunsResponse>() {
@java.lang.Override
public ListScanRunsResponse 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<ListScanRunsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListScanRunsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1.ListScanRunsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,496 | java-video-stitcher/proto-google-cloud-video-stitcher-v1/src/main/java/com/google/cloud/video/stitcher/v1/VodAdTagDetail.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/video/stitcher/v1/ad_tag_details.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.video.stitcher.v1;
/**
*
*
* <pre>
* Information related to the details for one ad tag. This resource is only
* available for VOD sessions that do not implement Google Ad Manager ad
* insertion.
* </pre>
*
* Protobuf type {@code google.cloud.video.stitcher.v1.VodAdTagDetail}
*/
public final class VodAdTagDetail extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.video.stitcher.v1.VodAdTagDetail)
VodAdTagDetailOrBuilder {
private static final long serialVersionUID = 0L;
// Use VodAdTagDetail.newBuilder() to construct.
private VodAdTagDetail(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private VodAdTagDetail() {
name_ = "";
adRequests_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new VodAdTagDetail();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.video.stitcher.v1.AdTagDetailsProto
.internal_static_google_cloud_video_stitcher_v1_VodAdTagDetail_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.video.stitcher.v1.AdTagDetailsProto
.internal_static_google_cloud_video_stitcher_v1_VodAdTagDetail_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.video.stitcher.v1.VodAdTagDetail.class,
com.google.cloud.video.stitcher.v1.VodAdTagDetail.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object name_ = "";
/**
*
*
* <pre>
* The name of the ad tag detail for the specified VOD session, in the form of
* `projects/{project}/locations/{location}/vodSessions/{vod_session_id}/vodAdTagDetails/{id}`.
* </pre>
*
* <code>string name = 1;</code>
*
* @return The name.
*/
@java.lang.Override
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
*
*
* <pre>
* The name of the ad tag detail for the specified VOD session, in the form of
* `projects/{project}/locations/{location}/vodSessions/{vod_session_id}/vodAdTagDetails/{id}`.
* </pre>
*
* <code>string name = 1;</code>
*
* @return The bytes for name.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int AD_REQUESTS_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.video.stitcher.v1.AdRequest> adRequests_;
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.video.stitcher.v1.AdRequest> getAdRequestsList() {
return adRequests_;
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.video.stitcher.v1.AdRequestOrBuilder>
getAdRequestsOrBuilderList() {
return adRequests_;
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
@java.lang.Override
public int getAdRequestsCount() {
return adRequests_.size();
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
@java.lang.Override
public com.google.cloud.video.stitcher.v1.AdRequest getAdRequests(int index) {
return adRequests_.get(index);
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
@java.lang.Override
public com.google.cloud.video.stitcher.v1.AdRequestOrBuilder getAdRequestsOrBuilder(int index) {
return adRequests_.get(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
for (int i = 0; i < adRequests_.size(); i++) {
output.writeMessage(2, adRequests_.get(i));
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
for (int i = 0; i < adRequests_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, adRequests_.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.video.stitcher.v1.VodAdTagDetail)) {
return super.equals(obj);
}
com.google.cloud.video.stitcher.v1.VodAdTagDetail other =
(com.google.cloud.video.stitcher.v1.VodAdTagDetail) obj;
if (!getName().equals(other.getName())) return false;
if (!getAdRequestsList().equals(other.getAdRequestsList())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
if (getAdRequestsCount() > 0) {
hash = (37 * hash) + AD_REQUESTS_FIELD_NUMBER;
hash = (53 * hash) + getAdRequestsList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.video.stitcher.v1.VodAdTagDetail parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.video.stitcher.v1.VodAdTagDetail 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.video.stitcher.v1.VodAdTagDetail parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.video.stitcher.v1.VodAdTagDetail 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.video.stitcher.v1.VodAdTagDetail parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.video.stitcher.v1.VodAdTagDetail parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.video.stitcher.v1.VodAdTagDetail parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.video.stitcher.v1.VodAdTagDetail 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.video.stitcher.v1.VodAdTagDetail parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.video.stitcher.v1.VodAdTagDetail 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.video.stitcher.v1.VodAdTagDetail parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.video.stitcher.v1.VodAdTagDetail 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.video.stitcher.v1.VodAdTagDetail 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>
* Information related to the details for one ad tag. This resource is only
* available for VOD sessions that do not implement Google Ad Manager ad
* insertion.
* </pre>
*
* Protobuf type {@code google.cloud.video.stitcher.v1.VodAdTagDetail}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.video.stitcher.v1.VodAdTagDetail)
com.google.cloud.video.stitcher.v1.VodAdTagDetailOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.video.stitcher.v1.AdTagDetailsProto
.internal_static_google_cloud_video_stitcher_v1_VodAdTagDetail_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.video.stitcher.v1.AdTagDetailsProto
.internal_static_google_cloud_video_stitcher_v1_VodAdTagDetail_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.video.stitcher.v1.VodAdTagDetail.class,
com.google.cloud.video.stitcher.v1.VodAdTagDetail.Builder.class);
}
// Construct using com.google.cloud.video.stitcher.v1.VodAdTagDetail.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
name_ = "";
if (adRequestsBuilder_ == null) {
adRequests_ = java.util.Collections.emptyList();
} else {
adRequests_ = null;
adRequestsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.video.stitcher.v1.AdTagDetailsProto
.internal_static_google_cloud_video_stitcher_v1_VodAdTagDetail_descriptor;
}
@java.lang.Override
public com.google.cloud.video.stitcher.v1.VodAdTagDetail getDefaultInstanceForType() {
return com.google.cloud.video.stitcher.v1.VodAdTagDetail.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.video.stitcher.v1.VodAdTagDetail build() {
com.google.cloud.video.stitcher.v1.VodAdTagDetail result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.video.stitcher.v1.VodAdTagDetail buildPartial() {
com.google.cloud.video.stitcher.v1.VodAdTagDetail result =
new com.google.cloud.video.stitcher.v1.VodAdTagDetail(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.video.stitcher.v1.VodAdTagDetail result) {
if (adRequestsBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)) {
adRequests_ = java.util.Collections.unmodifiableList(adRequests_);
bitField0_ = (bitField0_ & ~0x00000002);
}
result.adRequests_ = adRequests_;
} else {
result.adRequests_ = adRequestsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.video.stitcher.v1.VodAdTagDetail result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.name_ = name_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.video.stitcher.v1.VodAdTagDetail) {
return mergeFrom((com.google.cloud.video.stitcher.v1.VodAdTagDetail) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.video.stitcher.v1.VodAdTagDetail other) {
if (other == com.google.cloud.video.stitcher.v1.VodAdTagDetail.getDefaultInstance())
return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
bitField0_ |= 0x00000001;
onChanged();
}
if (adRequestsBuilder_ == null) {
if (!other.adRequests_.isEmpty()) {
if (adRequests_.isEmpty()) {
adRequests_ = other.adRequests_;
bitField0_ = (bitField0_ & ~0x00000002);
} else {
ensureAdRequestsIsMutable();
adRequests_.addAll(other.adRequests_);
}
onChanged();
}
} else {
if (!other.adRequests_.isEmpty()) {
if (adRequestsBuilder_.isEmpty()) {
adRequestsBuilder_.dispose();
adRequestsBuilder_ = null;
adRequests_ = other.adRequests_;
bitField0_ = (bitField0_ & ~0x00000002);
adRequestsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getAdRequestsFieldBuilder()
: null;
} else {
adRequestsBuilder_.addAllMessages(other.adRequests_);
}
}
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
name_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
com.google.cloud.video.stitcher.v1.AdRequest m =
input.readMessage(
com.google.cloud.video.stitcher.v1.AdRequest.parser(), extensionRegistry);
if (adRequestsBuilder_ == null) {
ensureAdRequestsIsMutable();
adRequests_.add(m);
} else {
adRequestsBuilder_.addMessage(m);
}
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object name_ = "";
/**
*
*
* <pre>
* The name of the ad tag detail for the specified VOD session, in the form of
* `projects/{project}/locations/{location}/vodSessions/{vod_session_id}/vodAdTagDetails/{id}`.
* </pre>
*
* <code>string name = 1;</code>
*
* @return The name.
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The name of the ad tag detail for the specified VOD session, in the form of
* `projects/{project}/locations/{location}/vodSessions/{vod_session_id}/vodAdTagDetails/{id}`.
* </pre>
*
* <code>string name = 1;</code>
*
* @return The bytes for name.
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The name of the ad tag detail for the specified VOD session, in the form of
* `projects/{project}/locations/{location}/vodSessions/{vod_session_id}/vodAdTagDetails/{id}`.
* </pre>
*
* <code>string name = 1;</code>
*
* @param value The name to set.
* @return This builder for chaining.
*/
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the ad tag detail for the specified VOD session, in the form of
* `projects/{project}/locations/{location}/vodSessions/{vod_session_id}/vodAdTagDetails/{id}`.
* </pre>
*
* <code>string name = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the ad tag detail for the specified VOD session, in the form of
* `projects/{project}/locations/{location}/vodSessions/{vod_session_id}/vodAdTagDetails/{id}`.
* </pre>
*
* <code>string name = 1;</code>
*
* @param value The bytes for name to set.
* @return This builder for chaining.
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.util.List<com.google.cloud.video.stitcher.v1.AdRequest> adRequests_ =
java.util.Collections.emptyList();
private void ensureAdRequestsIsMutable() {
if (!((bitField0_ & 0x00000002) != 0)) {
adRequests_ =
new java.util.ArrayList<com.google.cloud.video.stitcher.v1.AdRequest>(adRequests_);
bitField0_ |= 0x00000002;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.video.stitcher.v1.AdRequest,
com.google.cloud.video.stitcher.v1.AdRequest.Builder,
com.google.cloud.video.stitcher.v1.AdRequestOrBuilder>
adRequestsBuilder_;
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public java.util.List<com.google.cloud.video.stitcher.v1.AdRequest> getAdRequestsList() {
if (adRequestsBuilder_ == null) {
return java.util.Collections.unmodifiableList(adRequests_);
} else {
return adRequestsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public int getAdRequestsCount() {
if (adRequestsBuilder_ == null) {
return adRequests_.size();
} else {
return adRequestsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public com.google.cloud.video.stitcher.v1.AdRequest getAdRequests(int index) {
if (adRequestsBuilder_ == null) {
return adRequests_.get(index);
} else {
return adRequestsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public Builder setAdRequests(int index, com.google.cloud.video.stitcher.v1.AdRequest value) {
if (adRequestsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAdRequestsIsMutable();
adRequests_.set(index, value);
onChanged();
} else {
adRequestsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public Builder setAdRequests(
int index, com.google.cloud.video.stitcher.v1.AdRequest.Builder builderForValue) {
if (adRequestsBuilder_ == null) {
ensureAdRequestsIsMutable();
adRequests_.set(index, builderForValue.build());
onChanged();
} else {
adRequestsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public Builder addAdRequests(com.google.cloud.video.stitcher.v1.AdRequest value) {
if (adRequestsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAdRequestsIsMutable();
adRequests_.add(value);
onChanged();
} else {
adRequestsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public Builder addAdRequests(int index, com.google.cloud.video.stitcher.v1.AdRequest value) {
if (adRequestsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAdRequestsIsMutable();
adRequests_.add(index, value);
onChanged();
} else {
adRequestsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public Builder addAdRequests(
com.google.cloud.video.stitcher.v1.AdRequest.Builder builderForValue) {
if (adRequestsBuilder_ == null) {
ensureAdRequestsIsMutable();
adRequests_.add(builderForValue.build());
onChanged();
} else {
adRequestsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public Builder addAdRequests(
int index, com.google.cloud.video.stitcher.v1.AdRequest.Builder builderForValue) {
if (adRequestsBuilder_ == null) {
ensureAdRequestsIsMutable();
adRequests_.add(index, builderForValue.build());
onChanged();
} else {
adRequestsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public Builder addAllAdRequests(
java.lang.Iterable<? extends com.google.cloud.video.stitcher.v1.AdRequest> values) {
if (adRequestsBuilder_ == null) {
ensureAdRequestsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, adRequests_);
onChanged();
} else {
adRequestsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public Builder clearAdRequests() {
if (adRequestsBuilder_ == null) {
adRequests_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
} else {
adRequestsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public Builder removeAdRequests(int index) {
if (adRequestsBuilder_ == null) {
ensureAdRequestsIsMutable();
adRequests_.remove(index);
onChanged();
} else {
adRequestsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public com.google.cloud.video.stitcher.v1.AdRequest.Builder getAdRequestsBuilder(int index) {
return getAdRequestsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public com.google.cloud.video.stitcher.v1.AdRequestOrBuilder getAdRequestsOrBuilder(int index) {
if (adRequestsBuilder_ == null) {
return adRequests_.get(index);
} else {
return adRequestsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public java.util.List<? extends com.google.cloud.video.stitcher.v1.AdRequestOrBuilder>
getAdRequestsOrBuilderList() {
if (adRequestsBuilder_ != null) {
return adRequestsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(adRequests_);
}
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public com.google.cloud.video.stitcher.v1.AdRequest.Builder addAdRequestsBuilder() {
return getAdRequestsFieldBuilder()
.addBuilder(com.google.cloud.video.stitcher.v1.AdRequest.getDefaultInstance());
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public com.google.cloud.video.stitcher.v1.AdRequest.Builder addAdRequestsBuilder(int index) {
return getAdRequestsFieldBuilder()
.addBuilder(index, com.google.cloud.video.stitcher.v1.AdRequest.getDefaultInstance());
}
/**
*
*
* <pre>
* A list of ad requests for one ad tag.
* </pre>
*
* <code>repeated .google.cloud.video.stitcher.v1.AdRequest ad_requests = 2;</code>
*/
public java.util.List<com.google.cloud.video.stitcher.v1.AdRequest.Builder>
getAdRequestsBuilderList() {
return getAdRequestsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.video.stitcher.v1.AdRequest,
com.google.cloud.video.stitcher.v1.AdRequest.Builder,
com.google.cloud.video.stitcher.v1.AdRequestOrBuilder>
getAdRequestsFieldBuilder() {
if (adRequestsBuilder_ == null) {
adRequestsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.video.stitcher.v1.AdRequest,
com.google.cloud.video.stitcher.v1.AdRequest.Builder,
com.google.cloud.video.stitcher.v1.AdRequestOrBuilder>(
adRequests_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean());
adRequests_ = null;
}
return adRequestsBuilder_;
}
@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.video.stitcher.v1.VodAdTagDetail)
}
// @@protoc_insertion_point(class_scope:google.cloud.video.stitcher.v1.VodAdTagDetail)
private static final com.google.cloud.video.stitcher.v1.VodAdTagDetail DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.video.stitcher.v1.VodAdTagDetail();
}
public static com.google.cloud.video.stitcher.v1.VodAdTagDetail getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<VodAdTagDetail> PARSER =
new com.google.protobuf.AbstractParser<VodAdTagDetail>() {
@java.lang.Override
public VodAdTagDetail 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<VodAdTagDetail> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<VodAdTagDetail> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.video.stitcher.v1.VodAdTagDetail getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/iceberg | 36,519 | flink/v2.0/flink/src/test/java/org/apache/iceberg/flink/source/TestFlinkMetaDataTable.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.iceberg.flink.source;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assumptions.assumeThat;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.avro.generic.GenericData;
import org.apache.commons.collections.ListUtils;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.CoreOptions;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.types.Row;
import org.apache.iceberg.DeleteFile;
import org.apache.iceberg.FileContent;
import org.apache.iceberg.FileFormat;
import org.apache.iceberg.Files;
import org.apache.iceberg.HasTableOperations;
import org.apache.iceberg.ManifestFile;
import org.apache.iceberg.MetadataTableType;
import org.apache.iceberg.MetadataTableUtils;
import org.apache.iceberg.MetricsUtil;
import org.apache.iceberg.Parameter;
import org.apache.iceberg.Parameters;
import org.apache.iceberg.Schema;
import org.apache.iceberg.Snapshot;
import org.apache.iceberg.Table;
import org.apache.iceberg.TableMetadata;
import org.apache.iceberg.avro.Avro;
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.catalog.TableIdentifier;
import org.apache.iceberg.data.FileHelpers;
import org.apache.iceberg.data.GenericRecord;
import org.apache.iceberg.data.Record;
import org.apache.iceberg.expressions.Expressions;
import org.apache.iceberg.flink.CatalogTestBase;
import org.apache.iceberg.flink.TestHelpers;
import org.apache.iceberg.io.CloseableIterable;
import org.apache.iceberg.io.InputFile;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
import org.apache.iceberg.relocated.com.google.common.collect.Maps;
import org.apache.iceberg.types.Types;
import org.apache.iceberg.util.SnapshotUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.io.TempDir;
public class TestFlinkMetaDataTable extends CatalogTestBase {
private static final String TABLE_NAME = "test_table";
private final FileFormat format = FileFormat.AVRO;
private @TempDir Path temp;
@Parameter(index = 2)
private Boolean isPartition;
@Parameters(name = "catalogName={0}, baseNamespace={1}, isPartition={2}")
protected static List<Object[]> parameters() {
List<Object[]> parameters = Lists.newArrayList();
for (Boolean isPartition : new Boolean[] {true, false}) {
String catalogName = "testhadoop";
Namespace baseNamespace = Namespace.of("default");
parameters.add(new Object[] {catalogName, baseNamespace, isPartition});
}
return parameters;
}
@Override
protected TableEnvironment getTableEnv() {
Configuration configuration = super.getTableEnv().getConfig().getConfiguration();
configuration.set(CoreOptions.DEFAULT_PARALLELISM, 1);
return super.getTableEnv();
}
@BeforeEach
public void before() {
super.before();
sql("USE CATALOG %s", catalogName);
sql("CREATE DATABASE %s", flinkDatabase);
sql("USE %s", DATABASE);
if (isPartition) {
sql(
"CREATE TABLE %s (id INT, data VARCHAR,d DOUBLE) PARTITIONED BY (data) WITH ('format-version'='2', 'write.format.default'='%s')",
TABLE_NAME, format.name());
sql("INSERT INTO %s VALUES (1,'a',10),(2,'a',20)", TABLE_NAME);
sql("INSERT INTO %s VALUES (1,'b',10),(2,'b',20)", TABLE_NAME);
} else {
sql(
"CREATE TABLE %s (id INT, data VARCHAR,d DOUBLE) WITH ('format-version'='2', 'write.format.default'='%s')",
TABLE_NAME, format.name());
sql(
"INSERT INTO %s VALUES (1,'iceberg',10),(2,'b',20),(3,CAST(NULL AS VARCHAR),30)",
TABLE_NAME);
sql("INSERT INTO %s VALUES (4,'iceberg',10)", TABLE_NAME);
}
}
@Override
@AfterEach
public void clean() {
sql("DROP TABLE IF EXISTS %s.%s", flinkDatabase, TABLE_NAME);
dropDatabase(flinkDatabase, true);
super.clean();
}
@TestTemplate
public void testSnapshots() {
String sql = String.format("SELECT * FROM %s$snapshots ", TABLE_NAME);
List<Row> result = sql(sql);
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Iterator<Snapshot> snapshots = table.snapshots().iterator();
for (Row row : result) {
Snapshot next = snapshots.next();
assertThat(((Instant) row.getField(0)).toEpochMilli())
.as("Should have expected timestamp")
.isEqualTo(next.timestampMillis());
assertThat(next.snapshotId())
.as("Should have expected snapshot id")
.isEqualTo(next.snapshotId());
assertThat(row.getField(2)).as("Should have expected parent id").isEqualTo(next.parentId());
assertThat(row.getField(3)).as("Should have expected operation").isEqualTo(next.operation());
assertThat(row.getField(4))
.as("Should have expected manifest list location")
.isEqualTo(next.manifestListLocation());
assertThat(row.getField(5)).as("Should have expected summary").isEqualTo(next.summary());
}
}
@TestTemplate
public void testHistory() {
String sql = String.format("SELECT * FROM %s$history ", TABLE_NAME);
List<Row> result = sql(sql);
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Iterator<Snapshot> snapshots = table.snapshots().iterator();
for (Row row : result) {
Snapshot next = snapshots.next();
assertThat(((Instant) row.getField(0)).toEpochMilli())
.as("Should have expected made_current_at")
.isEqualTo(next.timestampMillis());
assertThat(row.getField(1))
.as("Should have expected snapshot id")
.isEqualTo(next.snapshotId());
assertThat(row.getField(2)).as("Should have expected parent id").isEqualTo(next.parentId());
assertThat(row.getField(3))
.as("Should have expected is current ancestor")
.isEqualTo(
SnapshotUtil.isAncestorOf(
table, table.currentSnapshot().snapshotId(), next.snapshotId()));
}
}
@TestTemplate
public void testManifests() {
String sql = String.format("SELECT * FROM %s$manifests ", TABLE_NAME);
List<Row> result = sql(sql);
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
List<ManifestFile> expectedDataManifests = dataManifests(table);
for (int i = 0; i < result.size(); i++) {
Row row = result.get(i);
ManifestFile manifestFile = expectedDataManifests.get(i);
assertThat(row.getField(0))
.as("Should have expected content")
.isEqualTo(manifestFile.content().id());
assertThat(row.getField(1)).as("Should have expected path").isEqualTo(manifestFile.path());
assertThat(row.getField(2))
.as("Should have expected length")
.isEqualTo(manifestFile.length());
assertThat(row.getField(3))
.as("Should have expected partition_spec_id")
.isEqualTo(manifestFile.partitionSpecId());
assertThat(row.getField(4))
.as("Should have expected added_snapshot_id")
.isEqualTo(manifestFile.snapshotId());
assertThat(row.getField(5))
.as("Should have expected added_data_files_count")
.isEqualTo(manifestFile.addedFilesCount());
assertThat(row.getField(6))
.as("Should have expected existing_data_files_count")
.isEqualTo(manifestFile.existingFilesCount());
assertThat(row.getField(7))
.as("Should have expected deleted_data_files_count")
.isEqualTo(manifestFile.deletedFilesCount());
}
}
@TestTemplate
public void testAllManifests() {
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
String sql = String.format("SELECT * FROM %s$all_manifests ", TABLE_NAME);
List<Row> result = sql(sql);
List<ManifestFile> expectedDataManifests = allDataManifests(table);
assertThat(expectedDataManifests).hasSize(result.size());
for (int i = 0; i < result.size(); i++) {
Row row = result.get(i);
ManifestFile manifestFile = expectedDataManifests.get(i);
assertThat(row.getField(0))
.as("Should have expected content")
.isEqualTo(manifestFile.content().id());
assertThat(row.getField(1)).as("Should have expected path").isEqualTo(manifestFile.path());
assertThat(row.getField(2))
.as("Should have expected length")
.isEqualTo(manifestFile.length());
assertThat(row.getField(3))
.as("Should have expected partition_spec_id")
.isEqualTo(manifestFile.partitionSpecId());
assertThat(row.getField(4))
.as("Should have expected added_snapshot_id")
.isEqualTo(manifestFile.snapshotId());
assertThat(row.getField(5))
.as("Should have expected added_data_files_count")
.isEqualTo(manifestFile.addedFilesCount());
assertThat(row.getField(6))
.as("Should have expected existing_data_files_count")
.isEqualTo(manifestFile.existingFilesCount());
assertThat(row.getField(7))
.as("Should have expected deleted_data_files_count")
.isEqualTo(manifestFile.deletedFilesCount());
}
}
@TestTemplate
public void testUnPartitionedTable() throws IOException {
assumeThat(isPartition).isFalse();
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Schema deleteRowSchema = table.schema().select("id");
Record dataDelete = GenericRecord.create(deleteRowSchema);
List<Record> dataDeletes = Lists.newArrayList(dataDelete.copy("id", 1));
File testFile = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes =
FileHelpers.writeDeleteFile(
table, Files.localOutput(testFile), dataDeletes, deleteRowSchema);
table.newRowDelta().addDeletes(eqDeletes).commit();
List<ManifestFile> expectedDataManifests = dataManifests(table);
List<ManifestFile> expectedDeleteManifests = deleteManifests(table);
assertThat(expectedDataManifests).hasSize(2);
assertThat(expectedDeleteManifests).hasSize(1);
Schema entriesTableSchema =
MetadataTableUtils.createMetadataTableInstance(table, MetadataTableType.from("entries"))
.schema();
// check delete files table
Schema deleteFilesTableSchema =
MetadataTableUtils.createMetadataTableInstance(
table, MetadataTableType.from("delete_files"))
.schema();
List<String> deleteColumns =
deleteFilesTableSchema.columns().stream()
.map(Types.NestedField::name)
.filter(c -> !c.equals(MetricsUtil.READABLE_METRICS))
.collect(Collectors.toList());
String deleteNames =
deleteColumns.stream().map(n -> "`" + n + "`").collect(Collectors.joining(","));
deleteFilesTableSchema = deleteFilesTableSchema.select(deleteColumns);
List<Row> actualDeleteFiles = sql("SELECT %s FROM %s$delete_files", deleteNames, TABLE_NAME);
assertThat(actualDeleteFiles).hasSize(1);
assertThat(expectedDeleteManifests).as("Should have 1 delete manifest").hasSize(1);
List<GenericData.Record> expectedDeleteFiles =
expectedEntries(
table, FileContent.EQUALITY_DELETES, entriesTableSchema, expectedDeleteManifests, null);
assertThat(expectedDeleteFiles).as("Should be 1 delete file manifest entry").hasSize(1);
TestHelpers.assertEquals(
deleteFilesTableSchema, expectedDeleteFiles.get(0), actualDeleteFiles.get(0));
// Check data files table
Schema filesTableSchema =
MetadataTableUtils.createMetadataTableInstance(table, MetadataTableType.from("files"))
.schema();
List<String> columns =
filesTableSchema.columns().stream()
.map(Types.NestedField::name)
.filter(c -> !c.equals(MetricsUtil.READABLE_METRICS))
.collect(Collectors.toList());
String names = columns.stream().map(n -> "`" + n + "`").collect(Collectors.joining(","));
filesTableSchema = filesTableSchema.select(columns);
List<Row> actualDataFiles = sql("SELECT %s FROM %s$data_files", names, TABLE_NAME);
assertThat(actualDataFiles).as("Metadata table should return 2 data file").hasSize(2);
List<GenericData.Record> expectedDataFiles =
expectedEntries(table, FileContent.DATA, entriesTableSchema, expectedDataManifests, null);
assertThat(expectedDataFiles).as("Should be 2 data file manifest entry").hasSize(2);
TestHelpers.assertEquals(filesTableSchema, expectedDataFiles.get(0), actualDataFiles.get(0));
// check all files table
List<Row> actualFiles = sql("SELECT %s FROM %s$files ORDER BY content", names, TABLE_NAME);
assertThat(actualFiles).as("Metadata table should return 3 files").hasSize(3);
List<GenericData.Record> expectedFiles =
Stream.concat(expectedDataFiles.stream(), expectedDeleteFiles.stream())
.collect(Collectors.toList());
assertThat(expectedFiles).as("Should have 3 files manifest entriess").hasSize(3);
TestHelpers.assertEquals(filesTableSchema, expectedFiles.get(0), actualFiles.get(0));
TestHelpers.assertEquals(filesTableSchema, expectedFiles.get(1), actualFiles.get(1));
}
@TestTemplate
public void testPartitionedTable() throws Exception {
assumeThat(isPartition).isTrue();
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Schema deleteRowSchema = table.schema().select("id", "data");
Record dataDelete = GenericRecord.create(deleteRowSchema);
Map<String, Object> deleteRow = Maps.newHashMap();
deleteRow.put("id", 1);
deleteRow.put("data", "a");
File testFile = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes =
FileHelpers.writeDeleteFile(
table,
Files.localOutput(testFile),
org.apache.iceberg.TestHelpers.Row.of("a"),
Lists.newArrayList(dataDelete.copy(deleteRow)),
deleteRowSchema);
table.newRowDelta().addDeletes(eqDeletes).commit();
deleteRow.put("data", "b");
File testFile2 = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes2 =
FileHelpers.writeDeleteFile(
table,
Files.localOutput(testFile2),
org.apache.iceberg.TestHelpers.Row.of("b"),
Lists.newArrayList(dataDelete.copy(deleteRow)),
deleteRowSchema);
table.newRowDelta().addDeletes(eqDeletes2).commit();
Schema entriesTableSchema =
MetadataTableUtils.createMetadataTableInstance(table, MetadataTableType.from("entries"))
.schema();
List<ManifestFile> expectedDataManifests = dataManifests(table);
List<ManifestFile> expectedDeleteManifests = deleteManifests(table);
assertThat(expectedDataManifests).hasSize(2);
assertThat(expectedDeleteManifests).hasSize(2);
Table deleteFilesTable =
MetadataTableUtils.createMetadataTableInstance(
table, MetadataTableType.from("delete_files"));
Schema filesTableSchema = deleteFilesTable.schema();
List<String> columns =
filesTableSchema.columns().stream()
.map(Types.NestedField::name)
.filter(c -> !c.equals(MetricsUtil.READABLE_METRICS))
.collect(Collectors.toList());
String names = columns.stream().map(n -> "`" + n + "`").collect(Collectors.joining(","));
filesTableSchema = filesTableSchema.select(columns);
// Check delete files table
List<GenericData.Record> expectedDeleteFiles =
expectedEntries(
table, FileContent.EQUALITY_DELETES, entriesTableSchema, expectedDeleteManifests, "a");
assertThat(expectedDeleteFiles).hasSize(1);
List<Row> actualDeleteFiles =
sql("SELECT %s FROM %s$delete_files WHERE `partition`.`data`='a'", names, TABLE_NAME);
assertThat(actualDeleteFiles).hasSize(1);
TestHelpers.assertEquals(
filesTableSchema, expectedDeleteFiles.get(0), actualDeleteFiles.get(0));
// Check data files table
List<GenericData.Record> expectedDataFiles =
expectedEntries(table, FileContent.DATA, entriesTableSchema, expectedDataManifests, "a");
assertThat(expectedDataFiles).hasSize(1);
List<Row> actualDataFiles =
sql("SELECT %s FROM %s$data_files WHERE `partition`.`data`='a'", names, TABLE_NAME);
assertThat(actualDataFiles).hasSize(1);
TestHelpers.assertEquals(filesTableSchema, expectedDataFiles.get(0), actualDataFiles.get(0));
List<Row> actualPartitionsWithProjection =
sql("SELECT file_count FROM %s$partitions ", TABLE_NAME);
assertThat(actualPartitionsWithProjection).hasSize(2);
for (int i = 0; i < 2; ++i) {
assertThat(actualPartitionsWithProjection.get(i).getField(0)).isEqualTo(1);
}
// Check files table
List<GenericData.Record> expectedFiles =
Stream.concat(expectedDataFiles.stream(), expectedDeleteFiles.stream())
.collect(Collectors.toList());
assertThat(expectedFiles).hasSize(2);
List<Row> actualFiles =
sql(
"SELECT %s FROM %s$files WHERE `partition`.`data`='a' ORDER BY content",
names, TABLE_NAME);
assertThat(actualFiles).hasSize(2);
TestHelpers.assertEquals(filesTableSchema, expectedFiles.get(0), actualFiles.get(0));
TestHelpers.assertEquals(filesTableSchema, expectedFiles.get(1), actualFiles.get(1));
}
@TestTemplate
public void testAllFilesUnpartitioned() throws Exception {
assumeThat(isPartition).isFalse();
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Schema deleteRowSchema = table.schema().select("id", "data");
Record dataDelete = GenericRecord.create(deleteRowSchema);
Map<String, Object> deleteRow = Maps.newHashMap();
deleteRow.put("id", 1);
File testFile = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes =
FileHelpers.writeDeleteFile(
table,
Files.localOutput(testFile),
Lists.newArrayList(dataDelete.copy(deleteRow)),
deleteRowSchema);
table.newRowDelta().addDeletes(eqDeletes).commit();
List<ManifestFile> expectedDataManifests = dataManifests(table);
assertThat(expectedDataManifests).hasSize(2);
List<ManifestFile> expectedDeleteManifests = deleteManifests(table);
assertThat(expectedDeleteManifests).hasSize(1);
// Clear table to test whether 'all_files' can read past files
table.newDelete().deleteFromRowFilter(Expressions.alwaysTrue()).commit();
Schema entriesTableSchema =
MetadataTableUtils.createMetadataTableInstance(table, MetadataTableType.from("entries"))
.schema();
Schema filesTableSchema =
MetadataTableUtils.createMetadataTableInstance(
table, MetadataTableType.from("all_data_files"))
.schema();
List<String> columns =
filesTableSchema.columns().stream()
.map(Types.NestedField::name)
.filter(c -> !c.equals(MetricsUtil.READABLE_METRICS))
.collect(Collectors.toList());
String names = columns.stream().map(n -> "`" + n + "`").collect(Collectors.joining(","));
filesTableSchema = filesTableSchema.select(columns);
// Check all data files table
List<Row> actualDataFiles =
sql("SELECT %s FROM %s$all_data_files order by record_count ", names, TABLE_NAME);
List<GenericData.Record> expectedDataFiles =
expectedEntries(table, FileContent.DATA, entriesTableSchema, expectedDataManifests, null);
assertThat(expectedDataFiles).hasSize(2);
assertThat(actualDataFiles).hasSize(2);
TestHelpers.assertEquals(filesTableSchema, expectedDataFiles, actualDataFiles);
// Check all delete files table
List<Row> actualDeleteFiles = sql("SELECT %s FROM %s$all_delete_files", names, TABLE_NAME);
List<GenericData.Record> expectedDeleteFiles =
expectedEntries(
table, FileContent.EQUALITY_DELETES, entriesTableSchema, expectedDeleteManifests, null);
assertThat(expectedDeleteFiles).hasSize(1);
assertThat(actualDeleteFiles).hasSize(1);
TestHelpers.assertEquals(
filesTableSchema, expectedDeleteFiles.get(0), actualDeleteFiles.get(0));
// Check all files table
List<Row> actualFiles =
sql("SELECT %s FROM %s$all_files ORDER BY content, record_count asc", names, TABLE_NAME);
List<GenericData.Record> expectedFiles =
ListUtils.union(expectedDataFiles, expectedDeleteFiles);
expectedFiles.sort(Comparator.comparing(r -> ((Integer) r.get("content"))));
assertThat(actualFiles).hasSize(3);
TestHelpers.assertEquals(filesTableSchema, expectedFiles, actualFiles);
}
@TestTemplate
public void testAllFilesPartitioned() throws Exception {
assumeThat(!isPartition).isFalse();
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
// Create delete file
Schema deleteRowSchema = table.schema().select("id");
Record dataDelete = GenericRecord.create(deleteRowSchema);
Map<String, Object> deleteRow = Maps.newHashMap();
deleteRow.put("id", 1);
File testFile = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes =
FileHelpers.writeDeleteFile(
table,
Files.localOutput(testFile),
org.apache.iceberg.TestHelpers.Row.of("a"),
Lists.newArrayList(dataDelete.copy(deleteRow)),
deleteRowSchema);
File testFile2 = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes2 =
FileHelpers.writeDeleteFile(
table,
Files.localOutput(testFile2),
org.apache.iceberg.TestHelpers.Row.of("b"),
Lists.newArrayList(dataDelete.copy(deleteRow)),
deleteRowSchema);
table.newRowDelta().addDeletes(eqDeletes).addDeletes(eqDeletes2).commit();
List<ManifestFile> expectedDataManifests = dataManifests(table);
assertThat(expectedDataManifests).hasSize(2);
List<ManifestFile> expectedDeleteManifests = deleteManifests(table);
assertThat(expectedDeleteManifests).hasSize(1);
// Clear table to test whether 'all_files' can read past files
table.newDelete().deleteFromRowFilter(Expressions.alwaysTrue()).commit();
Schema entriesTableSchema =
MetadataTableUtils.createMetadataTableInstance(table, MetadataTableType.from("entries"))
.schema();
Schema filesTableSchema =
MetadataTableUtils.createMetadataTableInstance(
table, MetadataTableType.from("all_data_files"))
.schema();
List<String> columns =
filesTableSchema.columns().stream()
.map(Types.NestedField::name)
.filter(c -> !c.equals(MetricsUtil.READABLE_METRICS))
.collect(Collectors.toList());
String names = columns.stream().map(n -> "`" + n + "`").collect(Collectors.joining(","));
filesTableSchema = filesTableSchema.select(columns);
// Check all data files table
List<Row> actualDataFiles =
sql("SELECT %s FROM %s$all_data_files WHERE `partition`.`data`='a'", names, TABLE_NAME);
List<GenericData.Record> expectedDataFiles =
expectedEntries(table, FileContent.DATA, entriesTableSchema, expectedDataManifests, "a");
assertThat(expectedDataFiles).hasSize(1);
assertThat(actualDataFiles).hasSize(1);
TestHelpers.assertEquals(filesTableSchema, expectedDataFiles.get(0), actualDataFiles.get(0));
// Check all delete files table
List<Row> actualDeleteFiles =
sql("SELECT %s FROM %s$all_delete_files WHERE `partition`.`data`='a'", names, TABLE_NAME);
List<GenericData.Record> expectedDeleteFiles =
expectedEntries(
table, FileContent.EQUALITY_DELETES, entriesTableSchema, expectedDeleteManifests, "a");
assertThat(expectedDeleteFiles).hasSize(1);
assertThat(actualDeleteFiles).hasSize(1);
TestHelpers.assertEquals(
filesTableSchema, expectedDeleteFiles.get(0), actualDeleteFiles.get(0));
// Check all files table
List<Row> actualFiles =
sql(
"SELECT %s FROM %s$all_files WHERE `partition`.`data`='a' ORDER BY content",
names, TABLE_NAME);
List<GenericData.Record> expectedFiles =
ListUtils.union(expectedDataFiles, expectedDeleteFiles);
expectedFiles.sort(Comparator.comparing(r -> ((Integer) r.get("content"))));
assertThat(actualFiles).hasSize(2);
TestHelpers.assertEquals(filesTableSchema, expectedFiles, actualFiles);
}
@TestTemplate
public void testMetadataLogEntries() {
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Long currentSnapshotId = table.currentSnapshot().snapshotId();
TableMetadata tableMetadata = ((HasTableOperations) table).operations().current();
Snapshot currentSnapshot = tableMetadata.currentSnapshot();
Snapshot parentSnapshot = table.snapshot(currentSnapshot.parentId());
List<TableMetadata.MetadataLogEntry> metadataLogEntries =
Lists.newArrayList(tableMetadata.previousFiles());
// Check metadataLog table
List<Row> metadataLogs = sql("SELECT * FROM %s$metadata_log_entries", TABLE_NAME);
assertThat(metadataLogs).hasSize(3);
Row metadataLog = metadataLogs.get(0);
assertThat(metadataLog.getField("timestamp"))
.isEqualTo(Instant.ofEpochMilli(metadataLogEntries.get(0).timestampMillis()));
assertThat(metadataLog.getField("file")).isEqualTo(metadataLogEntries.get(0).file());
assertThat(metadataLog.getField("latest_snapshot_id")).isNull();
assertThat(metadataLog.getField("latest_schema_id")).isNull();
assertThat(metadataLog.getField("latest_sequence_number")).isNull();
metadataLog = metadataLogs.get(1);
assertThat(metadataLog.getField("timestamp"))
.isEqualTo(Instant.ofEpochMilli(metadataLogEntries.get(1).timestampMillis()));
assertThat(metadataLog.getField("file")).isEqualTo(metadataLogEntries.get(1).file());
assertThat(metadataLog.getField("latest_snapshot_id")).isEqualTo(parentSnapshot.snapshotId());
assertThat(metadataLog.getField("latest_schema_id")).isEqualTo(parentSnapshot.schemaId());
assertThat(metadataLog.getField("latest_sequence_number"))
.isEqualTo(parentSnapshot.sequenceNumber());
assertThat(metadataLog.getField("latest_snapshot_id")).isEqualTo(parentSnapshot.snapshotId());
metadataLog = metadataLogs.get(2);
assertThat(metadataLog.getField("timestamp"))
.isEqualTo(Instant.ofEpochMilli(currentSnapshot.timestampMillis()));
assertThat(metadataLog.getField("file")).isEqualTo(tableMetadata.metadataFileLocation());
assertThat(metadataLog.getField("latest_snapshot_id")).isEqualTo(currentSnapshot.snapshotId());
assertThat(metadataLog.getField("latest_schema_id")).isEqualTo(currentSnapshot.schemaId());
assertThat(metadataLog.getField("latest_sequence_number"))
.isEqualTo(currentSnapshot.sequenceNumber());
// test filtering
List<Row> metadataLogWithFilters =
sql(
"SELECT * FROM %s$metadata_log_entries WHERE latest_snapshot_id = %s",
TABLE_NAME, currentSnapshotId);
assertThat(metadataLogWithFilters).hasSize(1);
metadataLog = metadataLogWithFilters.get(0);
assertThat(Instant.ofEpochMilli(tableMetadata.currentSnapshot().timestampMillis()))
.isEqualTo(metadataLog.getField("timestamp"));
assertThat(metadataLog.getField("file")).isEqualTo(tableMetadata.metadataFileLocation());
assertThat(metadataLog.getField("latest_snapshot_id"))
.isEqualTo(tableMetadata.currentSnapshot().snapshotId());
assertThat(metadataLog.getField("latest_schema_id"))
.isEqualTo(tableMetadata.currentSnapshot().schemaId());
assertThat(metadataLog.getField("latest_sequence_number"))
.isEqualTo(tableMetadata.currentSnapshot().sequenceNumber());
// test projection
List<String> metadataFiles =
metadataLogEntries.stream()
.map(TableMetadata.MetadataLogEntry::file)
.collect(Collectors.toList());
metadataFiles.add(tableMetadata.metadataFileLocation());
List<Row> metadataLogWithProjection =
sql("SELECT file FROM %s$metadata_log_entries", TABLE_NAME);
assertThat(metadataLogWithProjection).hasSize(3);
for (int i = 0; i < metadataFiles.size(); i++) {
assertThat(metadataLogWithProjection.get(i).getField("file")).isEqualTo(metadataFiles.get(i));
}
}
@TestTemplate
public void testSnapshotReferencesMetatable() {
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Long currentSnapshotId = table.currentSnapshot().snapshotId();
// Create branch
table
.manageSnapshots()
.createBranch("testBranch", currentSnapshotId)
.setMaxRefAgeMs("testBranch", 10)
.setMinSnapshotsToKeep("testBranch", 20)
.setMaxSnapshotAgeMs("testBranch", 30)
.commit();
// Create Tag
table
.manageSnapshots()
.createTag("testTag", currentSnapshotId)
.setMaxRefAgeMs("testTag", 50)
.commit();
// Check refs table
List<Row> references = sql("SELECT * FROM %s$refs", TABLE_NAME);
List<Row> branches = sql("SELECT * FROM %s$refs WHERE type='BRANCH'", TABLE_NAME);
assertThat(references).hasSize(3);
assertThat(branches).hasSize(2);
List<Row> tags = sql("SELECT * FROM %s$refs WHERE type='TAG'", TABLE_NAME);
assertThat(tags).hasSize(1);
// Check branch entries in refs table
List<Row> mainBranch =
sql("SELECT * FROM %s$refs WHERE name='main' AND type='BRANCH'", TABLE_NAME);
assertThat((String) mainBranch.get(0).getFieldAs("name")).isEqualTo("main");
assertThat((String) mainBranch.get(0).getFieldAs("type")).isEqualTo("BRANCH");
assertThat((Long) mainBranch.get(0).getFieldAs("snapshot_id")).isEqualTo(currentSnapshotId);
List<Row> testBranch =
sql("SELECT * FROM %s$refs WHERE name='testBranch' AND type='BRANCH'", TABLE_NAME);
assertThat((String) testBranch.get(0).getFieldAs("name")).isEqualTo("testBranch");
assertThat((String) testBranch.get(0).getFieldAs("type")).isEqualTo("BRANCH");
assertThat((Long) testBranch.get(0).getFieldAs("snapshot_id")).isEqualTo(currentSnapshotId);
assertThat((Long) testBranch.get(0).getFieldAs("max_reference_age_in_ms"))
.isEqualTo(Long.valueOf(10));
assertThat((Integer) testBranch.get(0).getFieldAs("min_snapshots_to_keep"))
.isEqualTo(Integer.valueOf(20));
assertThat((Long) testBranch.get(0).getFieldAs("max_snapshot_age_in_ms"))
.isEqualTo(Long.valueOf(30));
// Check tag entries in refs table
List<Row> testTag =
sql("SELECT * FROM %s$refs WHERE name='testTag' AND type='TAG'", TABLE_NAME);
assertThat((String) testTag.get(0).getFieldAs("name")).isEqualTo("testTag");
assertThat((String) testTag.get(0).getFieldAs("type")).isEqualTo("TAG");
assertThat((Long) testTag.get(0).getFieldAs("snapshot_id")).isEqualTo(currentSnapshotId);
assertThat((Long) testTag.get(0).getFieldAs("max_reference_age_in_ms"))
.isEqualTo(Long.valueOf(50));
// Check projection in refs table
List<Row> testTagProjection =
sql(
"SELECT name,type,snapshot_id,max_reference_age_in_ms,min_snapshots_to_keep FROM %s$refs where type='TAG'",
TABLE_NAME);
assertThat((String) testTagProjection.get(0).getFieldAs("name")).isEqualTo("testTag");
assertThat((String) testTagProjection.get(0).getFieldAs("type")).isEqualTo("TAG");
assertThat((Long) testTagProjection.get(0).getFieldAs("snapshot_id"))
.isEqualTo(currentSnapshotId);
assertThat((Long) testTagProjection.get(0).getFieldAs("max_reference_age_in_ms"))
.isEqualTo(Long.valueOf(50));
assertThat((String) testTagProjection.get(0).getFieldAs("min_snapshots_to_keep")).isNull();
List<Row> mainBranchProjection =
sql("SELECT name, type FROM %s$refs WHERE name='main' AND type = 'BRANCH'", TABLE_NAME);
assertThat((String) mainBranchProjection.get(0).getFieldAs("name")).isEqualTo("main");
assertThat((String) mainBranchProjection.get(0).getFieldAs("type")).isEqualTo("BRANCH");
List<Row> testBranchProjection =
sql(
"SELECT type, name, max_reference_age_in_ms, snapshot_id FROM %s$refs WHERE name='testBranch' AND type = 'BRANCH'",
TABLE_NAME);
assertThat((String) testBranchProjection.get(0).getFieldAs("name")).isEqualTo("testBranch");
assertThat((String) testBranchProjection.get(0).getFieldAs("type")).isEqualTo("BRANCH");
assertThat((Long) testBranchProjection.get(0).getFieldAs("snapshot_id"))
.isEqualTo(currentSnapshotId);
assertThat((Long) testBranchProjection.get(0).getFieldAs("max_reference_age_in_ms"))
.isEqualTo(Long.valueOf(10));
}
/**
* Find matching manifest entries of an Iceberg table
*
* @param table iceberg table
* @param expectedContent file content to populate on entries
* @param entriesTableSchema schema of Manifest entries
* @param manifestsToExplore manifests to explore of the table
* @param partValue partition value that manifest entries must match, or null to skip filtering
*/
private List<GenericData.Record> expectedEntries(
Table table,
FileContent expectedContent,
Schema entriesTableSchema,
List<ManifestFile> manifestsToExplore,
String partValue)
throws IOException {
List<GenericData.Record> expected = Lists.newArrayList();
for (ManifestFile manifest : manifestsToExplore) {
InputFile in = table.io().newInputFile(manifest.path());
try (CloseableIterable<GenericData.Record> rows =
Avro.read(in).project(entriesTableSchema).build()) {
for (GenericData.Record record : rows) {
if ((Integer) record.get("status") < 2 /* added or existing */) {
GenericData.Record file = (GenericData.Record) record.get("data_file");
if (partitionMatch(file, partValue)) {
asMetadataRecord(file, expectedContent);
expected.add(file);
}
}
}
}
}
return expected;
}
// Populate certain fields derived in the metadata tables
private void asMetadataRecord(GenericData.Record file, FileContent content) {
file.put(0, content.id());
file.put(3, 0); // specId
}
private boolean partitionMatch(GenericData.Record file, String partValue) {
if (partValue == null) {
return true;
}
GenericData.Record partition = (GenericData.Record) file.get(4);
return partValue.equals(partition.get(0).toString());
}
private List<ManifestFile> dataManifests(Table table) {
return table.currentSnapshot().dataManifests(table.io());
}
private List<ManifestFile> allDataManifests(Table table) {
List<ManifestFile> manifests = Lists.newArrayList();
for (Snapshot snapshot : table.snapshots()) {
manifests.addAll(snapshot.dataManifests(table.io()));
}
return manifests;
}
private List<ManifestFile> deleteManifests(Table table) {
return table.currentSnapshot().deleteManifests(table.io());
}
}
|
apache/iceberg | 36,519 | flink/v2.1/flink/src/test/java/org/apache/iceberg/flink/source/TestFlinkMetaDataTable.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.iceberg.flink.source;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assumptions.assumeThat;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.avro.generic.GenericData;
import org.apache.commons.collections.ListUtils;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.CoreOptions;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.types.Row;
import org.apache.iceberg.DeleteFile;
import org.apache.iceberg.FileContent;
import org.apache.iceberg.FileFormat;
import org.apache.iceberg.Files;
import org.apache.iceberg.HasTableOperations;
import org.apache.iceberg.ManifestFile;
import org.apache.iceberg.MetadataTableType;
import org.apache.iceberg.MetadataTableUtils;
import org.apache.iceberg.MetricsUtil;
import org.apache.iceberg.Parameter;
import org.apache.iceberg.Parameters;
import org.apache.iceberg.Schema;
import org.apache.iceberg.Snapshot;
import org.apache.iceberg.Table;
import org.apache.iceberg.TableMetadata;
import org.apache.iceberg.avro.Avro;
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.catalog.TableIdentifier;
import org.apache.iceberg.data.FileHelpers;
import org.apache.iceberg.data.GenericRecord;
import org.apache.iceberg.data.Record;
import org.apache.iceberg.expressions.Expressions;
import org.apache.iceberg.flink.CatalogTestBase;
import org.apache.iceberg.flink.TestHelpers;
import org.apache.iceberg.io.CloseableIterable;
import org.apache.iceberg.io.InputFile;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
import org.apache.iceberg.relocated.com.google.common.collect.Maps;
import org.apache.iceberg.types.Types;
import org.apache.iceberg.util.SnapshotUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.io.TempDir;
public class TestFlinkMetaDataTable extends CatalogTestBase {
private static final String TABLE_NAME = "test_table";
private final FileFormat format = FileFormat.AVRO;
private @TempDir Path temp;
@Parameter(index = 2)
private Boolean isPartition;
@Parameters(name = "catalogName={0}, baseNamespace={1}, isPartition={2}")
protected static List<Object[]> parameters() {
List<Object[]> parameters = Lists.newArrayList();
for (Boolean isPartition : new Boolean[] {true, false}) {
String catalogName = "testhadoop";
Namespace baseNamespace = Namespace.of("default");
parameters.add(new Object[] {catalogName, baseNamespace, isPartition});
}
return parameters;
}
@Override
protected TableEnvironment getTableEnv() {
Configuration configuration = super.getTableEnv().getConfig().getConfiguration();
configuration.set(CoreOptions.DEFAULT_PARALLELISM, 1);
return super.getTableEnv();
}
@BeforeEach
public void before() {
super.before();
sql("USE CATALOG %s", catalogName);
sql("CREATE DATABASE %s", flinkDatabase);
sql("USE %s", DATABASE);
if (isPartition) {
sql(
"CREATE TABLE %s (id INT, data VARCHAR,d DOUBLE) PARTITIONED BY (data) WITH ('format-version'='2', 'write.format.default'='%s')",
TABLE_NAME, format.name());
sql("INSERT INTO %s VALUES (1,'a',10),(2,'a',20)", TABLE_NAME);
sql("INSERT INTO %s VALUES (1,'b',10),(2,'b',20)", TABLE_NAME);
} else {
sql(
"CREATE TABLE %s (id INT, data VARCHAR,d DOUBLE) WITH ('format-version'='2', 'write.format.default'='%s')",
TABLE_NAME, format.name());
sql(
"INSERT INTO %s VALUES (1,'iceberg',10),(2,'b',20),(3,CAST(NULL AS VARCHAR),30)",
TABLE_NAME);
sql("INSERT INTO %s VALUES (4,'iceberg',10)", TABLE_NAME);
}
}
@Override
@AfterEach
public void clean() {
sql("DROP TABLE IF EXISTS %s.%s", flinkDatabase, TABLE_NAME);
dropDatabase(flinkDatabase, true);
super.clean();
}
@TestTemplate
public void testSnapshots() {
String sql = String.format("SELECT * FROM %s$snapshots ", TABLE_NAME);
List<Row> result = sql(sql);
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Iterator<Snapshot> snapshots = table.snapshots().iterator();
for (Row row : result) {
Snapshot next = snapshots.next();
assertThat(((Instant) row.getField(0)).toEpochMilli())
.as("Should have expected timestamp")
.isEqualTo(next.timestampMillis());
assertThat(next.snapshotId())
.as("Should have expected snapshot id")
.isEqualTo(next.snapshotId());
assertThat(row.getField(2)).as("Should have expected parent id").isEqualTo(next.parentId());
assertThat(row.getField(3)).as("Should have expected operation").isEqualTo(next.operation());
assertThat(row.getField(4))
.as("Should have expected manifest list location")
.isEqualTo(next.manifestListLocation());
assertThat(row.getField(5)).as("Should have expected summary").isEqualTo(next.summary());
}
}
@TestTemplate
public void testHistory() {
String sql = String.format("SELECT * FROM %s$history ", TABLE_NAME);
List<Row> result = sql(sql);
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Iterator<Snapshot> snapshots = table.snapshots().iterator();
for (Row row : result) {
Snapshot next = snapshots.next();
assertThat(((Instant) row.getField(0)).toEpochMilli())
.as("Should have expected made_current_at")
.isEqualTo(next.timestampMillis());
assertThat(row.getField(1))
.as("Should have expected snapshot id")
.isEqualTo(next.snapshotId());
assertThat(row.getField(2)).as("Should have expected parent id").isEqualTo(next.parentId());
assertThat(row.getField(3))
.as("Should have expected is current ancestor")
.isEqualTo(
SnapshotUtil.isAncestorOf(
table, table.currentSnapshot().snapshotId(), next.snapshotId()));
}
}
@TestTemplate
public void testManifests() {
String sql = String.format("SELECT * FROM %s$manifests ", TABLE_NAME);
List<Row> result = sql(sql);
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
List<ManifestFile> expectedDataManifests = dataManifests(table);
for (int i = 0; i < result.size(); i++) {
Row row = result.get(i);
ManifestFile manifestFile = expectedDataManifests.get(i);
assertThat(row.getField(0))
.as("Should have expected content")
.isEqualTo(manifestFile.content().id());
assertThat(row.getField(1)).as("Should have expected path").isEqualTo(manifestFile.path());
assertThat(row.getField(2))
.as("Should have expected length")
.isEqualTo(manifestFile.length());
assertThat(row.getField(3))
.as("Should have expected partition_spec_id")
.isEqualTo(manifestFile.partitionSpecId());
assertThat(row.getField(4))
.as("Should have expected added_snapshot_id")
.isEqualTo(manifestFile.snapshotId());
assertThat(row.getField(5))
.as("Should have expected added_data_files_count")
.isEqualTo(manifestFile.addedFilesCount());
assertThat(row.getField(6))
.as("Should have expected existing_data_files_count")
.isEqualTo(manifestFile.existingFilesCount());
assertThat(row.getField(7))
.as("Should have expected deleted_data_files_count")
.isEqualTo(manifestFile.deletedFilesCount());
}
}
@TestTemplate
public void testAllManifests() {
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
String sql = String.format("SELECT * FROM %s$all_manifests ", TABLE_NAME);
List<Row> result = sql(sql);
List<ManifestFile> expectedDataManifests = allDataManifests(table);
assertThat(expectedDataManifests).hasSize(result.size());
for (int i = 0; i < result.size(); i++) {
Row row = result.get(i);
ManifestFile manifestFile = expectedDataManifests.get(i);
assertThat(row.getField(0))
.as("Should have expected content")
.isEqualTo(manifestFile.content().id());
assertThat(row.getField(1)).as("Should have expected path").isEqualTo(manifestFile.path());
assertThat(row.getField(2))
.as("Should have expected length")
.isEqualTo(manifestFile.length());
assertThat(row.getField(3))
.as("Should have expected partition_spec_id")
.isEqualTo(manifestFile.partitionSpecId());
assertThat(row.getField(4))
.as("Should have expected added_snapshot_id")
.isEqualTo(manifestFile.snapshotId());
assertThat(row.getField(5))
.as("Should have expected added_data_files_count")
.isEqualTo(manifestFile.addedFilesCount());
assertThat(row.getField(6))
.as("Should have expected existing_data_files_count")
.isEqualTo(manifestFile.existingFilesCount());
assertThat(row.getField(7))
.as("Should have expected deleted_data_files_count")
.isEqualTo(manifestFile.deletedFilesCount());
}
}
@TestTemplate
public void testUnPartitionedTable() throws IOException {
assumeThat(isPartition).isFalse();
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Schema deleteRowSchema = table.schema().select("id");
Record dataDelete = GenericRecord.create(deleteRowSchema);
List<Record> dataDeletes = Lists.newArrayList(dataDelete.copy("id", 1));
File testFile = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes =
FileHelpers.writeDeleteFile(
table, Files.localOutput(testFile), dataDeletes, deleteRowSchema);
table.newRowDelta().addDeletes(eqDeletes).commit();
List<ManifestFile> expectedDataManifests = dataManifests(table);
List<ManifestFile> expectedDeleteManifests = deleteManifests(table);
assertThat(expectedDataManifests).hasSize(2);
assertThat(expectedDeleteManifests).hasSize(1);
Schema entriesTableSchema =
MetadataTableUtils.createMetadataTableInstance(table, MetadataTableType.from("entries"))
.schema();
// check delete files table
Schema deleteFilesTableSchema =
MetadataTableUtils.createMetadataTableInstance(
table, MetadataTableType.from("delete_files"))
.schema();
List<String> deleteColumns =
deleteFilesTableSchema.columns().stream()
.map(Types.NestedField::name)
.filter(c -> !c.equals(MetricsUtil.READABLE_METRICS))
.collect(Collectors.toList());
String deleteNames =
deleteColumns.stream().map(n -> "`" + n + "`").collect(Collectors.joining(","));
deleteFilesTableSchema = deleteFilesTableSchema.select(deleteColumns);
List<Row> actualDeleteFiles = sql("SELECT %s FROM %s$delete_files", deleteNames, TABLE_NAME);
assertThat(actualDeleteFiles).hasSize(1);
assertThat(expectedDeleteManifests).as("Should have 1 delete manifest").hasSize(1);
List<GenericData.Record> expectedDeleteFiles =
expectedEntries(
table, FileContent.EQUALITY_DELETES, entriesTableSchema, expectedDeleteManifests, null);
assertThat(expectedDeleteFiles).as("Should be 1 delete file manifest entry").hasSize(1);
TestHelpers.assertEquals(
deleteFilesTableSchema, expectedDeleteFiles.get(0), actualDeleteFiles.get(0));
// Check data files table
Schema filesTableSchema =
MetadataTableUtils.createMetadataTableInstance(table, MetadataTableType.from("files"))
.schema();
List<String> columns =
filesTableSchema.columns().stream()
.map(Types.NestedField::name)
.filter(c -> !c.equals(MetricsUtil.READABLE_METRICS))
.collect(Collectors.toList());
String names = columns.stream().map(n -> "`" + n + "`").collect(Collectors.joining(","));
filesTableSchema = filesTableSchema.select(columns);
List<Row> actualDataFiles = sql("SELECT %s FROM %s$data_files", names, TABLE_NAME);
assertThat(actualDataFiles).as("Metadata table should return 2 data file").hasSize(2);
List<GenericData.Record> expectedDataFiles =
expectedEntries(table, FileContent.DATA, entriesTableSchema, expectedDataManifests, null);
assertThat(expectedDataFiles).as("Should be 2 data file manifest entry").hasSize(2);
TestHelpers.assertEquals(filesTableSchema, expectedDataFiles.get(0), actualDataFiles.get(0));
// check all files table
List<Row> actualFiles = sql("SELECT %s FROM %s$files ORDER BY content", names, TABLE_NAME);
assertThat(actualFiles).as("Metadata table should return 3 files").hasSize(3);
List<GenericData.Record> expectedFiles =
Stream.concat(expectedDataFiles.stream(), expectedDeleteFiles.stream())
.collect(Collectors.toList());
assertThat(expectedFiles).as("Should have 3 files manifest entriess").hasSize(3);
TestHelpers.assertEquals(filesTableSchema, expectedFiles.get(0), actualFiles.get(0));
TestHelpers.assertEquals(filesTableSchema, expectedFiles.get(1), actualFiles.get(1));
}
@TestTemplate
public void testPartitionedTable() throws Exception {
assumeThat(isPartition).isTrue();
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Schema deleteRowSchema = table.schema().select("id", "data");
Record dataDelete = GenericRecord.create(deleteRowSchema);
Map<String, Object> deleteRow = Maps.newHashMap();
deleteRow.put("id", 1);
deleteRow.put("data", "a");
File testFile = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes =
FileHelpers.writeDeleteFile(
table,
Files.localOutput(testFile),
org.apache.iceberg.TestHelpers.Row.of("a"),
Lists.newArrayList(dataDelete.copy(deleteRow)),
deleteRowSchema);
table.newRowDelta().addDeletes(eqDeletes).commit();
deleteRow.put("data", "b");
File testFile2 = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes2 =
FileHelpers.writeDeleteFile(
table,
Files.localOutput(testFile2),
org.apache.iceberg.TestHelpers.Row.of("b"),
Lists.newArrayList(dataDelete.copy(deleteRow)),
deleteRowSchema);
table.newRowDelta().addDeletes(eqDeletes2).commit();
Schema entriesTableSchema =
MetadataTableUtils.createMetadataTableInstance(table, MetadataTableType.from("entries"))
.schema();
List<ManifestFile> expectedDataManifests = dataManifests(table);
List<ManifestFile> expectedDeleteManifests = deleteManifests(table);
assertThat(expectedDataManifests).hasSize(2);
assertThat(expectedDeleteManifests).hasSize(2);
Table deleteFilesTable =
MetadataTableUtils.createMetadataTableInstance(
table, MetadataTableType.from("delete_files"));
Schema filesTableSchema = deleteFilesTable.schema();
List<String> columns =
filesTableSchema.columns().stream()
.map(Types.NestedField::name)
.filter(c -> !c.equals(MetricsUtil.READABLE_METRICS))
.collect(Collectors.toList());
String names = columns.stream().map(n -> "`" + n + "`").collect(Collectors.joining(","));
filesTableSchema = filesTableSchema.select(columns);
// Check delete files table
List<GenericData.Record> expectedDeleteFiles =
expectedEntries(
table, FileContent.EQUALITY_DELETES, entriesTableSchema, expectedDeleteManifests, "a");
assertThat(expectedDeleteFiles).hasSize(1);
List<Row> actualDeleteFiles =
sql("SELECT %s FROM %s$delete_files WHERE `partition`.`data`='a'", names, TABLE_NAME);
assertThat(actualDeleteFiles).hasSize(1);
TestHelpers.assertEquals(
filesTableSchema, expectedDeleteFiles.get(0), actualDeleteFiles.get(0));
// Check data files table
List<GenericData.Record> expectedDataFiles =
expectedEntries(table, FileContent.DATA, entriesTableSchema, expectedDataManifests, "a");
assertThat(expectedDataFiles).hasSize(1);
List<Row> actualDataFiles =
sql("SELECT %s FROM %s$data_files WHERE `partition`.`data`='a'", names, TABLE_NAME);
assertThat(actualDataFiles).hasSize(1);
TestHelpers.assertEquals(filesTableSchema, expectedDataFiles.get(0), actualDataFiles.get(0));
List<Row> actualPartitionsWithProjection =
sql("SELECT file_count FROM %s$partitions ", TABLE_NAME);
assertThat(actualPartitionsWithProjection).hasSize(2);
for (int i = 0; i < 2; ++i) {
assertThat(actualPartitionsWithProjection.get(i).getField(0)).isEqualTo(1);
}
// Check files table
List<GenericData.Record> expectedFiles =
Stream.concat(expectedDataFiles.stream(), expectedDeleteFiles.stream())
.collect(Collectors.toList());
assertThat(expectedFiles).hasSize(2);
List<Row> actualFiles =
sql(
"SELECT %s FROM %s$files WHERE `partition`.`data`='a' ORDER BY content",
names, TABLE_NAME);
assertThat(actualFiles).hasSize(2);
TestHelpers.assertEquals(filesTableSchema, expectedFiles.get(0), actualFiles.get(0));
TestHelpers.assertEquals(filesTableSchema, expectedFiles.get(1), actualFiles.get(1));
}
@TestTemplate
public void testAllFilesUnpartitioned() throws Exception {
assumeThat(isPartition).isFalse();
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Schema deleteRowSchema = table.schema().select("id", "data");
Record dataDelete = GenericRecord.create(deleteRowSchema);
Map<String, Object> deleteRow = Maps.newHashMap();
deleteRow.put("id", 1);
File testFile = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes =
FileHelpers.writeDeleteFile(
table,
Files.localOutput(testFile),
Lists.newArrayList(dataDelete.copy(deleteRow)),
deleteRowSchema);
table.newRowDelta().addDeletes(eqDeletes).commit();
List<ManifestFile> expectedDataManifests = dataManifests(table);
assertThat(expectedDataManifests).hasSize(2);
List<ManifestFile> expectedDeleteManifests = deleteManifests(table);
assertThat(expectedDeleteManifests).hasSize(1);
// Clear table to test whether 'all_files' can read past files
table.newDelete().deleteFromRowFilter(Expressions.alwaysTrue()).commit();
Schema entriesTableSchema =
MetadataTableUtils.createMetadataTableInstance(table, MetadataTableType.from("entries"))
.schema();
Schema filesTableSchema =
MetadataTableUtils.createMetadataTableInstance(
table, MetadataTableType.from("all_data_files"))
.schema();
List<String> columns =
filesTableSchema.columns().stream()
.map(Types.NestedField::name)
.filter(c -> !c.equals(MetricsUtil.READABLE_METRICS))
.collect(Collectors.toList());
String names = columns.stream().map(n -> "`" + n + "`").collect(Collectors.joining(","));
filesTableSchema = filesTableSchema.select(columns);
// Check all data files table
List<Row> actualDataFiles =
sql("SELECT %s FROM %s$all_data_files order by record_count ", names, TABLE_NAME);
List<GenericData.Record> expectedDataFiles =
expectedEntries(table, FileContent.DATA, entriesTableSchema, expectedDataManifests, null);
assertThat(expectedDataFiles).hasSize(2);
assertThat(actualDataFiles).hasSize(2);
TestHelpers.assertEquals(filesTableSchema, expectedDataFiles, actualDataFiles);
// Check all delete files table
List<Row> actualDeleteFiles = sql("SELECT %s FROM %s$all_delete_files", names, TABLE_NAME);
List<GenericData.Record> expectedDeleteFiles =
expectedEntries(
table, FileContent.EQUALITY_DELETES, entriesTableSchema, expectedDeleteManifests, null);
assertThat(expectedDeleteFiles).hasSize(1);
assertThat(actualDeleteFiles).hasSize(1);
TestHelpers.assertEquals(
filesTableSchema, expectedDeleteFiles.get(0), actualDeleteFiles.get(0));
// Check all files table
List<Row> actualFiles =
sql("SELECT %s FROM %s$all_files ORDER BY content, record_count asc", names, TABLE_NAME);
List<GenericData.Record> expectedFiles =
ListUtils.union(expectedDataFiles, expectedDeleteFiles);
expectedFiles.sort(Comparator.comparing(r -> ((Integer) r.get("content"))));
assertThat(actualFiles).hasSize(3);
TestHelpers.assertEquals(filesTableSchema, expectedFiles, actualFiles);
}
@TestTemplate
public void testAllFilesPartitioned() throws Exception {
assumeThat(!isPartition).isFalse();
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
// Create delete file
Schema deleteRowSchema = table.schema().select("id");
Record dataDelete = GenericRecord.create(deleteRowSchema);
Map<String, Object> deleteRow = Maps.newHashMap();
deleteRow.put("id", 1);
File testFile = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes =
FileHelpers.writeDeleteFile(
table,
Files.localOutput(testFile),
org.apache.iceberg.TestHelpers.Row.of("a"),
Lists.newArrayList(dataDelete.copy(deleteRow)),
deleteRowSchema);
File testFile2 = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes2 =
FileHelpers.writeDeleteFile(
table,
Files.localOutput(testFile2),
org.apache.iceberg.TestHelpers.Row.of("b"),
Lists.newArrayList(dataDelete.copy(deleteRow)),
deleteRowSchema);
table.newRowDelta().addDeletes(eqDeletes).addDeletes(eqDeletes2).commit();
List<ManifestFile> expectedDataManifests = dataManifests(table);
assertThat(expectedDataManifests).hasSize(2);
List<ManifestFile> expectedDeleteManifests = deleteManifests(table);
assertThat(expectedDeleteManifests).hasSize(1);
// Clear table to test whether 'all_files' can read past files
table.newDelete().deleteFromRowFilter(Expressions.alwaysTrue()).commit();
Schema entriesTableSchema =
MetadataTableUtils.createMetadataTableInstance(table, MetadataTableType.from("entries"))
.schema();
Schema filesTableSchema =
MetadataTableUtils.createMetadataTableInstance(
table, MetadataTableType.from("all_data_files"))
.schema();
List<String> columns =
filesTableSchema.columns().stream()
.map(Types.NestedField::name)
.filter(c -> !c.equals(MetricsUtil.READABLE_METRICS))
.collect(Collectors.toList());
String names = columns.stream().map(n -> "`" + n + "`").collect(Collectors.joining(","));
filesTableSchema = filesTableSchema.select(columns);
// Check all data files table
List<Row> actualDataFiles =
sql("SELECT %s FROM %s$all_data_files WHERE `partition`.`data`='a'", names, TABLE_NAME);
List<GenericData.Record> expectedDataFiles =
expectedEntries(table, FileContent.DATA, entriesTableSchema, expectedDataManifests, "a");
assertThat(expectedDataFiles).hasSize(1);
assertThat(actualDataFiles).hasSize(1);
TestHelpers.assertEquals(filesTableSchema, expectedDataFiles.get(0), actualDataFiles.get(0));
// Check all delete files table
List<Row> actualDeleteFiles =
sql("SELECT %s FROM %s$all_delete_files WHERE `partition`.`data`='a'", names, TABLE_NAME);
List<GenericData.Record> expectedDeleteFiles =
expectedEntries(
table, FileContent.EQUALITY_DELETES, entriesTableSchema, expectedDeleteManifests, "a");
assertThat(expectedDeleteFiles).hasSize(1);
assertThat(actualDeleteFiles).hasSize(1);
TestHelpers.assertEquals(
filesTableSchema, expectedDeleteFiles.get(0), actualDeleteFiles.get(0));
// Check all files table
List<Row> actualFiles =
sql(
"SELECT %s FROM %s$all_files WHERE `partition`.`data`='a' ORDER BY content",
names, TABLE_NAME);
List<GenericData.Record> expectedFiles =
ListUtils.union(expectedDataFiles, expectedDeleteFiles);
expectedFiles.sort(Comparator.comparing(r -> ((Integer) r.get("content"))));
assertThat(actualFiles).hasSize(2);
TestHelpers.assertEquals(filesTableSchema, expectedFiles, actualFiles);
}
@TestTemplate
public void testMetadataLogEntries() {
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Long currentSnapshotId = table.currentSnapshot().snapshotId();
TableMetadata tableMetadata = ((HasTableOperations) table).operations().current();
Snapshot currentSnapshot = tableMetadata.currentSnapshot();
Snapshot parentSnapshot = table.snapshot(currentSnapshot.parentId());
List<TableMetadata.MetadataLogEntry> metadataLogEntries =
Lists.newArrayList(tableMetadata.previousFiles());
// Check metadataLog table
List<Row> metadataLogs = sql("SELECT * FROM %s$metadata_log_entries", TABLE_NAME);
assertThat(metadataLogs).hasSize(3);
Row metadataLog = metadataLogs.get(0);
assertThat(metadataLog.getField("timestamp"))
.isEqualTo(Instant.ofEpochMilli(metadataLogEntries.get(0).timestampMillis()));
assertThat(metadataLog.getField("file")).isEqualTo(metadataLogEntries.get(0).file());
assertThat(metadataLog.getField("latest_snapshot_id")).isNull();
assertThat(metadataLog.getField("latest_schema_id")).isNull();
assertThat(metadataLog.getField("latest_sequence_number")).isNull();
metadataLog = metadataLogs.get(1);
assertThat(metadataLog.getField("timestamp"))
.isEqualTo(Instant.ofEpochMilli(metadataLogEntries.get(1).timestampMillis()));
assertThat(metadataLog.getField("file")).isEqualTo(metadataLogEntries.get(1).file());
assertThat(metadataLog.getField("latest_snapshot_id")).isEqualTo(parentSnapshot.snapshotId());
assertThat(metadataLog.getField("latest_schema_id")).isEqualTo(parentSnapshot.schemaId());
assertThat(metadataLog.getField("latest_sequence_number"))
.isEqualTo(parentSnapshot.sequenceNumber());
assertThat(metadataLog.getField("latest_snapshot_id")).isEqualTo(parentSnapshot.snapshotId());
metadataLog = metadataLogs.get(2);
assertThat(metadataLog.getField("timestamp"))
.isEqualTo(Instant.ofEpochMilli(currentSnapshot.timestampMillis()));
assertThat(metadataLog.getField("file")).isEqualTo(tableMetadata.metadataFileLocation());
assertThat(metadataLog.getField("latest_snapshot_id")).isEqualTo(currentSnapshot.snapshotId());
assertThat(metadataLog.getField("latest_schema_id")).isEqualTo(currentSnapshot.schemaId());
assertThat(metadataLog.getField("latest_sequence_number"))
.isEqualTo(currentSnapshot.sequenceNumber());
// test filtering
List<Row> metadataLogWithFilters =
sql(
"SELECT * FROM %s$metadata_log_entries WHERE latest_snapshot_id = %s",
TABLE_NAME, currentSnapshotId);
assertThat(metadataLogWithFilters).hasSize(1);
metadataLog = metadataLogWithFilters.get(0);
assertThat(Instant.ofEpochMilli(tableMetadata.currentSnapshot().timestampMillis()))
.isEqualTo(metadataLog.getField("timestamp"));
assertThat(metadataLog.getField("file")).isEqualTo(tableMetadata.metadataFileLocation());
assertThat(metadataLog.getField("latest_snapshot_id"))
.isEqualTo(tableMetadata.currentSnapshot().snapshotId());
assertThat(metadataLog.getField("latest_schema_id"))
.isEqualTo(tableMetadata.currentSnapshot().schemaId());
assertThat(metadataLog.getField("latest_sequence_number"))
.isEqualTo(tableMetadata.currentSnapshot().sequenceNumber());
// test projection
List<String> metadataFiles =
metadataLogEntries.stream()
.map(TableMetadata.MetadataLogEntry::file)
.collect(Collectors.toList());
metadataFiles.add(tableMetadata.metadataFileLocation());
List<Row> metadataLogWithProjection =
sql("SELECT file FROM %s$metadata_log_entries", TABLE_NAME);
assertThat(metadataLogWithProjection).hasSize(3);
for (int i = 0; i < metadataFiles.size(); i++) {
assertThat(metadataLogWithProjection.get(i).getField("file")).isEqualTo(metadataFiles.get(i));
}
}
@TestTemplate
public void testSnapshotReferencesMetatable() {
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Long currentSnapshotId = table.currentSnapshot().snapshotId();
// Create branch
table
.manageSnapshots()
.createBranch("testBranch", currentSnapshotId)
.setMaxRefAgeMs("testBranch", 10)
.setMinSnapshotsToKeep("testBranch", 20)
.setMaxSnapshotAgeMs("testBranch", 30)
.commit();
// Create Tag
table
.manageSnapshots()
.createTag("testTag", currentSnapshotId)
.setMaxRefAgeMs("testTag", 50)
.commit();
// Check refs table
List<Row> references = sql("SELECT * FROM %s$refs", TABLE_NAME);
List<Row> branches = sql("SELECT * FROM %s$refs WHERE type='BRANCH'", TABLE_NAME);
assertThat(references).hasSize(3);
assertThat(branches).hasSize(2);
List<Row> tags = sql("SELECT * FROM %s$refs WHERE type='TAG'", TABLE_NAME);
assertThat(tags).hasSize(1);
// Check branch entries in refs table
List<Row> mainBranch =
sql("SELECT * FROM %s$refs WHERE name='main' AND type='BRANCH'", TABLE_NAME);
assertThat((String) mainBranch.get(0).getFieldAs("name")).isEqualTo("main");
assertThat((String) mainBranch.get(0).getFieldAs("type")).isEqualTo("BRANCH");
assertThat((Long) mainBranch.get(0).getFieldAs("snapshot_id")).isEqualTo(currentSnapshotId);
List<Row> testBranch =
sql("SELECT * FROM %s$refs WHERE name='testBranch' AND type='BRANCH'", TABLE_NAME);
assertThat((String) testBranch.get(0).getFieldAs("name")).isEqualTo("testBranch");
assertThat((String) testBranch.get(0).getFieldAs("type")).isEqualTo("BRANCH");
assertThat((Long) testBranch.get(0).getFieldAs("snapshot_id")).isEqualTo(currentSnapshotId);
assertThat((Long) testBranch.get(0).getFieldAs("max_reference_age_in_ms"))
.isEqualTo(Long.valueOf(10));
assertThat((Integer) testBranch.get(0).getFieldAs("min_snapshots_to_keep"))
.isEqualTo(Integer.valueOf(20));
assertThat((Long) testBranch.get(0).getFieldAs("max_snapshot_age_in_ms"))
.isEqualTo(Long.valueOf(30));
// Check tag entries in refs table
List<Row> testTag =
sql("SELECT * FROM %s$refs WHERE name='testTag' AND type='TAG'", TABLE_NAME);
assertThat((String) testTag.get(0).getFieldAs("name")).isEqualTo("testTag");
assertThat((String) testTag.get(0).getFieldAs("type")).isEqualTo("TAG");
assertThat((Long) testTag.get(0).getFieldAs("snapshot_id")).isEqualTo(currentSnapshotId);
assertThat((Long) testTag.get(0).getFieldAs("max_reference_age_in_ms"))
.isEqualTo(Long.valueOf(50));
// Check projection in refs table
List<Row> testTagProjection =
sql(
"SELECT name,type,snapshot_id,max_reference_age_in_ms,min_snapshots_to_keep FROM %s$refs where type='TAG'",
TABLE_NAME);
assertThat((String) testTagProjection.get(0).getFieldAs("name")).isEqualTo("testTag");
assertThat((String) testTagProjection.get(0).getFieldAs("type")).isEqualTo("TAG");
assertThat((Long) testTagProjection.get(0).getFieldAs("snapshot_id"))
.isEqualTo(currentSnapshotId);
assertThat((Long) testTagProjection.get(0).getFieldAs("max_reference_age_in_ms"))
.isEqualTo(Long.valueOf(50));
assertThat((String) testTagProjection.get(0).getFieldAs("min_snapshots_to_keep")).isNull();
List<Row> mainBranchProjection =
sql("SELECT name, type FROM %s$refs WHERE name='main' AND type = 'BRANCH'", TABLE_NAME);
assertThat((String) mainBranchProjection.get(0).getFieldAs("name")).isEqualTo("main");
assertThat((String) mainBranchProjection.get(0).getFieldAs("type")).isEqualTo("BRANCH");
List<Row> testBranchProjection =
sql(
"SELECT type, name, max_reference_age_in_ms, snapshot_id FROM %s$refs WHERE name='testBranch' AND type = 'BRANCH'",
TABLE_NAME);
assertThat((String) testBranchProjection.get(0).getFieldAs("name")).isEqualTo("testBranch");
assertThat((String) testBranchProjection.get(0).getFieldAs("type")).isEqualTo("BRANCH");
assertThat((Long) testBranchProjection.get(0).getFieldAs("snapshot_id"))
.isEqualTo(currentSnapshotId);
assertThat((Long) testBranchProjection.get(0).getFieldAs("max_reference_age_in_ms"))
.isEqualTo(Long.valueOf(10));
}
/**
* Find matching manifest entries of an Iceberg table
*
* @param table iceberg table
* @param expectedContent file content to populate on entries
* @param entriesTableSchema schema of Manifest entries
* @param manifestsToExplore manifests to explore of the table
* @param partValue partition value that manifest entries must match, or null to skip filtering
*/
private List<GenericData.Record> expectedEntries(
Table table,
FileContent expectedContent,
Schema entriesTableSchema,
List<ManifestFile> manifestsToExplore,
String partValue)
throws IOException {
List<GenericData.Record> expected = Lists.newArrayList();
for (ManifestFile manifest : manifestsToExplore) {
InputFile in = table.io().newInputFile(manifest.path());
try (CloseableIterable<GenericData.Record> rows =
Avro.read(in).project(entriesTableSchema).build()) {
for (GenericData.Record record : rows) {
if ((Integer) record.get("status") < 2 /* added or existing */) {
GenericData.Record file = (GenericData.Record) record.get("data_file");
if (partitionMatch(file, partValue)) {
asMetadataRecord(file, expectedContent);
expected.add(file);
}
}
}
}
}
return expected;
}
// Populate certain fields derived in the metadata tables
private void asMetadataRecord(GenericData.Record file, FileContent content) {
file.put(0, content.id());
file.put(3, 0); // specId
}
private boolean partitionMatch(GenericData.Record file, String partValue) {
if (partValue == null) {
return true;
}
GenericData.Record partition = (GenericData.Record) file.get(4);
return partValue.equals(partition.get(0).toString());
}
private List<ManifestFile> dataManifests(Table table) {
return table.currentSnapshot().dataManifests(table.io());
}
private List<ManifestFile> allDataManifests(Table table) {
List<ManifestFile> manifests = Lists.newArrayList();
for (Snapshot snapshot : table.snapshots()) {
manifests.addAll(snapshot.dataManifests(table.io()));
}
return manifests;
}
private List<ManifestFile> deleteManifests(Table table) {
return table.currentSnapshot().deleteManifests(table.io());
}
}
|
googleapis/google-cloud-java | 36,528 | java-container/proto-google-cloud-container-v1beta1/src/main/java/com/google/container/v1beta1/ListOperationsRequest.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/container/v1beta1/cluster_service.proto
// Protobuf Java Version: 3.25.8
package com.google.container.v1beta1;
/**
*
*
* <pre>
* ListOperationsRequest lists operations.
* </pre>
*
* Protobuf type {@code google.container.v1beta1.ListOperationsRequest}
*/
public final class ListOperationsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.container.v1beta1.ListOperationsRequest)
ListOperationsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListOperationsRequest.newBuilder() to construct.
private ListOperationsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListOperationsRequest() {
projectId_ = "";
zone_ = "";
parent_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListOperationsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.container.v1beta1.ClusterServiceProto
.internal_static_google_container_v1beta1_ListOperationsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.container.v1beta1.ClusterServiceProto
.internal_static_google_container_v1beta1_ListOperationsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.container.v1beta1.ListOperationsRequest.class,
com.google.container.v1beta1.ListOperationsRequest.Builder.class);
}
public static final int PROJECT_ID_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object projectId_ = "";
/**
*
*
* <pre>
* Deprecated. The Google Developers Console [project ID or project
* number](https://cloud.google.com/resource-manager/docs/creating-managing-projects).
* This field has been deprecated and replaced by the parent field.
* </pre>
*
* <code>string project_id = 1 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.ListOperationsRequest.project_id is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=4529
* @return The projectId.
*/
@java.lang.Override
@java.lang.Deprecated
public java.lang.String getProjectId() {
java.lang.Object ref = projectId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
projectId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Deprecated. The Google Developers Console [project ID or project
* number](https://cloud.google.com/resource-manager/docs/creating-managing-projects).
* This field has been deprecated and replaced by the parent field.
* </pre>
*
* <code>string project_id = 1 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.ListOperationsRequest.project_id is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=4529
* @return The bytes for projectId.
*/
@java.lang.Override
@java.lang.Deprecated
public com.google.protobuf.ByteString getProjectIdBytes() {
java.lang.Object ref = projectId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
projectId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ZONE_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object zone_ = "";
/**
*
*
* <pre>
* Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available)
* to return operations for, or `-` for all zones. This field has been
* deprecated and replaced by the parent field.
* </pre>
*
* <code>string zone = 2 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.ListOperationsRequest.zone is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=4535
* @return The zone.
*/
@java.lang.Override
@java.lang.Deprecated
public java.lang.String getZone() {
java.lang.Object ref = zone_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
zone_ = s;
return s;
}
}
/**
*
*
* <pre>
* Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available)
* to return operations for, or `-` for all zones. This field has been
* deprecated and replaced by the parent field.
* </pre>
*
* <code>string zone = 2 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.ListOperationsRequest.zone is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=4535
* @return The bytes for zone.
*/
@java.lang.Override
@java.lang.Deprecated
public com.google.protobuf.ByteString getZoneBytes() {
java.lang.Object ref = zone_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
zone_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PARENT_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* The parent (project and location) where the operations will be listed.
* Specified in the format `projects/*/locations/*`.
* Location "-" matches all zones and all regions.
* </pre>
*
* <code>string parent = 4;</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>
* The parent (project and location) where the operations will be listed.
* Specified in the format `projects/*/locations/*`.
* Location "-" matches all zones and all regions.
* </pre>
*
* <code>string parent = 4;</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;
}
}
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(projectId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, projectId_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(zone_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, zone_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, parent_);
}
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(projectId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, projectId_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(zone_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, zone_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, parent_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.container.v1beta1.ListOperationsRequest)) {
return super.equals(obj);
}
com.google.container.v1beta1.ListOperationsRequest other =
(com.google.container.v1beta1.ListOperationsRequest) obj;
if (!getProjectId().equals(other.getProjectId())) return false;
if (!getZone().equals(other.getZone())) return false;
if (!getParent().equals(other.getParent())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PROJECT_ID_FIELD_NUMBER;
hash = (53 * hash) + getProjectId().hashCode();
hash = (37 * hash) + ZONE_FIELD_NUMBER;
hash = (53 * hash) + getZone().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.container.v1beta1.ListOperationsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.container.v1beta1.ListOperationsRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.container.v1beta1.ListOperationsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.container.v1beta1.ListOperationsRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.container.v1beta1.ListOperationsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.container.v1beta1.ListOperationsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.container.v1beta1.ListOperationsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.container.v1beta1.ListOperationsRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.container.v1beta1.ListOperationsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.container.v1beta1.ListOperationsRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.container.v1beta1.ListOperationsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.container.v1beta1.ListOperationsRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.container.v1beta1.ListOperationsRequest 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>
* ListOperationsRequest lists operations.
* </pre>
*
* Protobuf type {@code google.container.v1beta1.ListOperationsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.container.v1beta1.ListOperationsRequest)
com.google.container.v1beta1.ListOperationsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.container.v1beta1.ClusterServiceProto
.internal_static_google_container_v1beta1_ListOperationsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.container.v1beta1.ClusterServiceProto
.internal_static_google_container_v1beta1_ListOperationsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.container.v1beta1.ListOperationsRequest.class,
com.google.container.v1beta1.ListOperationsRequest.Builder.class);
}
// Construct using com.google.container.v1beta1.ListOperationsRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
projectId_ = "";
zone_ = "";
parent_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.container.v1beta1.ClusterServiceProto
.internal_static_google_container_v1beta1_ListOperationsRequest_descriptor;
}
@java.lang.Override
public com.google.container.v1beta1.ListOperationsRequest getDefaultInstanceForType() {
return com.google.container.v1beta1.ListOperationsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.container.v1beta1.ListOperationsRequest build() {
com.google.container.v1beta1.ListOperationsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.container.v1beta1.ListOperationsRequest buildPartial() {
com.google.container.v1beta1.ListOperationsRequest result =
new com.google.container.v1beta1.ListOperationsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.container.v1beta1.ListOperationsRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.projectId_ = projectId_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.zone_ = zone_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.parent_ = parent_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.container.v1beta1.ListOperationsRequest) {
return mergeFrom((com.google.container.v1beta1.ListOperationsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.container.v1beta1.ListOperationsRequest other) {
if (other == com.google.container.v1beta1.ListOperationsRequest.getDefaultInstance())
return this;
if (!other.getProjectId().isEmpty()) {
projectId_ = other.projectId_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getZone().isEmpty()) {
zone_ = other.zone_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
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:
{
projectId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
zone_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 34:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 34
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object projectId_ = "";
/**
*
*
* <pre>
* Deprecated. The Google Developers Console [project ID or project
* number](https://cloud.google.com/resource-manager/docs/creating-managing-projects).
* This field has been deprecated and replaced by the parent field.
* </pre>
*
* <code>string project_id = 1 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.ListOperationsRequest.project_id is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=4529
* @return The projectId.
*/
@java.lang.Deprecated
public java.lang.String getProjectId() {
java.lang.Object ref = projectId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
projectId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Deprecated. The Google Developers Console [project ID or project
* number](https://cloud.google.com/resource-manager/docs/creating-managing-projects).
* This field has been deprecated and replaced by the parent field.
* </pre>
*
* <code>string project_id = 1 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.ListOperationsRequest.project_id is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=4529
* @return The bytes for projectId.
*/
@java.lang.Deprecated
public com.google.protobuf.ByteString getProjectIdBytes() {
java.lang.Object ref = projectId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
projectId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Deprecated. The Google Developers Console [project ID or project
* number](https://cloud.google.com/resource-manager/docs/creating-managing-projects).
* This field has been deprecated and replaced by the parent field.
* </pre>
*
* <code>string project_id = 1 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.ListOperationsRequest.project_id is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=4529
* @param value The projectId to set.
* @return This builder for chaining.
*/
@java.lang.Deprecated
public Builder setProjectId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
projectId_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Deprecated. The Google Developers Console [project ID or project
* number](https://cloud.google.com/resource-manager/docs/creating-managing-projects).
* This field has been deprecated and replaced by the parent field.
* </pre>
*
* <code>string project_id = 1 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.ListOperationsRequest.project_id is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=4529
* @return This builder for chaining.
*/
@java.lang.Deprecated
public Builder clearProjectId() {
projectId_ = getDefaultInstance().getProjectId();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Deprecated. The Google Developers Console [project ID or project
* number](https://cloud.google.com/resource-manager/docs/creating-managing-projects).
* This field has been deprecated and replaced by the parent field.
* </pre>
*
* <code>string project_id = 1 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.ListOperationsRequest.project_id is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=4529
* @param value The bytes for projectId to set.
* @return This builder for chaining.
*/
@java.lang.Deprecated
public Builder setProjectIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
projectId_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object zone_ = "";
/**
*
*
* <pre>
* Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available)
* to return operations for, or `-` for all zones. This field has been
* deprecated and replaced by the parent field.
* </pre>
*
* <code>string zone = 2 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.ListOperationsRequest.zone is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=4535
* @return The zone.
*/
@java.lang.Deprecated
public java.lang.String getZone() {
java.lang.Object ref = zone_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
zone_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available)
* to return operations for, or `-` for all zones. This field has been
* deprecated and replaced by the parent field.
* </pre>
*
* <code>string zone = 2 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.ListOperationsRequest.zone is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=4535
* @return The bytes for zone.
*/
@java.lang.Deprecated
public com.google.protobuf.ByteString getZoneBytes() {
java.lang.Object ref = zone_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
zone_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available)
* to return operations for, or `-` for all zones. This field has been
* deprecated and replaced by the parent field.
* </pre>
*
* <code>string zone = 2 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.ListOperationsRequest.zone is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=4535
* @param value The zone to set.
* @return This builder for chaining.
*/
@java.lang.Deprecated
public Builder setZone(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
zone_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available)
* to return operations for, or `-` for all zones. This field has been
* deprecated and replaced by the parent field.
* </pre>
*
* <code>string zone = 2 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.ListOperationsRequest.zone is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=4535
* @return This builder for chaining.
*/
@java.lang.Deprecated
public Builder clearZone() {
zone_ = getDefaultInstance().getZone();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Deprecated. The name of the Google Compute Engine
* [zone](https://cloud.google.com/compute/docs/zones#available)
* to return operations for, or `-` for all zones. This field has been
* deprecated and replaced by the parent field.
* </pre>
*
* <code>string zone = 2 [deprecated = true];</code>
*
* @deprecated google.container.v1beta1.ListOperationsRequest.zone is deprecated. See
* google/container/v1beta1/cluster_service.proto;l=4535
* @param value The bytes for zone to set.
* @return This builder for chaining.
*/
@java.lang.Deprecated
public Builder setZoneBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
zone_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* The parent (project and location) where the operations will be listed.
* Specified in the format `projects/*/locations/*`.
* Location "-" matches all zones and all regions.
* </pre>
*
* <code>string parent = 4;</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>
* The parent (project and location) where the operations will be listed.
* Specified in the format `projects/*/locations/*`.
* Location "-" matches all zones and all regions.
* </pre>
*
* <code>string parent = 4;</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>
* The parent (project and location) where the operations will be listed.
* Specified in the format `projects/*/locations/*`.
* Location "-" matches all zones and all regions.
* </pre>
*
* <code>string parent = 4;</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_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The parent (project and location) where the operations will be listed.
* Specified in the format `projects/*/locations/*`.
* Location "-" matches all zones and all regions.
* </pre>
*
* <code>string parent = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* The parent (project and location) where the operations will be listed.
* Specified in the format `projects/*/locations/*`.
* Location "-" matches all zones and all regions.
* </pre>
*
* <code>string parent = 4;</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_ |= 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.container.v1beta1.ListOperationsRequest)
}
// @@protoc_insertion_point(class_scope:google.container.v1beta1.ListOperationsRequest)
private static final com.google.container.v1beta1.ListOperationsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.container.v1beta1.ListOperationsRequest();
}
public static com.google.container.v1beta1.ListOperationsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListOperationsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListOperationsRequest>() {
@java.lang.Override
public ListOperationsRequest 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<ListOperationsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListOperationsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.container.v1beta1.ListOperationsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/iceberg | 36,519 | flink/v1.20/flink/src/test/java/org/apache/iceberg/flink/source/TestFlinkMetaDataTable.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.iceberg.flink.source;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assumptions.assumeThat;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.avro.generic.GenericData;
import org.apache.commons.collections.ListUtils;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.CoreOptions;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.types.Row;
import org.apache.iceberg.DeleteFile;
import org.apache.iceberg.FileContent;
import org.apache.iceberg.FileFormat;
import org.apache.iceberg.Files;
import org.apache.iceberg.HasTableOperations;
import org.apache.iceberg.ManifestFile;
import org.apache.iceberg.MetadataTableType;
import org.apache.iceberg.MetadataTableUtils;
import org.apache.iceberg.MetricsUtil;
import org.apache.iceberg.Parameter;
import org.apache.iceberg.Parameters;
import org.apache.iceberg.Schema;
import org.apache.iceberg.Snapshot;
import org.apache.iceberg.Table;
import org.apache.iceberg.TableMetadata;
import org.apache.iceberg.avro.Avro;
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.catalog.TableIdentifier;
import org.apache.iceberg.data.FileHelpers;
import org.apache.iceberg.data.GenericRecord;
import org.apache.iceberg.data.Record;
import org.apache.iceberg.expressions.Expressions;
import org.apache.iceberg.flink.CatalogTestBase;
import org.apache.iceberg.flink.TestHelpers;
import org.apache.iceberg.io.CloseableIterable;
import org.apache.iceberg.io.InputFile;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
import org.apache.iceberg.relocated.com.google.common.collect.Maps;
import org.apache.iceberg.types.Types;
import org.apache.iceberg.util.SnapshotUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.io.TempDir;
public class TestFlinkMetaDataTable extends CatalogTestBase {
private static final String TABLE_NAME = "test_table";
private final FileFormat format = FileFormat.AVRO;
private @TempDir Path temp;
@Parameter(index = 2)
private Boolean isPartition;
@Parameters(name = "catalogName={0}, baseNamespace={1}, isPartition={2}")
protected static List<Object[]> parameters() {
List<Object[]> parameters = Lists.newArrayList();
for (Boolean isPartition : new Boolean[] {true, false}) {
String catalogName = "testhadoop";
Namespace baseNamespace = Namespace.of("default");
parameters.add(new Object[] {catalogName, baseNamespace, isPartition});
}
return parameters;
}
@Override
protected TableEnvironment getTableEnv() {
Configuration configuration = super.getTableEnv().getConfig().getConfiguration();
configuration.set(CoreOptions.DEFAULT_PARALLELISM, 1);
return super.getTableEnv();
}
@BeforeEach
public void before() {
super.before();
sql("USE CATALOG %s", catalogName);
sql("CREATE DATABASE %s", flinkDatabase);
sql("USE %s", DATABASE);
if (isPartition) {
sql(
"CREATE TABLE %s (id INT, data VARCHAR,d DOUBLE) PARTITIONED BY (data) WITH ('format-version'='2', 'write.format.default'='%s')",
TABLE_NAME, format.name());
sql("INSERT INTO %s VALUES (1,'a',10),(2,'a',20)", TABLE_NAME);
sql("INSERT INTO %s VALUES (1,'b',10),(2,'b',20)", TABLE_NAME);
} else {
sql(
"CREATE TABLE %s (id INT, data VARCHAR,d DOUBLE) WITH ('format-version'='2', 'write.format.default'='%s')",
TABLE_NAME, format.name());
sql(
"INSERT INTO %s VALUES (1,'iceberg',10),(2,'b',20),(3,CAST(NULL AS VARCHAR),30)",
TABLE_NAME);
sql("INSERT INTO %s VALUES (4,'iceberg',10)", TABLE_NAME);
}
}
@Override
@AfterEach
public void clean() {
sql("DROP TABLE IF EXISTS %s.%s", flinkDatabase, TABLE_NAME);
dropDatabase(flinkDatabase, true);
super.clean();
}
@TestTemplate
public void testSnapshots() {
String sql = String.format("SELECT * FROM %s$snapshots ", TABLE_NAME);
List<Row> result = sql(sql);
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Iterator<Snapshot> snapshots = table.snapshots().iterator();
for (Row row : result) {
Snapshot next = snapshots.next();
assertThat(((Instant) row.getField(0)).toEpochMilli())
.as("Should have expected timestamp")
.isEqualTo(next.timestampMillis());
assertThat(next.snapshotId())
.as("Should have expected snapshot id")
.isEqualTo(next.snapshotId());
assertThat(row.getField(2)).as("Should have expected parent id").isEqualTo(next.parentId());
assertThat(row.getField(3)).as("Should have expected operation").isEqualTo(next.operation());
assertThat(row.getField(4))
.as("Should have expected manifest list location")
.isEqualTo(next.manifestListLocation());
assertThat(row.getField(5)).as("Should have expected summary").isEqualTo(next.summary());
}
}
@TestTemplate
public void testHistory() {
String sql = String.format("SELECT * FROM %s$history ", TABLE_NAME);
List<Row> result = sql(sql);
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Iterator<Snapshot> snapshots = table.snapshots().iterator();
for (Row row : result) {
Snapshot next = snapshots.next();
assertThat(((Instant) row.getField(0)).toEpochMilli())
.as("Should have expected made_current_at")
.isEqualTo(next.timestampMillis());
assertThat(row.getField(1))
.as("Should have expected snapshot id")
.isEqualTo(next.snapshotId());
assertThat(row.getField(2)).as("Should have expected parent id").isEqualTo(next.parentId());
assertThat(row.getField(3))
.as("Should have expected is current ancestor")
.isEqualTo(
SnapshotUtil.isAncestorOf(
table, table.currentSnapshot().snapshotId(), next.snapshotId()));
}
}
@TestTemplate
public void testManifests() {
String sql = String.format("SELECT * FROM %s$manifests ", TABLE_NAME);
List<Row> result = sql(sql);
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
List<ManifestFile> expectedDataManifests = dataManifests(table);
for (int i = 0; i < result.size(); i++) {
Row row = result.get(i);
ManifestFile manifestFile = expectedDataManifests.get(i);
assertThat(row.getField(0))
.as("Should have expected content")
.isEqualTo(manifestFile.content().id());
assertThat(row.getField(1)).as("Should have expected path").isEqualTo(manifestFile.path());
assertThat(row.getField(2))
.as("Should have expected length")
.isEqualTo(manifestFile.length());
assertThat(row.getField(3))
.as("Should have expected partition_spec_id")
.isEqualTo(manifestFile.partitionSpecId());
assertThat(row.getField(4))
.as("Should have expected added_snapshot_id")
.isEqualTo(manifestFile.snapshotId());
assertThat(row.getField(5))
.as("Should have expected added_data_files_count")
.isEqualTo(manifestFile.addedFilesCount());
assertThat(row.getField(6))
.as("Should have expected existing_data_files_count")
.isEqualTo(manifestFile.existingFilesCount());
assertThat(row.getField(7))
.as("Should have expected deleted_data_files_count")
.isEqualTo(manifestFile.deletedFilesCount());
}
}
@TestTemplate
public void testAllManifests() {
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
String sql = String.format("SELECT * FROM %s$all_manifests ", TABLE_NAME);
List<Row> result = sql(sql);
List<ManifestFile> expectedDataManifests = allDataManifests(table);
assertThat(expectedDataManifests).hasSize(result.size());
for (int i = 0; i < result.size(); i++) {
Row row = result.get(i);
ManifestFile manifestFile = expectedDataManifests.get(i);
assertThat(row.getField(0))
.as("Should have expected content")
.isEqualTo(manifestFile.content().id());
assertThat(row.getField(1)).as("Should have expected path").isEqualTo(manifestFile.path());
assertThat(row.getField(2))
.as("Should have expected length")
.isEqualTo(manifestFile.length());
assertThat(row.getField(3))
.as("Should have expected partition_spec_id")
.isEqualTo(manifestFile.partitionSpecId());
assertThat(row.getField(4))
.as("Should have expected added_snapshot_id")
.isEqualTo(manifestFile.snapshotId());
assertThat(row.getField(5))
.as("Should have expected added_data_files_count")
.isEqualTo(manifestFile.addedFilesCount());
assertThat(row.getField(6))
.as("Should have expected existing_data_files_count")
.isEqualTo(manifestFile.existingFilesCount());
assertThat(row.getField(7))
.as("Should have expected deleted_data_files_count")
.isEqualTo(manifestFile.deletedFilesCount());
}
}
@TestTemplate
public void testUnPartitionedTable() throws IOException {
assumeThat(isPartition).isFalse();
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Schema deleteRowSchema = table.schema().select("id");
Record dataDelete = GenericRecord.create(deleteRowSchema);
List<Record> dataDeletes = Lists.newArrayList(dataDelete.copy("id", 1));
File testFile = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes =
FileHelpers.writeDeleteFile(
table, Files.localOutput(testFile), dataDeletes, deleteRowSchema);
table.newRowDelta().addDeletes(eqDeletes).commit();
List<ManifestFile> expectedDataManifests = dataManifests(table);
List<ManifestFile> expectedDeleteManifests = deleteManifests(table);
assertThat(expectedDataManifests).hasSize(2);
assertThat(expectedDeleteManifests).hasSize(1);
Schema entriesTableSchema =
MetadataTableUtils.createMetadataTableInstance(table, MetadataTableType.from("entries"))
.schema();
// check delete files table
Schema deleteFilesTableSchema =
MetadataTableUtils.createMetadataTableInstance(
table, MetadataTableType.from("delete_files"))
.schema();
List<String> deleteColumns =
deleteFilesTableSchema.columns().stream()
.map(Types.NestedField::name)
.filter(c -> !c.equals(MetricsUtil.READABLE_METRICS))
.collect(Collectors.toList());
String deleteNames =
deleteColumns.stream().map(n -> "`" + n + "`").collect(Collectors.joining(","));
deleteFilesTableSchema = deleteFilesTableSchema.select(deleteColumns);
List<Row> actualDeleteFiles = sql("SELECT %s FROM %s$delete_files", deleteNames, TABLE_NAME);
assertThat(actualDeleteFiles).hasSize(1);
assertThat(expectedDeleteManifests).as("Should have 1 delete manifest").hasSize(1);
List<GenericData.Record> expectedDeleteFiles =
expectedEntries(
table, FileContent.EQUALITY_DELETES, entriesTableSchema, expectedDeleteManifests, null);
assertThat(expectedDeleteFiles).as("Should be 1 delete file manifest entry").hasSize(1);
TestHelpers.assertEquals(
deleteFilesTableSchema, expectedDeleteFiles.get(0), actualDeleteFiles.get(0));
// Check data files table
Schema filesTableSchema =
MetadataTableUtils.createMetadataTableInstance(table, MetadataTableType.from("files"))
.schema();
List<String> columns =
filesTableSchema.columns().stream()
.map(Types.NestedField::name)
.filter(c -> !c.equals(MetricsUtil.READABLE_METRICS))
.collect(Collectors.toList());
String names = columns.stream().map(n -> "`" + n + "`").collect(Collectors.joining(","));
filesTableSchema = filesTableSchema.select(columns);
List<Row> actualDataFiles = sql("SELECT %s FROM %s$data_files", names, TABLE_NAME);
assertThat(actualDataFiles).as("Metadata table should return 2 data file").hasSize(2);
List<GenericData.Record> expectedDataFiles =
expectedEntries(table, FileContent.DATA, entriesTableSchema, expectedDataManifests, null);
assertThat(expectedDataFiles).as("Should be 2 data file manifest entry").hasSize(2);
TestHelpers.assertEquals(filesTableSchema, expectedDataFiles.get(0), actualDataFiles.get(0));
// check all files table
List<Row> actualFiles = sql("SELECT %s FROM %s$files ORDER BY content", names, TABLE_NAME);
assertThat(actualFiles).as("Metadata table should return 3 files").hasSize(3);
List<GenericData.Record> expectedFiles =
Stream.concat(expectedDataFiles.stream(), expectedDeleteFiles.stream())
.collect(Collectors.toList());
assertThat(expectedFiles).as("Should have 3 files manifest entriess").hasSize(3);
TestHelpers.assertEquals(filesTableSchema, expectedFiles.get(0), actualFiles.get(0));
TestHelpers.assertEquals(filesTableSchema, expectedFiles.get(1), actualFiles.get(1));
}
@TestTemplate
public void testPartitionedTable() throws Exception {
assumeThat(isPartition).isTrue();
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Schema deleteRowSchema = table.schema().select("id", "data");
Record dataDelete = GenericRecord.create(deleteRowSchema);
Map<String, Object> deleteRow = Maps.newHashMap();
deleteRow.put("id", 1);
deleteRow.put("data", "a");
File testFile = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes =
FileHelpers.writeDeleteFile(
table,
Files.localOutput(testFile),
org.apache.iceberg.TestHelpers.Row.of("a"),
Lists.newArrayList(dataDelete.copy(deleteRow)),
deleteRowSchema);
table.newRowDelta().addDeletes(eqDeletes).commit();
deleteRow.put("data", "b");
File testFile2 = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes2 =
FileHelpers.writeDeleteFile(
table,
Files.localOutput(testFile2),
org.apache.iceberg.TestHelpers.Row.of("b"),
Lists.newArrayList(dataDelete.copy(deleteRow)),
deleteRowSchema);
table.newRowDelta().addDeletes(eqDeletes2).commit();
Schema entriesTableSchema =
MetadataTableUtils.createMetadataTableInstance(table, MetadataTableType.from("entries"))
.schema();
List<ManifestFile> expectedDataManifests = dataManifests(table);
List<ManifestFile> expectedDeleteManifests = deleteManifests(table);
assertThat(expectedDataManifests).hasSize(2);
assertThat(expectedDeleteManifests).hasSize(2);
Table deleteFilesTable =
MetadataTableUtils.createMetadataTableInstance(
table, MetadataTableType.from("delete_files"));
Schema filesTableSchema = deleteFilesTable.schema();
List<String> columns =
filesTableSchema.columns().stream()
.map(Types.NestedField::name)
.filter(c -> !c.equals(MetricsUtil.READABLE_METRICS))
.collect(Collectors.toList());
String names = columns.stream().map(n -> "`" + n + "`").collect(Collectors.joining(","));
filesTableSchema = filesTableSchema.select(columns);
// Check delete files table
List<GenericData.Record> expectedDeleteFiles =
expectedEntries(
table, FileContent.EQUALITY_DELETES, entriesTableSchema, expectedDeleteManifests, "a");
assertThat(expectedDeleteFiles).hasSize(1);
List<Row> actualDeleteFiles =
sql("SELECT %s FROM %s$delete_files WHERE `partition`.`data`='a'", names, TABLE_NAME);
assertThat(actualDeleteFiles).hasSize(1);
TestHelpers.assertEquals(
filesTableSchema, expectedDeleteFiles.get(0), actualDeleteFiles.get(0));
// Check data files table
List<GenericData.Record> expectedDataFiles =
expectedEntries(table, FileContent.DATA, entriesTableSchema, expectedDataManifests, "a");
assertThat(expectedDataFiles).hasSize(1);
List<Row> actualDataFiles =
sql("SELECT %s FROM %s$data_files WHERE `partition`.`data`='a'", names, TABLE_NAME);
assertThat(actualDataFiles).hasSize(1);
TestHelpers.assertEquals(filesTableSchema, expectedDataFiles.get(0), actualDataFiles.get(0));
List<Row> actualPartitionsWithProjection =
sql("SELECT file_count FROM %s$partitions ", TABLE_NAME);
assertThat(actualPartitionsWithProjection).hasSize(2);
for (int i = 0; i < 2; ++i) {
assertThat(actualPartitionsWithProjection.get(i).getField(0)).isEqualTo(1);
}
// Check files table
List<GenericData.Record> expectedFiles =
Stream.concat(expectedDataFiles.stream(), expectedDeleteFiles.stream())
.collect(Collectors.toList());
assertThat(expectedFiles).hasSize(2);
List<Row> actualFiles =
sql(
"SELECT %s FROM %s$files WHERE `partition`.`data`='a' ORDER BY content",
names, TABLE_NAME);
assertThat(actualFiles).hasSize(2);
TestHelpers.assertEquals(filesTableSchema, expectedFiles.get(0), actualFiles.get(0));
TestHelpers.assertEquals(filesTableSchema, expectedFiles.get(1), actualFiles.get(1));
}
@TestTemplate
public void testAllFilesUnpartitioned() throws Exception {
assumeThat(isPartition).isFalse();
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Schema deleteRowSchema = table.schema().select("id", "data");
Record dataDelete = GenericRecord.create(deleteRowSchema);
Map<String, Object> deleteRow = Maps.newHashMap();
deleteRow.put("id", 1);
File testFile = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes =
FileHelpers.writeDeleteFile(
table,
Files.localOutput(testFile),
Lists.newArrayList(dataDelete.copy(deleteRow)),
deleteRowSchema);
table.newRowDelta().addDeletes(eqDeletes).commit();
List<ManifestFile> expectedDataManifests = dataManifests(table);
assertThat(expectedDataManifests).hasSize(2);
List<ManifestFile> expectedDeleteManifests = deleteManifests(table);
assertThat(expectedDeleteManifests).hasSize(1);
// Clear table to test whether 'all_files' can read past files
table.newDelete().deleteFromRowFilter(Expressions.alwaysTrue()).commit();
Schema entriesTableSchema =
MetadataTableUtils.createMetadataTableInstance(table, MetadataTableType.from("entries"))
.schema();
Schema filesTableSchema =
MetadataTableUtils.createMetadataTableInstance(
table, MetadataTableType.from("all_data_files"))
.schema();
List<String> columns =
filesTableSchema.columns().stream()
.map(Types.NestedField::name)
.filter(c -> !c.equals(MetricsUtil.READABLE_METRICS))
.collect(Collectors.toList());
String names = columns.stream().map(n -> "`" + n + "`").collect(Collectors.joining(","));
filesTableSchema = filesTableSchema.select(columns);
// Check all data files table
List<Row> actualDataFiles =
sql("SELECT %s FROM %s$all_data_files order by record_count ", names, TABLE_NAME);
List<GenericData.Record> expectedDataFiles =
expectedEntries(table, FileContent.DATA, entriesTableSchema, expectedDataManifests, null);
assertThat(expectedDataFiles).hasSize(2);
assertThat(actualDataFiles).hasSize(2);
TestHelpers.assertEquals(filesTableSchema, expectedDataFiles, actualDataFiles);
// Check all delete files table
List<Row> actualDeleteFiles = sql("SELECT %s FROM %s$all_delete_files", names, TABLE_NAME);
List<GenericData.Record> expectedDeleteFiles =
expectedEntries(
table, FileContent.EQUALITY_DELETES, entriesTableSchema, expectedDeleteManifests, null);
assertThat(expectedDeleteFiles).hasSize(1);
assertThat(actualDeleteFiles).hasSize(1);
TestHelpers.assertEquals(
filesTableSchema, expectedDeleteFiles.get(0), actualDeleteFiles.get(0));
// Check all files table
List<Row> actualFiles =
sql("SELECT %s FROM %s$all_files ORDER BY content, record_count asc", names, TABLE_NAME);
List<GenericData.Record> expectedFiles =
ListUtils.union(expectedDataFiles, expectedDeleteFiles);
expectedFiles.sort(Comparator.comparing(r -> ((Integer) r.get("content"))));
assertThat(actualFiles).hasSize(3);
TestHelpers.assertEquals(filesTableSchema, expectedFiles, actualFiles);
}
@TestTemplate
public void testAllFilesPartitioned() throws Exception {
assumeThat(!isPartition).isFalse();
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
// Create delete file
Schema deleteRowSchema = table.schema().select("id");
Record dataDelete = GenericRecord.create(deleteRowSchema);
Map<String, Object> deleteRow = Maps.newHashMap();
deleteRow.put("id", 1);
File testFile = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes =
FileHelpers.writeDeleteFile(
table,
Files.localOutput(testFile),
org.apache.iceberg.TestHelpers.Row.of("a"),
Lists.newArrayList(dataDelete.copy(deleteRow)),
deleteRowSchema);
File testFile2 = File.createTempFile("junit", null, temp.toFile());
DeleteFile eqDeletes2 =
FileHelpers.writeDeleteFile(
table,
Files.localOutput(testFile2),
org.apache.iceberg.TestHelpers.Row.of("b"),
Lists.newArrayList(dataDelete.copy(deleteRow)),
deleteRowSchema);
table.newRowDelta().addDeletes(eqDeletes).addDeletes(eqDeletes2).commit();
List<ManifestFile> expectedDataManifests = dataManifests(table);
assertThat(expectedDataManifests).hasSize(2);
List<ManifestFile> expectedDeleteManifests = deleteManifests(table);
assertThat(expectedDeleteManifests).hasSize(1);
// Clear table to test whether 'all_files' can read past files
table.newDelete().deleteFromRowFilter(Expressions.alwaysTrue()).commit();
Schema entriesTableSchema =
MetadataTableUtils.createMetadataTableInstance(table, MetadataTableType.from("entries"))
.schema();
Schema filesTableSchema =
MetadataTableUtils.createMetadataTableInstance(
table, MetadataTableType.from("all_data_files"))
.schema();
List<String> columns =
filesTableSchema.columns().stream()
.map(Types.NestedField::name)
.filter(c -> !c.equals(MetricsUtil.READABLE_METRICS))
.collect(Collectors.toList());
String names = columns.stream().map(n -> "`" + n + "`").collect(Collectors.joining(","));
filesTableSchema = filesTableSchema.select(columns);
// Check all data files table
List<Row> actualDataFiles =
sql("SELECT %s FROM %s$all_data_files WHERE `partition`.`data`='a'", names, TABLE_NAME);
List<GenericData.Record> expectedDataFiles =
expectedEntries(table, FileContent.DATA, entriesTableSchema, expectedDataManifests, "a");
assertThat(expectedDataFiles).hasSize(1);
assertThat(actualDataFiles).hasSize(1);
TestHelpers.assertEquals(filesTableSchema, expectedDataFiles.get(0), actualDataFiles.get(0));
// Check all delete files table
List<Row> actualDeleteFiles =
sql("SELECT %s FROM %s$all_delete_files WHERE `partition`.`data`='a'", names, TABLE_NAME);
List<GenericData.Record> expectedDeleteFiles =
expectedEntries(
table, FileContent.EQUALITY_DELETES, entriesTableSchema, expectedDeleteManifests, "a");
assertThat(expectedDeleteFiles).hasSize(1);
assertThat(actualDeleteFiles).hasSize(1);
TestHelpers.assertEquals(
filesTableSchema, expectedDeleteFiles.get(0), actualDeleteFiles.get(0));
// Check all files table
List<Row> actualFiles =
sql(
"SELECT %s FROM %s$all_files WHERE `partition`.`data`='a' ORDER BY content",
names, TABLE_NAME);
List<GenericData.Record> expectedFiles =
ListUtils.union(expectedDataFiles, expectedDeleteFiles);
expectedFiles.sort(Comparator.comparing(r -> ((Integer) r.get("content"))));
assertThat(actualFiles).hasSize(2);
TestHelpers.assertEquals(filesTableSchema, expectedFiles, actualFiles);
}
@TestTemplate
public void testMetadataLogEntries() {
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Long currentSnapshotId = table.currentSnapshot().snapshotId();
TableMetadata tableMetadata = ((HasTableOperations) table).operations().current();
Snapshot currentSnapshot = tableMetadata.currentSnapshot();
Snapshot parentSnapshot = table.snapshot(currentSnapshot.parentId());
List<TableMetadata.MetadataLogEntry> metadataLogEntries =
Lists.newArrayList(tableMetadata.previousFiles());
// Check metadataLog table
List<Row> metadataLogs = sql("SELECT * FROM %s$metadata_log_entries", TABLE_NAME);
assertThat(metadataLogs).hasSize(3);
Row metadataLog = metadataLogs.get(0);
assertThat(metadataLog.getField("timestamp"))
.isEqualTo(Instant.ofEpochMilli(metadataLogEntries.get(0).timestampMillis()));
assertThat(metadataLog.getField("file")).isEqualTo(metadataLogEntries.get(0).file());
assertThat(metadataLog.getField("latest_snapshot_id")).isNull();
assertThat(metadataLog.getField("latest_schema_id")).isNull();
assertThat(metadataLog.getField("latest_sequence_number")).isNull();
metadataLog = metadataLogs.get(1);
assertThat(metadataLog.getField("timestamp"))
.isEqualTo(Instant.ofEpochMilli(metadataLogEntries.get(1).timestampMillis()));
assertThat(metadataLog.getField("file")).isEqualTo(metadataLogEntries.get(1).file());
assertThat(metadataLog.getField("latest_snapshot_id")).isEqualTo(parentSnapshot.snapshotId());
assertThat(metadataLog.getField("latest_schema_id")).isEqualTo(parentSnapshot.schemaId());
assertThat(metadataLog.getField("latest_sequence_number"))
.isEqualTo(parentSnapshot.sequenceNumber());
assertThat(metadataLog.getField("latest_snapshot_id")).isEqualTo(parentSnapshot.snapshotId());
metadataLog = metadataLogs.get(2);
assertThat(metadataLog.getField("timestamp"))
.isEqualTo(Instant.ofEpochMilli(currentSnapshot.timestampMillis()));
assertThat(metadataLog.getField("file")).isEqualTo(tableMetadata.metadataFileLocation());
assertThat(metadataLog.getField("latest_snapshot_id")).isEqualTo(currentSnapshot.snapshotId());
assertThat(metadataLog.getField("latest_schema_id")).isEqualTo(currentSnapshot.schemaId());
assertThat(metadataLog.getField("latest_sequence_number"))
.isEqualTo(currentSnapshot.sequenceNumber());
// test filtering
List<Row> metadataLogWithFilters =
sql(
"SELECT * FROM %s$metadata_log_entries WHERE latest_snapshot_id = %s",
TABLE_NAME, currentSnapshotId);
assertThat(metadataLogWithFilters).hasSize(1);
metadataLog = metadataLogWithFilters.get(0);
assertThat(Instant.ofEpochMilli(tableMetadata.currentSnapshot().timestampMillis()))
.isEqualTo(metadataLog.getField("timestamp"));
assertThat(metadataLog.getField("file")).isEqualTo(tableMetadata.metadataFileLocation());
assertThat(metadataLog.getField("latest_snapshot_id"))
.isEqualTo(tableMetadata.currentSnapshot().snapshotId());
assertThat(metadataLog.getField("latest_schema_id"))
.isEqualTo(tableMetadata.currentSnapshot().schemaId());
assertThat(metadataLog.getField("latest_sequence_number"))
.isEqualTo(tableMetadata.currentSnapshot().sequenceNumber());
// test projection
List<String> metadataFiles =
metadataLogEntries.stream()
.map(TableMetadata.MetadataLogEntry::file)
.collect(Collectors.toList());
metadataFiles.add(tableMetadata.metadataFileLocation());
List<Row> metadataLogWithProjection =
sql("SELECT file FROM %s$metadata_log_entries", TABLE_NAME);
assertThat(metadataLogWithProjection).hasSize(3);
for (int i = 0; i < metadataFiles.size(); i++) {
assertThat(metadataLogWithProjection.get(i).getField("file")).isEqualTo(metadataFiles.get(i));
}
}
@TestTemplate
public void testSnapshotReferencesMetatable() {
Table table = validationCatalog.loadTable(TableIdentifier.of(icebergNamespace, TABLE_NAME));
Long currentSnapshotId = table.currentSnapshot().snapshotId();
// Create branch
table
.manageSnapshots()
.createBranch("testBranch", currentSnapshotId)
.setMaxRefAgeMs("testBranch", 10)
.setMinSnapshotsToKeep("testBranch", 20)
.setMaxSnapshotAgeMs("testBranch", 30)
.commit();
// Create Tag
table
.manageSnapshots()
.createTag("testTag", currentSnapshotId)
.setMaxRefAgeMs("testTag", 50)
.commit();
// Check refs table
List<Row> references = sql("SELECT * FROM %s$refs", TABLE_NAME);
List<Row> branches = sql("SELECT * FROM %s$refs WHERE type='BRANCH'", TABLE_NAME);
assertThat(references).hasSize(3);
assertThat(branches).hasSize(2);
List<Row> tags = sql("SELECT * FROM %s$refs WHERE type='TAG'", TABLE_NAME);
assertThat(tags).hasSize(1);
// Check branch entries in refs table
List<Row> mainBranch =
sql("SELECT * FROM %s$refs WHERE name='main' AND type='BRANCH'", TABLE_NAME);
assertThat((String) mainBranch.get(0).getFieldAs("name")).isEqualTo("main");
assertThat((String) mainBranch.get(0).getFieldAs("type")).isEqualTo("BRANCH");
assertThat((Long) mainBranch.get(0).getFieldAs("snapshot_id")).isEqualTo(currentSnapshotId);
List<Row> testBranch =
sql("SELECT * FROM %s$refs WHERE name='testBranch' AND type='BRANCH'", TABLE_NAME);
assertThat((String) testBranch.get(0).getFieldAs("name")).isEqualTo("testBranch");
assertThat((String) testBranch.get(0).getFieldAs("type")).isEqualTo("BRANCH");
assertThat((Long) testBranch.get(0).getFieldAs("snapshot_id")).isEqualTo(currentSnapshotId);
assertThat((Long) testBranch.get(0).getFieldAs("max_reference_age_in_ms"))
.isEqualTo(Long.valueOf(10));
assertThat((Integer) testBranch.get(0).getFieldAs("min_snapshots_to_keep"))
.isEqualTo(Integer.valueOf(20));
assertThat((Long) testBranch.get(0).getFieldAs("max_snapshot_age_in_ms"))
.isEqualTo(Long.valueOf(30));
// Check tag entries in refs table
List<Row> testTag =
sql("SELECT * FROM %s$refs WHERE name='testTag' AND type='TAG'", TABLE_NAME);
assertThat((String) testTag.get(0).getFieldAs("name")).isEqualTo("testTag");
assertThat((String) testTag.get(0).getFieldAs("type")).isEqualTo("TAG");
assertThat((Long) testTag.get(0).getFieldAs("snapshot_id")).isEqualTo(currentSnapshotId);
assertThat((Long) testTag.get(0).getFieldAs("max_reference_age_in_ms"))
.isEqualTo(Long.valueOf(50));
// Check projection in refs table
List<Row> testTagProjection =
sql(
"SELECT name,type,snapshot_id,max_reference_age_in_ms,min_snapshots_to_keep FROM %s$refs where type='TAG'",
TABLE_NAME);
assertThat((String) testTagProjection.get(0).getFieldAs("name")).isEqualTo("testTag");
assertThat((String) testTagProjection.get(0).getFieldAs("type")).isEqualTo("TAG");
assertThat((Long) testTagProjection.get(0).getFieldAs("snapshot_id"))
.isEqualTo(currentSnapshotId);
assertThat((Long) testTagProjection.get(0).getFieldAs("max_reference_age_in_ms"))
.isEqualTo(Long.valueOf(50));
assertThat((String) testTagProjection.get(0).getFieldAs("min_snapshots_to_keep")).isNull();
List<Row> mainBranchProjection =
sql("SELECT name, type FROM %s$refs WHERE name='main' AND type = 'BRANCH'", TABLE_NAME);
assertThat((String) mainBranchProjection.get(0).getFieldAs("name")).isEqualTo("main");
assertThat((String) mainBranchProjection.get(0).getFieldAs("type")).isEqualTo("BRANCH");
List<Row> testBranchProjection =
sql(
"SELECT type, name, max_reference_age_in_ms, snapshot_id FROM %s$refs WHERE name='testBranch' AND type = 'BRANCH'",
TABLE_NAME);
assertThat((String) testBranchProjection.get(0).getFieldAs("name")).isEqualTo("testBranch");
assertThat((String) testBranchProjection.get(0).getFieldAs("type")).isEqualTo("BRANCH");
assertThat((Long) testBranchProjection.get(0).getFieldAs("snapshot_id"))
.isEqualTo(currentSnapshotId);
assertThat((Long) testBranchProjection.get(0).getFieldAs("max_reference_age_in_ms"))
.isEqualTo(Long.valueOf(10));
}
/**
* Find matching manifest entries of an Iceberg table
*
* @param table iceberg table
* @param expectedContent file content to populate on entries
* @param entriesTableSchema schema of Manifest entries
* @param manifestsToExplore manifests to explore of the table
* @param partValue partition value that manifest entries must match, or null to skip filtering
*/
private List<GenericData.Record> expectedEntries(
Table table,
FileContent expectedContent,
Schema entriesTableSchema,
List<ManifestFile> manifestsToExplore,
String partValue)
throws IOException {
List<GenericData.Record> expected = Lists.newArrayList();
for (ManifestFile manifest : manifestsToExplore) {
InputFile in = table.io().newInputFile(manifest.path());
try (CloseableIterable<GenericData.Record> rows =
Avro.read(in).project(entriesTableSchema).build()) {
for (GenericData.Record record : rows) {
if ((Integer) record.get("status") < 2 /* added or existing */) {
GenericData.Record file = (GenericData.Record) record.get("data_file");
if (partitionMatch(file, partValue)) {
asMetadataRecord(file, expectedContent);
expected.add(file);
}
}
}
}
}
return expected;
}
// Populate certain fields derived in the metadata tables
private void asMetadataRecord(GenericData.Record file, FileContent content) {
file.put(0, content.id());
file.put(3, 0); // specId
}
private boolean partitionMatch(GenericData.Record file, String partValue) {
if (partValue == null) {
return true;
}
GenericData.Record partition = (GenericData.Record) file.get(4);
return partValue.equals(partition.get(0).toString());
}
private List<ManifestFile> dataManifests(Table table) {
return table.currentSnapshot().dataManifests(table.io());
}
private List<ManifestFile> allDataManifests(Table table) {
List<ManifestFile> manifests = Lists.newArrayList();
for (Snapshot snapshot : table.snapshots()) {
manifests.addAll(snapshot.dataManifests(table.io()));
}
return manifests;
}
private List<ManifestFile> deleteManifests(Table table) {
return table.currentSnapshot().deleteManifests(table.io());
}
}
|
googleapis/google-api-java-client-services | 36,600 | clients/google-api-services-reseller/v1/2.0.0/com/google/api/services/reseller/model/Subscription.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.reseller.model;
/**
* JSON template for a subscription.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Google Workspace Reseller 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 Subscription extends com.google.api.client.json.GenericJson {
/**
* Read-only field that returns the current billing method for a subscription.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String billingMethod;
/**
* The `creationTime` property is the date when subscription was created. It is in milliseconds
* using the Epoch format. See an example Epoch converter.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long creationTime;
/**
* Primary domain name of the customer
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String customerDomain;
/**
* This property will always be returned in a response as the unique identifier generated by
* Google. In a request, this property can be either the primary domain or the unique identifier
* generated by Google.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String customerId;
/**
* Google-issued code (100 char max) for discounted pricing on subscription plans. Deal code must
* be included in `insert` requests in order to receive discounted rate. This property is
* optional, regular pricing applies if left empty.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String dealCode;
/**
* Identifies the resource as a Subscription. Value: `reseller#subscription`
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* The `plan` property is required. In this version of the API, the G Suite plans are the flexible
* plan, annual commitment plan, and the 30-day free trial plan. For more information about the
* API"s payment plans, see the API concepts.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Plan plan;
/**
* This is an optional property. This purchase order (PO) information is for resellers to use for
* their company tracking usage. If a `purchaseOrderId` value is given it appears in the API
* responses and shows up in the invoice. The property accepts up to 80 plain text characters.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String purchaseOrderId;
/**
* Renewal settings for the annual commitment plan. For more detailed information, see renewal
* options in the administrator help center.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private RenewalSettings renewalSettings;
/**
* URL to customer's Subscriptions page in the Admin console. The read-only URL is generated by
* the API service. This is used if your client application requires the customer to complete a
* task using the Subscriptions page in the Admin console.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String resourceUiUrl;
/**
* This is a required property. The number and limit of user seat licenses in the plan.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Seats seats;
/**
* A required property. The `skuId` is a unique system identifier for a product's SKU assigned to
* a customer in the subscription. For products and SKUs available in this version of the API, see
* Product and SKU IDs.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String skuId;
/**
* Read-only external display name for a product's SKU assigned to a customer in the subscription.
* SKU names are subject to change at Google's discretion. For products and SKUs available in this
* version of the API, see Product and SKU IDs.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String skuName;
/**
* This is an optional property.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String status;
/**
* The `subscriptionId` is the subscription identifier and is unique for each customer. This is a
* required property. Since a `subscriptionId` changes when a subscription is updated, we
* recommend not using this ID as a key for persistent data. Use the `subscriptionId` as described
* in retrieve all reseller subscriptions.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String subscriptionId;
/**
* Read-only field containing an enumerable of all the current suspension reasons for a
* subscription. It is possible for a subscription to have many concurrent, overlapping suspension
* reasons. A subscription's `STATUS` is `SUSPENDED` until all pending suspensions are removed.
* Possible options include: - `PENDING_TOS_ACCEPTANCE` - The customer has not logged in and
* accepted the G Suite Resold Terms of Services. - `RENEWAL_WITH_TYPE_CANCEL` - The customer's
* commitment ended and their service was cancelled at the end of their term. -
* `RESELLER_INITIATED` - A manual suspension invoked by a Reseller. - `TRIAL_ENDED` - The
* customer's trial expired without a plan selected. - `OTHER` - The customer is suspended for an
* internal Google reason (e.g. abuse or otherwise).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> suspensionReasons;
/**
* Read-only transfer related information for the subscription. For more information, see retrieve
* transferable subscriptions for a customer.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TransferInfo transferInfo;
/**
* The G Suite annual commitment and flexible payment plans can be in a 30-day free trial. For
* more information, see the API concepts.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TrialSettings trialSettings;
/**
* Read-only field that returns the current billing method for a subscription.
* @return value or {@code null} for none
*/
public java.lang.String getBillingMethod() {
return billingMethod;
}
/**
* Read-only field that returns the current billing method for a subscription.
* @param billingMethod billingMethod or {@code null} for none
*/
public Subscription setBillingMethod(java.lang.String billingMethod) {
this.billingMethod = billingMethod;
return this;
}
/**
* The `creationTime` property is the date when subscription was created. It is in milliseconds
* using the Epoch format. See an example Epoch converter.
* @return value or {@code null} for none
*/
public java.lang.Long getCreationTime() {
return creationTime;
}
/**
* The `creationTime` property is the date when subscription was created. It is in milliseconds
* using the Epoch format. See an example Epoch converter.
* @param creationTime creationTime or {@code null} for none
*/
public Subscription setCreationTime(java.lang.Long creationTime) {
this.creationTime = creationTime;
return this;
}
/**
* Primary domain name of the customer
* @return value or {@code null} for none
*/
public java.lang.String getCustomerDomain() {
return customerDomain;
}
/**
* Primary domain name of the customer
* @param customerDomain customerDomain or {@code null} for none
*/
public Subscription setCustomerDomain(java.lang.String customerDomain) {
this.customerDomain = customerDomain;
return this;
}
/**
* This property will always be returned in a response as the unique identifier generated by
* Google. In a request, this property can be either the primary domain or the unique identifier
* generated by Google.
* @return value or {@code null} for none
*/
public java.lang.String getCustomerId() {
return customerId;
}
/**
* This property will always be returned in a response as the unique identifier generated by
* Google. In a request, this property can be either the primary domain or the unique identifier
* generated by Google.
* @param customerId customerId or {@code null} for none
*/
public Subscription setCustomerId(java.lang.String customerId) {
this.customerId = customerId;
return this;
}
/**
* Google-issued code (100 char max) for discounted pricing on subscription plans. Deal code must
* be included in `insert` requests in order to receive discounted rate. This property is
* optional, regular pricing applies if left empty.
* @return value or {@code null} for none
*/
public java.lang.String getDealCode() {
return dealCode;
}
/**
* Google-issued code (100 char max) for discounted pricing on subscription plans. Deal code must
* be included in `insert` requests in order to receive discounted rate. This property is
* optional, regular pricing applies if left empty.
* @param dealCode dealCode or {@code null} for none
*/
public Subscription setDealCode(java.lang.String dealCode) {
this.dealCode = dealCode;
return this;
}
/**
* Identifies the resource as a Subscription. Value: `reseller#subscription`
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* Identifies the resource as a Subscription. Value: `reseller#subscription`
* @param kind kind or {@code null} for none
*/
public Subscription setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* The `plan` property is required. In this version of the API, the G Suite plans are the flexible
* plan, annual commitment plan, and the 30-day free trial plan. For more information about the
* API"s payment plans, see the API concepts.
* @return value or {@code null} for none
*/
public Plan getPlan() {
return plan;
}
/**
* The `plan` property is required. In this version of the API, the G Suite plans are the flexible
* plan, annual commitment plan, and the 30-day free trial plan. For more information about the
* API"s payment plans, see the API concepts.
* @param plan plan or {@code null} for none
*/
public Subscription setPlan(Plan plan) {
this.plan = plan;
return this;
}
/**
* This is an optional property. This purchase order (PO) information is for resellers to use for
* their company tracking usage. If a `purchaseOrderId` value is given it appears in the API
* responses and shows up in the invoice. The property accepts up to 80 plain text characters.
* @return value or {@code null} for none
*/
public java.lang.String getPurchaseOrderId() {
return purchaseOrderId;
}
/**
* This is an optional property. This purchase order (PO) information is for resellers to use for
* their company tracking usage. If a `purchaseOrderId` value is given it appears in the API
* responses and shows up in the invoice. The property accepts up to 80 plain text characters.
* @param purchaseOrderId purchaseOrderId or {@code null} for none
*/
public Subscription setPurchaseOrderId(java.lang.String purchaseOrderId) {
this.purchaseOrderId = purchaseOrderId;
return this;
}
/**
* Renewal settings for the annual commitment plan. For more detailed information, see renewal
* options in the administrator help center.
* @return value or {@code null} for none
*/
public RenewalSettings getRenewalSettings() {
return renewalSettings;
}
/**
* Renewal settings for the annual commitment plan. For more detailed information, see renewal
* options in the administrator help center.
* @param renewalSettings renewalSettings or {@code null} for none
*/
public Subscription setRenewalSettings(RenewalSettings renewalSettings) {
this.renewalSettings = renewalSettings;
return this;
}
/**
* URL to customer's Subscriptions page in the Admin console. The read-only URL is generated by
* the API service. This is used if your client application requires the customer to complete a
* task using the Subscriptions page in the Admin console.
* @return value or {@code null} for none
*/
public java.lang.String getResourceUiUrl() {
return resourceUiUrl;
}
/**
* URL to customer's Subscriptions page in the Admin console. The read-only URL is generated by
* the API service. This is used if your client application requires the customer to complete a
* task using the Subscriptions page in the Admin console.
* @param resourceUiUrl resourceUiUrl or {@code null} for none
*/
public Subscription setResourceUiUrl(java.lang.String resourceUiUrl) {
this.resourceUiUrl = resourceUiUrl;
return this;
}
/**
* This is a required property. The number and limit of user seat licenses in the plan.
* @return value or {@code null} for none
*/
public Seats getSeats() {
return seats;
}
/**
* This is a required property. The number and limit of user seat licenses in the plan.
* @param seats seats or {@code null} for none
*/
public Subscription setSeats(Seats seats) {
this.seats = seats;
return this;
}
/**
* A required property. The `skuId` is a unique system identifier for a product's SKU assigned to
* a customer in the subscription. For products and SKUs available in this version of the API, see
* Product and SKU IDs.
* @return value or {@code null} for none
*/
public java.lang.String getSkuId() {
return skuId;
}
/**
* A required property. The `skuId` is a unique system identifier for a product's SKU assigned to
* a customer in the subscription. For products and SKUs available in this version of the API, see
* Product and SKU IDs.
* @param skuId skuId or {@code null} for none
*/
public Subscription setSkuId(java.lang.String skuId) {
this.skuId = skuId;
return this;
}
/**
* Read-only external display name for a product's SKU assigned to a customer in the subscription.
* SKU names are subject to change at Google's discretion. For products and SKUs available in this
* version of the API, see Product and SKU IDs.
* @return value or {@code null} for none
*/
public java.lang.String getSkuName() {
return skuName;
}
/**
* Read-only external display name for a product's SKU assigned to a customer in the subscription.
* SKU names are subject to change at Google's discretion. For products and SKUs available in this
* version of the API, see Product and SKU IDs.
* @param skuName skuName or {@code null} for none
*/
public Subscription setSkuName(java.lang.String skuName) {
this.skuName = skuName;
return this;
}
/**
* This is an optional property.
* @return value or {@code null} for none
*/
public java.lang.String getStatus() {
return status;
}
/**
* This is an optional property.
* @param status status or {@code null} for none
*/
public Subscription setStatus(java.lang.String status) {
this.status = status;
return this;
}
/**
* The `subscriptionId` is the subscription identifier and is unique for each customer. This is a
* required property. Since a `subscriptionId` changes when a subscription is updated, we
* recommend not using this ID as a key for persistent data. Use the `subscriptionId` as described
* in retrieve all reseller subscriptions.
* @return value or {@code null} for none
*/
public java.lang.String getSubscriptionId() {
return subscriptionId;
}
/**
* The `subscriptionId` is the subscription identifier and is unique for each customer. This is a
* required property. Since a `subscriptionId` changes when a subscription is updated, we
* recommend not using this ID as a key for persistent data. Use the `subscriptionId` as described
* in retrieve all reseller subscriptions.
* @param subscriptionId subscriptionId or {@code null} for none
*/
public Subscription setSubscriptionId(java.lang.String subscriptionId) {
this.subscriptionId = subscriptionId;
return this;
}
/**
* Read-only field containing an enumerable of all the current suspension reasons for a
* subscription. It is possible for a subscription to have many concurrent, overlapping suspension
* reasons. A subscription's `STATUS` is `SUSPENDED` until all pending suspensions are removed.
* Possible options include: - `PENDING_TOS_ACCEPTANCE` - The customer has not logged in and
* accepted the G Suite Resold Terms of Services. - `RENEWAL_WITH_TYPE_CANCEL` - The customer's
* commitment ended and their service was cancelled at the end of their term. -
* `RESELLER_INITIATED` - A manual suspension invoked by a Reseller. - `TRIAL_ENDED` - The
* customer's trial expired without a plan selected. - `OTHER` - The customer is suspended for an
* internal Google reason (e.g. abuse or otherwise).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSuspensionReasons() {
return suspensionReasons;
}
/**
* Read-only field containing an enumerable of all the current suspension reasons for a
* subscription. It is possible for a subscription to have many concurrent, overlapping suspension
* reasons. A subscription's `STATUS` is `SUSPENDED` until all pending suspensions are removed.
* Possible options include: - `PENDING_TOS_ACCEPTANCE` - The customer has not logged in and
* accepted the G Suite Resold Terms of Services. - `RENEWAL_WITH_TYPE_CANCEL` - The customer's
* commitment ended and their service was cancelled at the end of their term. -
* `RESELLER_INITIATED` - A manual suspension invoked by a Reseller. - `TRIAL_ENDED` - The
* customer's trial expired without a plan selected. - `OTHER` - The customer is suspended for an
* internal Google reason (e.g. abuse or otherwise).
* @param suspensionReasons suspensionReasons or {@code null} for none
*/
public Subscription setSuspensionReasons(java.util.List<java.lang.String> suspensionReasons) {
this.suspensionReasons = suspensionReasons;
return this;
}
/**
* Read-only transfer related information for the subscription. For more information, see retrieve
* transferable subscriptions for a customer.
* @return value or {@code null} for none
*/
public TransferInfo getTransferInfo() {
return transferInfo;
}
/**
* Read-only transfer related information for the subscription. For more information, see retrieve
* transferable subscriptions for a customer.
* @param transferInfo transferInfo or {@code null} for none
*/
public Subscription setTransferInfo(TransferInfo transferInfo) {
this.transferInfo = transferInfo;
return this;
}
/**
* The G Suite annual commitment and flexible payment plans can be in a 30-day free trial. For
* more information, see the API concepts.
* @return value or {@code null} for none
*/
public TrialSettings getTrialSettings() {
return trialSettings;
}
/**
* The G Suite annual commitment and flexible payment plans can be in a 30-day free trial. For
* more information, see the API concepts.
* @param trialSettings trialSettings or {@code null} for none
*/
public Subscription setTrialSettings(TrialSettings trialSettings) {
this.trialSettings = trialSettings;
return this;
}
@Override
public Subscription set(String fieldName, Object value) {
return (Subscription) super.set(fieldName, value);
}
@Override
public Subscription clone() {
return (Subscription) super.clone();
}
/**
* The `plan` property is required. In this version of the API, the G Suite plans are the flexible
* plan, annual commitment plan, and the 30-day free trial plan. For more information about the
* API"s payment plans, see the API concepts.
*/
public static final class Plan extends com.google.api.client.json.GenericJson {
/**
* In this version of the API, annual commitment plan's interval is one year. *Note: *When
* `billingMethod` value is `OFFLINE`, the subscription property object `plan.commitmentInterval`
* is omitted in all API responses.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CommitmentInterval commitmentInterval;
/**
* The `isCommitmentPlan` property's boolean value identifies the plan as an annual commitment
* plan: - `true` — The subscription's plan is an annual commitment plan. - `false` — The plan is
* not an annual commitment plan.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean isCommitmentPlan;
/**
* The `planName` property is required. This is the name of the subscription's plan. For more
* information about the Google payment plans, see the API concepts. Possible values are: -
* `ANNUAL_MONTHLY_PAY` — The annual commitment plan with monthly payments. *Caution:
* *`ANNUAL_MONTHLY_PAY` is returned as `ANNUAL` in all API responses. - `ANNUAL_YEARLY_PAY` — The
* annual commitment plan with yearly payments - `FLEXIBLE` — The flexible plan - `TRIAL` — The
* 30-day free trial plan. A subscription in trial will be suspended after the 30th free day if no
* payment plan is assigned. Calling `changePlan` will assign a payment plan to a trial but will
* not activate the plan. A trial will automatically begin its assigned payment plan after its
* 30th free day or immediately after calling `startPaidService`. - `FREE` — The free plan is
* exclusive to the Cloud Identity SKU and does not incur any billing.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String planName;
/**
* In this version of the API, annual commitment plan's interval is one year. *Note: *When
* `billingMethod` value is `OFFLINE`, the subscription property object `plan.commitmentInterval`
* is omitted in all API responses.
* @return value or {@code null} for none
*/
public CommitmentInterval getCommitmentInterval() {
return commitmentInterval;
}
/**
* In this version of the API, annual commitment plan's interval is one year. *Note: *When
* `billingMethod` value is `OFFLINE`, the subscription property object `plan.commitmentInterval`
* is omitted in all API responses.
* @param commitmentInterval commitmentInterval or {@code null} for none
*/
public Plan setCommitmentInterval(CommitmentInterval commitmentInterval) {
this.commitmentInterval = commitmentInterval;
return this;
}
/**
* The `isCommitmentPlan` property's boolean value identifies the plan as an annual commitment
* plan: - `true` — The subscription's plan is an annual commitment plan. - `false` — The plan is
* not an annual commitment plan.
* @return value or {@code null} for none
*/
public java.lang.Boolean getIsCommitmentPlan() {
return isCommitmentPlan;
}
/**
* The `isCommitmentPlan` property's boolean value identifies the plan as an annual commitment
* plan: - `true` — The subscription's plan is an annual commitment plan. - `false` — The plan is
* not an annual commitment plan.
* @param isCommitmentPlan isCommitmentPlan or {@code null} for none
*/
public Plan setIsCommitmentPlan(java.lang.Boolean isCommitmentPlan) {
this.isCommitmentPlan = isCommitmentPlan;
return this;
}
/**
* The `planName` property is required. This is the name of the subscription's plan. For more
* information about the Google payment plans, see the API concepts. Possible values are: -
* `ANNUAL_MONTHLY_PAY` — The annual commitment plan with monthly payments. *Caution:
* *`ANNUAL_MONTHLY_PAY` is returned as `ANNUAL` in all API responses. - `ANNUAL_YEARLY_PAY` — The
* annual commitment plan with yearly payments - `FLEXIBLE` — The flexible plan - `TRIAL` — The
* 30-day free trial plan. A subscription in trial will be suspended after the 30th free day if no
* payment plan is assigned. Calling `changePlan` will assign a payment plan to a trial but will
* not activate the plan. A trial will automatically begin its assigned payment plan after its
* 30th free day or immediately after calling `startPaidService`. - `FREE` — The free plan is
* exclusive to the Cloud Identity SKU and does not incur any billing.
* @return value or {@code null} for none
*/
public java.lang.String getPlanName() {
return planName;
}
/**
* The `planName` property is required. This is the name of the subscription's plan. For more
* information about the Google payment plans, see the API concepts. Possible values are: -
* `ANNUAL_MONTHLY_PAY` — The annual commitment plan with monthly payments. *Caution:
* *`ANNUAL_MONTHLY_PAY` is returned as `ANNUAL` in all API responses. - `ANNUAL_YEARLY_PAY` — The
* annual commitment plan with yearly payments - `FLEXIBLE` — The flexible plan - `TRIAL` — The
* 30-day free trial plan. A subscription in trial will be suspended after the 30th free day if no
* payment plan is assigned. Calling `changePlan` will assign a payment plan to a trial but will
* not activate the plan. A trial will automatically begin its assigned payment plan after its
* 30th free day or immediately after calling `startPaidService`. - `FREE` — The free plan is
* exclusive to the Cloud Identity SKU and does not incur any billing.
* @param planName planName or {@code null} for none
*/
public Plan setPlanName(java.lang.String planName) {
this.planName = planName;
return this;
}
@Override
public Plan set(String fieldName, Object value) {
return (Plan) super.set(fieldName, value);
}
@Override
public Plan clone() {
return (Plan) super.clone();
}
/**
* In this version of the API, annual commitment plan's interval is one year. *Note: *When
* `billingMethod` value is `OFFLINE`, the subscription property object `plan.commitmentInterval` is
* omitted in all API responses.
*/
public static final class CommitmentInterval extends com.google.api.client.json.GenericJson {
/**
* An annual commitment plan's interval's `endTime` in milliseconds using the UNIX Epoch format.
* See an example Epoch converter.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long endTime;
/**
* An annual commitment plan's interval's `startTime` in milliseconds using UNIX Epoch format. See
* an example Epoch converter.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long startTime;
/**
* An annual commitment plan's interval's `endTime` in milliseconds using the UNIX Epoch format.
* See an example Epoch converter.
* @return value or {@code null} for none
*/
public java.lang.Long getEndTime() {
return endTime;
}
/**
* An annual commitment plan's interval's `endTime` in milliseconds using the UNIX Epoch format.
* See an example Epoch converter.
* @param endTime endTime or {@code null} for none
*/
public CommitmentInterval setEndTime(java.lang.Long endTime) {
this.endTime = endTime;
return this;
}
/**
* An annual commitment plan's interval's `startTime` in milliseconds using UNIX Epoch format. See
* an example Epoch converter.
* @return value or {@code null} for none
*/
public java.lang.Long getStartTime() {
return startTime;
}
/**
* An annual commitment plan's interval's `startTime` in milliseconds using UNIX Epoch format. See
* an example Epoch converter.
* @param startTime startTime or {@code null} for none
*/
public CommitmentInterval setStartTime(java.lang.Long startTime) {
this.startTime = startTime;
return this;
}
@Override
public CommitmentInterval set(String fieldName, Object value) {
return (CommitmentInterval) super.set(fieldName, value);
}
@Override
public CommitmentInterval clone() {
return (CommitmentInterval) super.clone();
}
}
}
/**
* Read-only transfer related information for the subscription. For more information, see retrieve
* transferable subscriptions for a customer.
*/
public static final class TransferInfo extends com.google.api.client.json.GenericJson {
/**
* The `skuId` of the current resold subscription. This is populated only when the customer has a
* subscription with a legacy SKU and the subscription resource is populated with the `skuId` of
* the SKU recommended for the transfer.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String currentLegacySkuId;
/**
* When inserting a subscription, this is the minimum number of seats listed in the transfer order
* for this product. For example, if the customer has 20 users, the reseller cannot place a
* transfer order of 15 seats. The minimum is 20 seats.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer minimumTransferableSeats;
/**
* The time when transfer token or intent to transfer will expire. The time is in milliseconds
* using UNIX Epoch format.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long transferabilityExpirationTime;
/**
* The `skuId` of the current resold subscription. This is populated only when the customer has a
* subscription with a legacy SKU and the subscription resource is populated with the `skuId` of
* the SKU recommended for the transfer.
* @return value or {@code null} for none
*/
public java.lang.String getCurrentLegacySkuId() {
return currentLegacySkuId;
}
/**
* The `skuId` of the current resold subscription. This is populated only when the customer has a
* subscription with a legacy SKU and the subscription resource is populated with the `skuId` of
* the SKU recommended for the transfer.
* @param currentLegacySkuId currentLegacySkuId or {@code null} for none
*/
public TransferInfo setCurrentLegacySkuId(java.lang.String currentLegacySkuId) {
this.currentLegacySkuId = currentLegacySkuId;
return this;
}
/**
* When inserting a subscription, this is the minimum number of seats listed in the transfer order
* for this product. For example, if the customer has 20 users, the reseller cannot place a
* transfer order of 15 seats. The minimum is 20 seats.
* @return value or {@code null} for none
*/
public java.lang.Integer getMinimumTransferableSeats() {
return minimumTransferableSeats;
}
/**
* When inserting a subscription, this is the minimum number of seats listed in the transfer order
* for this product. For example, if the customer has 20 users, the reseller cannot place a
* transfer order of 15 seats. The minimum is 20 seats.
* @param minimumTransferableSeats minimumTransferableSeats or {@code null} for none
*/
public TransferInfo setMinimumTransferableSeats(java.lang.Integer minimumTransferableSeats) {
this.minimumTransferableSeats = minimumTransferableSeats;
return this;
}
/**
* The time when transfer token or intent to transfer will expire. The time is in milliseconds
* using UNIX Epoch format.
* @return value or {@code null} for none
*/
public java.lang.Long getTransferabilityExpirationTime() {
return transferabilityExpirationTime;
}
/**
* The time when transfer token or intent to transfer will expire. The time is in milliseconds
* using UNIX Epoch format.
* @param transferabilityExpirationTime transferabilityExpirationTime or {@code null} for none
*/
public TransferInfo setTransferabilityExpirationTime(java.lang.Long transferabilityExpirationTime) {
this.transferabilityExpirationTime = transferabilityExpirationTime;
return this;
}
@Override
public TransferInfo set(String fieldName, Object value) {
return (TransferInfo) super.set(fieldName, value);
}
@Override
public TransferInfo clone() {
return (TransferInfo) super.clone();
}
}
/**
* The G Suite annual commitment and flexible payment plans can be in a 30-day free trial. For more
* information, see the API concepts.
*/
public static final class TrialSettings extends com.google.api.client.json.GenericJson {
/**
* Determines if a subscription's plan is in a 30-day free trial or not: - `true` — The plan is in
* trial. - `false` — The plan is not in trial.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean isInTrial;
/**
* Date when the trial ends. The value is in milliseconds using the UNIX Epoch format. See an
* example Epoch converter.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long trialEndTime;
/**
* Determines if a subscription's plan is in a 30-day free trial or not: - `true` — The plan is in
* trial. - `false` — The plan is not in trial.
* @return value or {@code null} for none
*/
public java.lang.Boolean getIsInTrial() {
return isInTrial;
}
/**
* Determines if a subscription's plan is in a 30-day free trial or not: - `true` — The plan is in
* trial. - `false` — The plan is not in trial.
* @param isInTrial isInTrial or {@code null} for none
*/
public TrialSettings setIsInTrial(java.lang.Boolean isInTrial) {
this.isInTrial = isInTrial;
return this;
}
/**
* Date when the trial ends. The value is in milliseconds using the UNIX Epoch format. See an
* example Epoch converter.
* @return value or {@code null} for none
*/
public java.lang.Long getTrialEndTime() {
return trialEndTime;
}
/**
* Date when the trial ends. The value is in milliseconds using the UNIX Epoch format. See an
* example Epoch converter.
* @param trialEndTime trialEndTime or {@code null} for none
*/
public TrialSettings setTrialEndTime(java.lang.Long trialEndTime) {
this.trialEndTime = trialEndTime;
return this;
}
@Override
public TrialSettings set(String fieldName, Object value) {
return (TrialSettings) super.set(fieldName, value);
}
@Override
public TrialSettings clone() {
return (TrialSettings) super.clone();
}
}
}
|
googleapis/google-api-java-client-services | 36,600 | clients/google-api-services-reseller/v1/1.31.0/com/google/api/services/reseller/model/Subscription.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.reseller.model;
/**
* JSON template for a subscription.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Google Workspace Reseller 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 Subscription extends com.google.api.client.json.GenericJson {
/**
* Read-only field that returns the current billing method for a subscription.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String billingMethod;
/**
* The `creationTime` property is the date when subscription was created. It is in milliseconds
* using the Epoch format. See an example Epoch converter.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long creationTime;
/**
* Primary domain name of the customer
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String customerDomain;
/**
* This property will always be returned in a response as the unique identifier generated by
* Google. In a request, this property can be either the primary domain or the unique identifier
* generated by Google.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String customerId;
/**
* Google-issued code (100 char max) for discounted pricing on subscription plans. Deal code must
* be included in `insert` requests in order to receive discounted rate. This property is
* optional, regular pricing applies if left empty.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String dealCode;
/**
* Identifies the resource as a Subscription. Value: `reseller#subscription`
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* The `plan` property is required. In this version of the API, the G Suite plans are the flexible
* plan, annual commitment plan, and the 30-day free trial plan. For more information about the
* API"s payment plans, see the API concepts.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Plan plan;
/**
* This is an optional property. This purchase order (PO) information is for resellers to use for
* their company tracking usage. If a `purchaseOrderId` value is given it appears in the API
* responses and shows up in the invoice. The property accepts up to 80 plain text characters.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String purchaseOrderId;
/**
* Renewal settings for the annual commitment plan. For more detailed information, see renewal
* options in the administrator help center.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private RenewalSettings renewalSettings;
/**
* URL to customer's Subscriptions page in the Admin console. The read-only URL is generated by
* the API service. This is used if your client application requires the customer to complete a
* task using the Subscriptions page in the Admin console.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String resourceUiUrl;
/**
* This is a required property. The number and limit of user seat licenses in the plan.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Seats seats;
/**
* A required property. The `skuId` is a unique system identifier for a product's SKU assigned to
* a customer in the subscription. For products and SKUs available in this version of the API, see
* Product and SKU IDs.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String skuId;
/**
* Read-only external display name for a product's SKU assigned to a customer in the subscription.
* SKU names are subject to change at Google's discretion. For products and SKUs available in this
* version of the API, see Product and SKU IDs.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String skuName;
/**
* This is an optional property.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String status;
/**
* The `subscriptionId` is the subscription identifier and is unique for each customer. This is a
* required property. Since a `subscriptionId` changes when a subscription is updated, we
* recommend not using this ID as a key for persistent data. Use the `subscriptionId` as described
* in retrieve all reseller subscriptions.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String subscriptionId;
/**
* Read-only field containing an enumerable of all the current suspension reasons for a
* subscription. It is possible for a subscription to have many concurrent, overlapping suspension
* reasons. A subscription's `STATUS` is `SUSPENDED` until all pending suspensions are removed.
* Possible options include: - `PENDING_TOS_ACCEPTANCE` - The customer has not logged in and
* accepted the G Suite Resold Terms of Services. - `RENEWAL_WITH_TYPE_CANCEL` - The customer's
* commitment ended and their service was cancelled at the end of their term. -
* `RESELLER_INITIATED` - A manual suspension invoked by a Reseller. - `TRIAL_ENDED` - The
* customer's trial expired without a plan selected. - `OTHER` - The customer is suspended for an
* internal Google reason (e.g. abuse or otherwise).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> suspensionReasons;
/**
* Read-only transfer related information for the subscription. For more information, see retrieve
* transferable subscriptions for a customer.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TransferInfo transferInfo;
/**
* The G Suite annual commitment and flexible payment plans can be in a 30-day free trial. For
* more information, see the API concepts.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TrialSettings trialSettings;
/**
* Read-only field that returns the current billing method for a subscription.
* @return value or {@code null} for none
*/
public java.lang.String getBillingMethod() {
return billingMethod;
}
/**
* Read-only field that returns the current billing method for a subscription.
* @param billingMethod billingMethod or {@code null} for none
*/
public Subscription setBillingMethod(java.lang.String billingMethod) {
this.billingMethod = billingMethod;
return this;
}
/**
* The `creationTime` property is the date when subscription was created. It is in milliseconds
* using the Epoch format. See an example Epoch converter.
* @return value or {@code null} for none
*/
public java.lang.Long getCreationTime() {
return creationTime;
}
/**
* The `creationTime` property is the date when subscription was created. It is in milliseconds
* using the Epoch format. See an example Epoch converter.
* @param creationTime creationTime or {@code null} for none
*/
public Subscription setCreationTime(java.lang.Long creationTime) {
this.creationTime = creationTime;
return this;
}
/**
* Primary domain name of the customer
* @return value or {@code null} for none
*/
public java.lang.String getCustomerDomain() {
return customerDomain;
}
/**
* Primary domain name of the customer
* @param customerDomain customerDomain or {@code null} for none
*/
public Subscription setCustomerDomain(java.lang.String customerDomain) {
this.customerDomain = customerDomain;
return this;
}
/**
* This property will always be returned in a response as the unique identifier generated by
* Google. In a request, this property can be either the primary domain or the unique identifier
* generated by Google.
* @return value or {@code null} for none
*/
public java.lang.String getCustomerId() {
return customerId;
}
/**
* This property will always be returned in a response as the unique identifier generated by
* Google. In a request, this property can be either the primary domain or the unique identifier
* generated by Google.
* @param customerId customerId or {@code null} for none
*/
public Subscription setCustomerId(java.lang.String customerId) {
this.customerId = customerId;
return this;
}
/**
* Google-issued code (100 char max) for discounted pricing on subscription plans. Deal code must
* be included in `insert` requests in order to receive discounted rate. This property is
* optional, regular pricing applies if left empty.
* @return value or {@code null} for none
*/
public java.lang.String getDealCode() {
return dealCode;
}
/**
* Google-issued code (100 char max) for discounted pricing on subscription plans. Deal code must
* be included in `insert` requests in order to receive discounted rate. This property is
* optional, regular pricing applies if left empty.
* @param dealCode dealCode or {@code null} for none
*/
public Subscription setDealCode(java.lang.String dealCode) {
this.dealCode = dealCode;
return this;
}
/**
* Identifies the resource as a Subscription. Value: `reseller#subscription`
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* Identifies the resource as a Subscription. Value: `reseller#subscription`
* @param kind kind or {@code null} for none
*/
public Subscription setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* The `plan` property is required. In this version of the API, the G Suite plans are the flexible
* plan, annual commitment plan, and the 30-day free trial plan. For more information about the
* API"s payment plans, see the API concepts.
* @return value or {@code null} for none
*/
public Plan getPlan() {
return plan;
}
/**
* The `plan` property is required. In this version of the API, the G Suite plans are the flexible
* plan, annual commitment plan, and the 30-day free trial plan. For more information about the
* API"s payment plans, see the API concepts.
* @param plan plan or {@code null} for none
*/
public Subscription setPlan(Plan plan) {
this.plan = plan;
return this;
}
/**
* This is an optional property. This purchase order (PO) information is for resellers to use for
* their company tracking usage. If a `purchaseOrderId` value is given it appears in the API
* responses and shows up in the invoice. The property accepts up to 80 plain text characters.
* @return value or {@code null} for none
*/
public java.lang.String getPurchaseOrderId() {
return purchaseOrderId;
}
/**
* This is an optional property. This purchase order (PO) information is for resellers to use for
* their company tracking usage. If a `purchaseOrderId` value is given it appears in the API
* responses and shows up in the invoice. The property accepts up to 80 plain text characters.
* @param purchaseOrderId purchaseOrderId or {@code null} for none
*/
public Subscription setPurchaseOrderId(java.lang.String purchaseOrderId) {
this.purchaseOrderId = purchaseOrderId;
return this;
}
/**
* Renewal settings for the annual commitment plan. For more detailed information, see renewal
* options in the administrator help center.
* @return value or {@code null} for none
*/
public RenewalSettings getRenewalSettings() {
return renewalSettings;
}
/**
* Renewal settings for the annual commitment plan. For more detailed information, see renewal
* options in the administrator help center.
* @param renewalSettings renewalSettings or {@code null} for none
*/
public Subscription setRenewalSettings(RenewalSettings renewalSettings) {
this.renewalSettings = renewalSettings;
return this;
}
/**
* URL to customer's Subscriptions page in the Admin console. The read-only URL is generated by
* the API service. This is used if your client application requires the customer to complete a
* task using the Subscriptions page in the Admin console.
* @return value or {@code null} for none
*/
public java.lang.String getResourceUiUrl() {
return resourceUiUrl;
}
/**
* URL to customer's Subscriptions page in the Admin console. The read-only URL is generated by
* the API service. This is used if your client application requires the customer to complete a
* task using the Subscriptions page in the Admin console.
* @param resourceUiUrl resourceUiUrl or {@code null} for none
*/
public Subscription setResourceUiUrl(java.lang.String resourceUiUrl) {
this.resourceUiUrl = resourceUiUrl;
return this;
}
/**
* This is a required property. The number and limit of user seat licenses in the plan.
* @return value or {@code null} for none
*/
public Seats getSeats() {
return seats;
}
/**
* This is a required property. The number and limit of user seat licenses in the plan.
* @param seats seats or {@code null} for none
*/
public Subscription setSeats(Seats seats) {
this.seats = seats;
return this;
}
/**
* A required property. The `skuId` is a unique system identifier for a product's SKU assigned to
* a customer in the subscription. For products and SKUs available in this version of the API, see
* Product and SKU IDs.
* @return value or {@code null} for none
*/
public java.lang.String getSkuId() {
return skuId;
}
/**
* A required property. The `skuId` is a unique system identifier for a product's SKU assigned to
* a customer in the subscription. For products and SKUs available in this version of the API, see
* Product and SKU IDs.
* @param skuId skuId or {@code null} for none
*/
public Subscription setSkuId(java.lang.String skuId) {
this.skuId = skuId;
return this;
}
/**
* Read-only external display name for a product's SKU assigned to a customer in the subscription.
* SKU names are subject to change at Google's discretion. For products and SKUs available in this
* version of the API, see Product and SKU IDs.
* @return value or {@code null} for none
*/
public java.lang.String getSkuName() {
return skuName;
}
/**
* Read-only external display name for a product's SKU assigned to a customer in the subscription.
* SKU names are subject to change at Google's discretion. For products and SKUs available in this
* version of the API, see Product and SKU IDs.
* @param skuName skuName or {@code null} for none
*/
public Subscription setSkuName(java.lang.String skuName) {
this.skuName = skuName;
return this;
}
/**
* This is an optional property.
* @return value or {@code null} for none
*/
public java.lang.String getStatus() {
return status;
}
/**
* This is an optional property.
* @param status status or {@code null} for none
*/
public Subscription setStatus(java.lang.String status) {
this.status = status;
return this;
}
/**
* The `subscriptionId` is the subscription identifier and is unique for each customer. This is a
* required property. Since a `subscriptionId` changes when a subscription is updated, we
* recommend not using this ID as a key for persistent data. Use the `subscriptionId` as described
* in retrieve all reseller subscriptions.
* @return value or {@code null} for none
*/
public java.lang.String getSubscriptionId() {
return subscriptionId;
}
/**
* The `subscriptionId` is the subscription identifier and is unique for each customer. This is a
* required property. Since a `subscriptionId` changes when a subscription is updated, we
* recommend not using this ID as a key for persistent data. Use the `subscriptionId` as described
* in retrieve all reseller subscriptions.
* @param subscriptionId subscriptionId or {@code null} for none
*/
public Subscription setSubscriptionId(java.lang.String subscriptionId) {
this.subscriptionId = subscriptionId;
return this;
}
/**
* Read-only field containing an enumerable of all the current suspension reasons for a
* subscription. It is possible for a subscription to have many concurrent, overlapping suspension
* reasons. A subscription's `STATUS` is `SUSPENDED` until all pending suspensions are removed.
* Possible options include: - `PENDING_TOS_ACCEPTANCE` - The customer has not logged in and
* accepted the G Suite Resold Terms of Services. - `RENEWAL_WITH_TYPE_CANCEL` - The customer's
* commitment ended and their service was cancelled at the end of their term. -
* `RESELLER_INITIATED` - A manual suspension invoked by a Reseller. - `TRIAL_ENDED` - The
* customer's trial expired without a plan selected. - `OTHER` - The customer is suspended for an
* internal Google reason (e.g. abuse or otherwise).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSuspensionReasons() {
return suspensionReasons;
}
/**
* Read-only field containing an enumerable of all the current suspension reasons for a
* subscription. It is possible for a subscription to have many concurrent, overlapping suspension
* reasons. A subscription's `STATUS` is `SUSPENDED` until all pending suspensions are removed.
* Possible options include: - `PENDING_TOS_ACCEPTANCE` - The customer has not logged in and
* accepted the G Suite Resold Terms of Services. - `RENEWAL_WITH_TYPE_CANCEL` - The customer's
* commitment ended and their service was cancelled at the end of their term. -
* `RESELLER_INITIATED` - A manual suspension invoked by a Reseller. - `TRIAL_ENDED` - The
* customer's trial expired without a plan selected. - `OTHER` - The customer is suspended for an
* internal Google reason (e.g. abuse or otherwise).
* @param suspensionReasons suspensionReasons or {@code null} for none
*/
public Subscription setSuspensionReasons(java.util.List<java.lang.String> suspensionReasons) {
this.suspensionReasons = suspensionReasons;
return this;
}
/**
* Read-only transfer related information for the subscription. For more information, see retrieve
* transferable subscriptions for a customer.
* @return value or {@code null} for none
*/
public TransferInfo getTransferInfo() {
return transferInfo;
}
/**
* Read-only transfer related information for the subscription. For more information, see retrieve
* transferable subscriptions for a customer.
* @param transferInfo transferInfo or {@code null} for none
*/
public Subscription setTransferInfo(TransferInfo transferInfo) {
this.transferInfo = transferInfo;
return this;
}
/**
* The G Suite annual commitment and flexible payment plans can be in a 30-day free trial. For
* more information, see the API concepts.
* @return value or {@code null} for none
*/
public TrialSettings getTrialSettings() {
return trialSettings;
}
/**
* The G Suite annual commitment and flexible payment plans can be in a 30-day free trial. For
* more information, see the API concepts.
* @param trialSettings trialSettings or {@code null} for none
*/
public Subscription setTrialSettings(TrialSettings trialSettings) {
this.trialSettings = trialSettings;
return this;
}
@Override
public Subscription set(String fieldName, Object value) {
return (Subscription) super.set(fieldName, value);
}
@Override
public Subscription clone() {
return (Subscription) super.clone();
}
/**
* The `plan` property is required. In this version of the API, the G Suite plans are the flexible
* plan, annual commitment plan, and the 30-day free trial plan. For more information about the
* API"s payment plans, see the API concepts.
*/
public static final class Plan extends com.google.api.client.json.GenericJson {
/**
* In this version of the API, annual commitment plan's interval is one year. *Note: *When
* `billingMethod` value is `OFFLINE`, the subscription property object `plan.commitmentInterval`
* is omitted in all API responses.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CommitmentInterval commitmentInterval;
/**
* The `isCommitmentPlan` property's boolean value identifies the plan as an annual commitment
* plan: - `true` — The subscription's plan is an annual commitment plan. - `false` — The plan is
* not an annual commitment plan.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean isCommitmentPlan;
/**
* The `planName` property is required. This is the name of the subscription's plan. For more
* information about the Google payment plans, see the API concepts. Possible values are: -
* `ANNUAL_MONTHLY_PAY` — The annual commitment plan with monthly payments. *Caution:
* *`ANNUAL_MONTHLY_PAY` is returned as `ANNUAL` in all API responses. - `ANNUAL_YEARLY_PAY` — The
* annual commitment plan with yearly payments - `FLEXIBLE` — The flexible plan - `TRIAL` — The
* 30-day free trial plan. A subscription in trial will be suspended after the 30th free day if no
* payment plan is assigned. Calling `changePlan` will assign a payment plan to a trial but will
* not activate the plan. A trial will automatically begin its assigned payment plan after its
* 30th free day or immediately after calling `startPaidService`. - `FREE` — The free plan is
* exclusive to the Cloud Identity SKU and does not incur any billing.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String planName;
/**
* In this version of the API, annual commitment plan's interval is one year. *Note: *When
* `billingMethod` value is `OFFLINE`, the subscription property object `plan.commitmentInterval`
* is omitted in all API responses.
* @return value or {@code null} for none
*/
public CommitmentInterval getCommitmentInterval() {
return commitmentInterval;
}
/**
* In this version of the API, annual commitment plan's interval is one year. *Note: *When
* `billingMethod` value is `OFFLINE`, the subscription property object `plan.commitmentInterval`
* is omitted in all API responses.
* @param commitmentInterval commitmentInterval or {@code null} for none
*/
public Plan setCommitmentInterval(CommitmentInterval commitmentInterval) {
this.commitmentInterval = commitmentInterval;
return this;
}
/**
* The `isCommitmentPlan` property's boolean value identifies the plan as an annual commitment
* plan: - `true` — The subscription's plan is an annual commitment plan. - `false` — The plan is
* not an annual commitment plan.
* @return value or {@code null} for none
*/
public java.lang.Boolean getIsCommitmentPlan() {
return isCommitmentPlan;
}
/**
* The `isCommitmentPlan` property's boolean value identifies the plan as an annual commitment
* plan: - `true` — The subscription's plan is an annual commitment plan. - `false` — The plan is
* not an annual commitment plan.
* @param isCommitmentPlan isCommitmentPlan or {@code null} for none
*/
public Plan setIsCommitmentPlan(java.lang.Boolean isCommitmentPlan) {
this.isCommitmentPlan = isCommitmentPlan;
return this;
}
/**
* The `planName` property is required. This is the name of the subscription's plan. For more
* information about the Google payment plans, see the API concepts. Possible values are: -
* `ANNUAL_MONTHLY_PAY` — The annual commitment plan with monthly payments. *Caution:
* *`ANNUAL_MONTHLY_PAY` is returned as `ANNUAL` in all API responses. - `ANNUAL_YEARLY_PAY` — The
* annual commitment plan with yearly payments - `FLEXIBLE` — The flexible plan - `TRIAL` — The
* 30-day free trial plan. A subscription in trial will be suspended after the 30th free day if no
* payment plan is assigned. Calling `changePlan` will assign a payment plan to a trial but will
* not activate the plan. A trial will automatically begin its assigned payment plan after its
* 30th free day or immediately after calling `startPaidService`. - `FREE` — The free plan is
* exclusive to the Cloud Identity SKU and does not incur any billing.
* @return value or {@code null} for none
*/
public java.lang.String getPlanName() {
return planName;
}
/**
* The `planName` property is required. This is the name of the subscription's plan. For more
* information about the Google payment plans, see the API concepts. Possible values are: -
* `ANNUAL_MONTHLY_PAY` — The annual commitment plan with monthly payments. *Caution:
* *`ANNUAL_MONTHLY_PAY` is returned as `ANNUAL` in all API responses. - `ANNUAL_YEARLY_PAY` — The
* annual commitment plan with yearly payments - `FLEXIBLE` — The flexible plan - `TRIAL` — The
* 30-day free trial plan. A subscription in trial will be suspended after the 30th free day if no
* payment plan is assigned. Calling `changePlan` will assign a payment plan to a trial but will
* not activate the plan. A trial will automatically begin its assigned payment plan after its
* 30th free day or immediately after calling `startPaidService`. - `FREE` — The free plan is
* exclusive to the Cloud Identity SKU and does not incur any billing.
* @param planName planName or {@code null} for none
*/
public Plan setPlanName(java.lang.String planName) {
this.planName = planName;
return this;
}
@Override
public Plan set(String fieldName, Object value) {
return (Plan) super.set(fieldName, value);
}
@Override
public Plan clone() {
return (Plan) super.clone();
}
/**
* In this version of the API, annual commitment plan's interval is one year. *Note: *When
* `billingMethod` value is `OFFLINE`, the subscription property object `plan.commitmentInterval` is
* omitted in all API responses.
*/
public static final class CommitmentInterval extends com.google.api.client.json.GenericJson {
/**
* An annual commitment plan's interval's `endTime` in milliseconds using the UNIX Epoch format.
* See an example Epoch converter.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long endTime;
/**
* An annual commitment plan's interval's `startTime` in milliseconds using UNIX Epoch format. See
* an example Epoch converter.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long startTime;
/**
* An annual commitment plan's interval's `endTime` in milliseconds using the UNIX Epoch format.
* See an example Epoch converter.
* @return value or {@code null} for none
*/
public java.lang.Long getEndTime() {
return endTime;
}
/**
* An annual commitment plan's interval's `endTime` in milliseconds using the UNIX Epoch format.
* See an example Epoch converter.
* @param endTime endTime or {@code null} for none
*/
public CommitmentInterval setEndTime(java.lang.Long endTime) {
this.endTime = endTime;
return this;
}
/**
* An annual commitment plan's interval's `startTime` in milliseconds using UNIX Epoch format. See
* an example Epoch converter.
* @return value or {@code null} for none
*/
public java.lang.Long getStartTime() {
return startTime;
}
/**
* An annual commitment plan's interval's `startTime` in milliseconds using UNIX Epoch format. See
* an example Epoch converter.
* @param startTime startTime or {@code null} for none
*/
public CommitmentInterval setStartTime(java.lang.Long startTime) {
this.startTime = startTime;
return this;
}
@Override
public CommitmentInterval set(String fieldName, Object value) {
return (CommitmentInterval) super.set(fieldName, value);
}
@Override
public CommitmentInterval clone() {
return (CommitmentInterval) super.clone();
}
}
}
/**
* Read-only transfer related information for the subscription. For more information, see retrieve
* transferable subscriptions for a customer.
*/
public static final class TransferInfo extends com.google.api.client.json.GenericJson {
/**
* The `skuId` of the current resold subscription. This is populated only when the customer has a
* subscription with a legacy SKU and the subscription resource is populated with the `skuId` of
* the SKU recommended for the transfer.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String currentLegacySkuId;
/**
* When inserting a subscription, this is the minimum number of seats listed in the transfer order
* for this product. For example, if the customer has 20 users, the reseller cannot place a
* transfer order of 15 seats. The minimum is 20 seats.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer minimumTransferableSeats;
/**
* The time when transfer token or intent to transfer will expire. The time is in milliseconds
* using UNIX Epoch format.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long transferabilityExpirationTime;
/**
* The `skuId` of the current resold subscription. This is populated only when the customer has a
* subscription with a legacy SKU and the subscription resource is populated with the `skuId` of
* the SKU recommended for the transfer.
* @return value or {@code null} for none
*/
public java.lang.String getCurrentLegacySkuId() {
return currentLegacySkuId;
}
/**
* The `skuId` of the current resold subscription. This is populated only when the customer has a
* subscription with a legacy SKU and the subscription resource is populated with the `skuId` of
* the SKU recommended for the transfer.
* @param currentLegacySkuId currentLegacySkuId or {@code null} for none
*/
public TransferInfo setCurrentLegacySkuId(java.lang.String currentLegacySkuId) {
this.currentLegacySkuId = currentLegacySkuId;
return this;
}
/**
* When inserting a subscription, this is the minimum number of seats listed in the transfer order
* for this product. For example, if the customer has 20 users, the reseller cannot place a
* transfer order of 15 seats. The minimum is 20 seats.
* @return value or {@code null} for none
*/
public java.lang.Integer getMinimumTransferableSeats() {
return minimumTransferableSeats;
}
/**
* When inserting a subscription, this is the minimum number of seats listed in the transfer order
* for this product. For example, if the customer has 20 users, the reseller cannot place a
* transfer order of 15 seats. The minimum is 20 seats.
* @param minimumTransferableSeats minimumTransferableSeats or {@code null} for none
*/
public TransferInfo setMinimumTransferableSeats(java.lang.Integer minimumTransferableSeats) {
this.minimumTransferableSeats = minimumTransferableSeats;
return this;
}
/**
* The time when transfer token or intent to transfer will expire. The time is in milliseconds
* using UNIX Epoch format.
* @return value or {@code null} for none
*/
public java.lang.Long getTransferabilityExpirationTime() {
return transferabilityExpirationTime;
}
/**
* The time when transfer token or intent to transfer will expire. The time is in milliseconds
* using UNIX Epoch format.
* @param transferabilityExpirationTime transferabilityExpirationTime or {@code null} for none
*/
public TransferInfo setTransferabilityExpirationTime(java.lang.Long transferabilityExpirationTime) {
this.transferabilityExpirationTime = transferabilityExpirationTime;
return this;
}
@Override
public TransferInfo set(String fieldName, Object value) {
return (TransferInfo) super.set(fieldName, value);
}
@Override
public TransferInfo clone() {
return (TransferInfo) super.clone();
}
}
/**
* The G Suite annual commitment and flexible payment plans can be in a 30-day free trial. For more
* information, see the API concepts.
*/
public static final class TrialSettings extends com.google.api.client.json.GenericJson {
/**
* Determines if a subscription's plan is in a 30-day free trial or not: - `true` — The plan is in
* trial. - `false` — The plan is not in trial.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean isInTrial;
/**
* Date when the trial ends. The value is in milliseconds using the UNIX Epoch format. See an
* example Epoch converter.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long trialEndTime;
/**
* Determines if a subscription's plan is in a 30-day free trial or not: - `true` — The plan is in
* trial. - `false` — The plan is not in trial.
* @return value or {@code null} for none
*/
public java.lang.Boolean getIsInTrial() {
return isInTrial;
}
/**
* Determines if a subscription's plan is in a 30-day free trial or not: - `true` — The plan is in
* trial. - `false` — The plan is not in trial.
* @param isInTrial isInTrial or {@code null} for none
*/
public TrialSettings setIsInTrial(java.lang.Boolean isInTrial) {
this.isInTrial = isInTrial;
return this;
}
/**
* Date when the trial ends. The value is in milliseconds using the UNIX Epoch format. See an
* example Epoch converter.
* @return value or {@code null} for none
*/
public java.lang.Long getTrialEndTime() {
return trialEndTime;
}
/**
* Date when the trial ends. The value is in milliseconds using the UNIX Epoch format. See an
* example Epoch converter.
* @param trialEndTime trialEndTime or {@code null} for none
*/
public TrialSettings setTrialEndTime(java.lang.Long trialEndTime) {
this.trialEndTime = trialEndTime;
return this;
}
@Override
public TrialSettings set(String fieldName, Object value) {
return (TrialSettings) super.set(fieldName, value);
}
@Override
public TrialSettings clone() {
return (TrialSettings) super.clone();
}
}
}
|
apache/hive | 36,904 | ql/src/java/org/apache/hadoop/hive/ql/parse/TaskCompiler.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.parse;
import com.google.common.collect.Interner;
import com.google.common.collect.Interners;
import com.google.common.collect.Lists;
import org.apache.commons.collections.*;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.HiveStatsUtils;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ResultFileFormat;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.ql.Context;
import org.apache.hadoop.hive.ql.ErrorMsg;
import org.apache.hadoop.hive.ql.QueryState;
import org.apache.hadoop.hive.ql.ddl.DDLDesc;
import org.apache.hadoop.hive.ql.ddl.DDLDescWithTableProperties;
import org.apache.hadoop.hive.ql.ddl.DDLTask;
import org.apache.hadoop.hive.ql.ddl.DDLWork;
import org.apache.hadoop.hive.ql.ddl.table.create.CreateTableDesc;
import org.apache.hadoop.hive.ql.ddl.view.create.CreateMaterializedViewDesc;
import org.apache.hadoop.hive.ql.ddl.view.materialized.alter.rewrite.AlterMaterializedViewRewriteDesc;
import org.apache.hadoop.hive.ql.ddl.view.materialized.update.MaterializedViewUpdateDesc;
import org.apache.hadoop.hive.ql.exec.FetchTask;
import org.apache.hadoop.hive.ql.exec.FileSinkOperator;
import org.apache.hadoop.hive.ql.exec.MoveTask;
import org.apache.hadoop.hive.ql.exec.Operator;
import org.apache.hadoop.hive.ql.exec.OperatorUtils;
import org.apache.hadoop.hive.ql.exec.StatsTask;
import org.apache.hadoop.hive.ql.exec.TableScanOperator;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.TaskFactory;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.hooks.ReadEntity;
import org.apache.hadoop.hive.ql.hooks.WriteEntity;
import org.apache.hadoop.hive.ql.io.AcidUtils;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.HiveUtils;
import org.apache.hadoop.hive.ql.metadata.Partition;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.optimizer.GenMapRedUtils;
import org.apache.hadoop.hive.ql.optimizer.NonBlockingOpDeDupProc;
import org.apache.hadoop.hive.ql.optimizer.SortedDynPartitionOptimizer;
import org.apache.hadoop.hive.ql.optimizer.correlation.ReduceSinkDeDuplication;
import org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer.AnalyzeRewriteContext;
import org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer.TableSpec;
import org.apache.hadoop.hive.ql.plan.BasicStatsWork;
import org.apache.hadoop.hive.ql.plan.ColumnStatsDesc;
import org.apache.hadoop.hive.ql.plan.FetchWork;
import org.apache.hadoop.hive.ql.plan.FileSinkDesc;
import org.apache.hadoop.hive.ql.plan.LoadFileDesc;
import org.apache.hadoop.hive.ql.plan.LoadTableDesc;
import org.apache.hadoop.hive.ql.plan.MoveWork;
import org.apache.hadoop.hive.ql.plan.PlanUtils;
import org.apache.hadoop.hive.ql.plan.StatsWork;
import org.apache.hadoop.hive.ql.plan.TableDesc;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hadoop.hive.ql.session.SessionState.LogHelper;
import org.apache.hadoop.hive.ql.stats.BasicStatsNoJobTask;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.hive.serde2.DefaultFetchFormatter;
import org.apache.hadoop.hive.serde2.Deserializer;
import org.apache.hadoop.hive.serde2.NoOpFetchFormatter;
import org.apache.hadoop.hive.serde2.SerDeUtils;
import org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe;
import org.apache.hadoop.hive.serde2.thrift.ThriftFormatter;
import org.apache.hadoop.hive.serde2.thrift.ThriftJDBCBinarySerDe;
import org.apache.hadoop.mapred.InputFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* TaskCompiler is the base class for classes that compile
* operator pipelines into tasks.
*/
public abstract class TaskCompiler {
protected final Logger LOG = LoggerFactory.getLogger(TaskCompiler.class);
// Assumes one instance of this + single-threaded compilation for each query.
protected Hive db;
protected LogHelper console;
protected QueryState queryState;
protected HiveConf conf;
public void init(QueryState queryState, LogHelper console, Hive db) {
this.queryState = queryState;
this.conf = queryState.getConf();
this.db = db;
this.console = console;
}
@SuppressWarnings("nls")
public void compile(final ParseContext pCtx,
final List<Task<?>> rootTasks,
final Set<ReadEntity> inputs, final Set<WriteEntity> outputs) throws SemanticException {
Context ctx = pCtx.getContext();
GlobalLimitCtx globalLimitCtx = pCtx.getGlobalLimitCtx();
List<Task<MoveWork>> mvTask = new ArrayList<>();
List<LoadTableDesc> loadTableWork = pCtx.getLoadTableWork();
List<LoadFileDesc> loadFileWork = pCtx.getLoadFileWork();
boolean isCStats = pCtx.getQueryProperties().isAnalyzeRewrite();
int outerQueryLimit = pCtx.getQueryProperties().getOuterQueryLimit();
boolean directInsert = false;
if (pCtx.getCreateTable() != null && pCtx.getCreateTable().getStorageHandler() != null) {
try {
directInsert =
HiveUtils.getStorageHandler(conf, pCtx.getCreateTable().getStorageHandler()).directInsert();
} catch (HiveException e) {
throw new SemanticException("Failed to load storage handler: " + e.getMessage());
}
}
if (pCtx.getCreateViewDesc() != null && pCtx.getCreateViewDesc().getStorageHandler() != null) {
try {
directInsert =
HiveUtils.getStorageHandler(conf, pCtx.getCreateViewDesc().getStorageHandler()).directInsert();
} catch (HiveException e) {
throw new SemanticException("Failed to load storage handler: " + e.getMessage());
}
}
if (pCtx.getFetchTask() != null) {
if (pCtx.getFetchTask().getTblDesc() == null) {
return;
}
pCtx.getFetchTask().getWork().setHiveServerQuery(SessionState.get().isHiveServerQuery());
TableDesc resultTab = pCtx.getFetchTask().getTblDesc();
// If the serializer is ThriftJDBCBinarySerDe, then it requires that NoOpFetchFormatter be used. But when it isn't,
// then either the ThriftFormatter or the DefaultFetchFormatter should be used.
if (!resultTab.getSerdeClassName().equalsIgnoreCase(ThriftJDBCBinarySerDe.class.getName())) {
if (SessionState.get().isHiveServerQuery()) {
conf.set(SerDeUtils.LIST_SINK_OUTPUT_FORMATTER,ThriftFormatter.class.getName());
} else {
String formatterName = conf.get(SerDeUtils.LIST_SINK_OUTPUT_FORMATTER);
if (formatterName == null || formatterName.isEmpty()) {
conf.set(SerDeUtils.LIST_SINK_OUTPUT_FORMATTER, DefaultFetchFormatter.class.getName());
}
}
}
return;
}
if (!pCtx.getQueryProperties().isAnalyzeCommand()) {
LOG.debug("Skipping optimize operator plan for analyze command.");
optimizeOperatorPlan(pCtx);
}
/*
* In case of a select, use a fetch task instead of a move task.
* If the select is from analyze table column rewrite, don't create a fetch task. Instead create
* a column stats task later.
*/
if (pCtx.getQueryProperties().isQuery() && !isCStats) {
if ((!loadTableWork.isEmpty()) || (loadFileWork.size() != 1)) {
throw new SemanticException(ErrorMsg.INVALID_LOAD_TABLE_FILE_WORK.getMsg());
}
LoadFileDesc loadFileDesc = loadFileWork.get(0);
String cols = loadFileDesc.getColumns();
String colTypes = loadFileDesc.getColumnTypes();
TableDesc resultTab = pCtx.getFetchTableDesc();
boolean shouldSetOutputFormatter = false;
if (resultTab == null) {
ResultFileFormat resFileFormat = conf.getResultFileFormat();
String fileFormat;
Class<? extends Deserializer> serdeClass;
if (SessionState.get().getIsUsingThriftJDBCBinarySerDe()
&& resFileFormat == ResultFileFormat.SEQUENCEFILE) {
fileFormat = resFileFormat.toString();
serdeClass = ThriftJDBCBinarySerDe.class;
shouldSetOutputFormatter = true;
} else if (resFileFormat == ResultFileFormat.SEQUENCEFILE) {
// file format is changed so that IF file sink provides list of files to fetch from (instead
// of whole directory) list status is done on files (which is what HiveSequenceFileInputFormat does)
fileFormat = "HiveSequenceFile";
serdeClass = LazySimpleSerDe.class;
} else {
// All other cases we use the defined file format and LazySimpleSerde
fileFormat = resFileFormat.toString();
serdeClass = LazySimpleSerDe.class;
}
resultTab = PlanUtils.getDefaultQueryOutputTableDesc(cols, colTypes, fileFormat, serdeClass);
} else {
shouldSetOutputFormatter = resultTab.getProperties().getProperty(serdeConstants.SERIALIZATION_LIB)
.equalsIgnoreCase(ThriftJDBCBinarySerDe.class.getName());
}
if (shouldSetOutputFormatter) {
// Set the fetch formatter to be a no-op for the ListSinkOperator, since we will
// read formatted thrift objects from the output SequenceFile written by Tasks.
conf.set(SerDeUtils.LIST_SINK_OUTPUT_FORMATTER, NoOpFetchFormatter.class.getName());
}
FetchWork fetch = new FetchWork(loadFileDesc.getSourcePath(), resultTab, outerQueryLimit);
boolean isHiveServerQuery = SessionState.get().isHiveServerQuery();
fetch.setHiveServerQuery(isHiveServerQuery);
fetch.setSource(pCtx.getFetchSource());
fetch.setSink(pCtx.getFetchSink());
if (isHiveServerQuery &&
null != resultTab &&
resultTab.getSerdeClassName().equalsIgnoreCase(ThriftJDBCBinarySerDe.class.getName()) &&
HiveConf.getBoolVar(conf, HiveConf.ConfVars.HIVE_SERVER2_THRIFT_RESULTSET_SERIALIZE_IN_TASKS)) {
fetch.setIsUsingThriftJDBCBinarySerDe(true);
} else {
fetch.setIsUsingThriftJDBCBinarySerDe(false);
}
// The idea here is to keep an object reference both in FileSink and in FetchTask for list of files
// to be fetched. During Job close file sink will populate the list and fetch task later will use it
// to fetch the results.
Collection<Operator<?>> tableScanOps =
Lists.<Operator<?>>newArrayList(pCtx.getTopOps().values());
Set<FileSinkOperator> fsOps = OperatorUtils.findOperators(tableScanOps, FileSinkOperator.class);
if(fsOps != null && fsOps.size() == 1) {
FileSinkOperator op = fsOps.iterator().next();
Set<FileStatus> filesToFetch = new HashSet<>();
op.getConf().setFilesToFetch(filesToFetch);
fetch.setFilesToFetch(filesToFetch);
}
pCtx.setFetchTask((FetchTask) TaskFactory.get(fetch));
// For the FetchTask, the limit optimization requires we fetch all the rows
// in memory and count how many rows we get. It's not practical if the
// limit factor is too big
int fetchLimit = HiveConf.getIntVar(conf, HiveConf.ConfVars.HIVE_LIMIT_OPT_MAX_FETCH);
if (globalLimitCtx.isEnable() && globalLimitCtx.getGlobalLimit() > fetchLimit) {
LOG.info("For FetchTask, LIMIT " + globalLimitCtx.getGlobalLimit() + " > " + fetchLimit
+ ". Doesn't qualify limit optimization.");
globalLimitCtx.disableOpt();
}
if (outerQueryLimit == 0) {
// Believe it or not, some tools do generate queries with limit 0 and than expect
// query to run quickly. Let's meet their requirement.
LOG.info("Limit 0. No query execution needed.");
return;
}
} else if (!isCStats) {
for (LoadTableDesc ltd : loadTableWork) {
Task<MoveWork> tsk = TaskFactory
.get(new MoveWork(pCtx.getQueryProperties().isCTAS() && pCtx.getCreateTable().isExternal(),
null, null, ltd, null, false));
mvTask.add(tsk);
}
boolean oneLoadFileForCtas = true;
for (LoadFileDesc lfd : loadFileWork) {
if (pCtx.getQueryProperties().isCTAS() || pCtx.getQueryProperties().isMaterializedView()) {
if (!oneLoadFileForCtas) { // should not have more than 1 load file for CTAS.
throw new SemanticException(
"One query is not expected to contain multiple CTAS loads statements");
}
setLoadFileLocation(pCtx, lfd);
oneLoadFileForCtas = false;
}
mvTask.add(TaskFactory.get(
new MoveWork(pCtx.getQueryProperties().isCTAS() && pCtx.getCreateTable().isExternal(), null, null, null,
lfd, false)));
}
}
generateTaskTree(rootTasks, pCtx, mvTask, inputs, outputs);
// For each task, set the key descriptor for the reducer
for (Task<?> rootTask : rootTasks) {
GenMapRedUtils.setKeyAndValueDescForTaskTree(rootTask);
}
// If a task contains an operator which instructs bucketizedhiveinputformat
// to be used, please do so
for (Task<?> rootTask : rootTasks) {
setInputFormat(rootTask);
}
if (directInsert) {
if (pCtx.getCreateTable() != null) {
CreateTableDesc crtTblDesc = pCtx.getCreateTable();
crtTblDesc.validate(conf);
Task<?> crtTask = TaskFactory.get(new DDLWork(inputs, outputs, crtTblDesc));
for (Task<?> rootTask : rootTasks) {
crtTask.addDependentTask(rootTask);
rootTasks.clear();
rootTasks.add(crtTask);
}
} else if (pCtx.getCreateViewDesc() != null) {
CreateMaterializedViewDesc createMaterializedViewDesc = pCtx.getCreateViewDesc();
Task<?> crtTask = TaskFactory.get(new DDLWork(inputs, outputs, createMaterializedViewDesc));
MaterializedViewUpdateDesc materializedViewUpdateDesc = new MaterializedViewUpdateDesc(
createMaterializedViewDesc.getViewName(), createMaterializedViewDesc.isRewriteEnabled(), false, false);
Task<?> updateTask = TaskFactory.get(new DDLWork(inputs, outputs, materializedViewUpdateDesc));
crtTask.addDependentTask(updateTask);
for (Task<?> rootTask : rootTasks) {
updateTask.addDependentTask(rootTask);
rootTasks.clear();
rootTasks.add(crtTask);
}
}
}
optimizeTaskPlan(rootTasks, pCtx, ctx);
/*
* If the query was the result of analyze table column compute statistics rewrite, create
* a column stats task instead of a fetch task to persist stats to the metastore.
* As per HIVE-15903, we will also collect table stats when user computes column stats.
* That means, if isCStats || !pCtx.getColumnStatsAutoGatherContexts().isEmpty()
* We need to collect table stats
* if isCStats, we need to include a basic stats task
* else it is ColumnStatsAutoGather, which should have a move task with a stats task already.
*/
if (isCStats || !pCtx.getColumnStatsAutoGatherContexts().isEmpty()) {
// map from tablename to task (ColumnStatsTask which includes a BasicStatsTask)
Map<String, StatsTask> map = new LinkedHashMap<>();
if (isCStats) {
if (rootTasks == null || rootTasks.size() != 1 || pCtx.getTopOps() == null
|| pCtx.getTopOps().size() != 1) {
throw new SemanticException("Can not find correct root task!");
}
try {
Task<?> root = rootTasks.iterator().next();
StatsTask tsk = (StatsTask) genTableStats(pCtx, pCtx.getTopOps().values()
.iterator().next(), root, outputs);
root.addDependentTask(tsk);
map.put(extractTableFullName(tsk), tsk);
} catch (HiveException e) {
throw new SemanticException(e);
}
genColumnStatsTask(pCtx.getAnalyzeRewrite(), loadFileWork, map, outerQueryLimit, 0);
} else {
Set<Task<?>> leafTasks = new LinkedHashSet<Task<?>>();
getLeafTasks(rootTasks, leafTasks);
List<Task<?>> nonStatsLeafTasks = new ArrayList<>();
for (Task<?> tsk : leafTasks) {
// map table name to the correct ColumnStatsTask
if (tsk instanceof StatsTask) {
map.put(extractTableFullName((StatsTask) tsk), (StatsTask) tsk);
} else {
nonStatsLeafTasks.add(tsk);
}
}
// add cStatsTask as a dependent of all the nonStatsLeafTasks
for (Task<?> tsk : nonStatsLeafTasks) {
for (Task<?> cStatsTask : map.values()) {
tsk.addDependentTask(cStatsTask);
}
}
for (ColumnStatsAutoGatherContext columnStatsAutoGatherContext : pCtx
.getColumnStatsAutoGatherContexts()) {
if (!columnStatsAutoGatherContext.isInsertInto()) {
genColumnStatsTask(columnStatsAutoGatherContext.getAnalyzeRewrite(),
columnStatsAutoGatherContext.getLoadFileWork(), map, outerQueryLimit, 0);
} else {
int numBitVector;
try {
numBitVector = HiveStatsUtils.getNumBitVectorsForNDVEstimation(conf);
} catch (Exception e) {
throw new SemanticException(e.getMessage());
}
genColumnStatsTask(columnStatsAutoGatherContext.getAnalyzeRewrite(),
columnStatsAutoGatherContext.getLoadFileWork(), map, outerQueryLimit, numBitVector);
}
}
}
}
decideExecMode(rootTasks, ctx, globalLimitCtx);
// for direct insert CTAS, we don't need this table creation DDL task, since the table will be created
// ahead of time by the non-native table
if (pCtx.getQueryProperties().isCTAS() && !pCtx.getCreateTable().isMaterialization() && !directInsert) {
// generate a DDL task and make it a dependent task of the leaf
CreateTableDesc crtTblDesc = pCtx.getCreateTable();
crtTblDesc.validate(conf);
Task<?> crtTblTask = TaskFactory.get(new DDLWork(inputs, outputs, crtTblDesc));
patchUpAfterCTASorMaterializedView(rootTasks, inputs, outputs, crtTblTask,
CollectionUtils.isEmpty(crtTblDesc.getPartColNames()));
} else if (pCtx.getQueryProperties().isMaterializedView() && !directInsert) {
// generate a DDL task and make it a dependent task of the leaf
CreateMaterializedViewDesc viewDesc = pCtx.getCreateViewDesc();
Task<?> crtViewTask = TaskFactory.get(new DDLWork(
inputs, outputs, viewDesc));
patchUpAfterCTASorMaterializedView(rootTasks, inputs, outputs, crtViewTask,
CollectionUtils.isEmpty(viewDesc.getPartColNames()));
} else if (pCtx.getMaterializedViewUpdateDesc() != null) {
// If there is a materialized view update desc, we create introduce it at the end
// of the tree.
MaterializedViewUpdateDesc materializedViewDesc = pCtx.getMaterializedViewUpdateDesc();
DDLWork ddlWork = new DDLWork(inputs, outputs, materializedViewDesc);
Set<Task<?>> leafTasks = new LinkedHashSet<Task<?>>();
getLeafTasks(rootTasks, leafTasks);
Task<?> materializedViewTask = TaskFactory.get(ddlWork, conf);
for (Task<?> task : leafTasks) {
task.addDependentTask(materializedViewTask);
}
}
if (globalLimitCtx.isEnable() && pCtx.getFetchTask() != null) {
LOG.info("set least row check for FetchTask: " + globalLimitCtx.getGlobalLimit());
pCtx.getFetchTask().getWork().setLeastNumRows(globalLimitCtx.getGlobalLimit());
}
if (globalLimitCtx.isEnable() && globalLimitCtx.getLastReduceLimitDesc() != null) {
LOG.info("set least row check for LimitDesc: " + globalLimitCtx.getGlobalLimit());
globalLimitCtx.getLastReduceLimitDesc().setLeastRows(globalLimitCtx.getGlobalLimit());
}
Interner<TableDesc> interner = Interners.newStrongInterner();
// Perform Final chores on generated Map works
// 1. Intern the table descriptors
// 2. Derive final explain attributes based on previous compilation.
GenMapRedUtils.finalMapWorkChores(rootTasks, pCtx.getConf(), interner);
}
private String extractTableFullName(StatsTask tsk) throws SemanticException {
return tsk.getWork().getFullTableName();
}
private Task<?> genTableStats(ParseContext parseContext, TableScanOperator tableScan, Task currentTask, final Set<WriteEntity> outputs)
throws HiveException {
Class<? extends InputFormat> inputFormat = tableScan.getConf().getTableMetadata()
.getInputFormatClass();
Table table = tableScan.getConf().getTableMetadata();
List<Partition> partitions = new ArrayList<>();
if (table.isPartitioned()) {
partitions.addAll(parseContext.getPrunedPartitions(tableScan).getPartitions());
for (Partition partn : partitions) {
LOG.trace("adding part: " + partn);
outputs.add(new WriteEntity(partn, WriteEntity.WriteType.DDL_NO_LOCK));
}
}
TableSpec tableSpec = new TableSpec(table, partitions);
tableScan.getConf().getTableMetadata().setTableSpec(tableSpec);
if (BasicStatsNoJobTask.canUseFooterScan(table, inputFormat)) {
// For ORC, there is no Tez Job for table stats.
StatsWork columnStatsWork = new StatsWork(table, parseContext.getConf());
columnStatsWork.setFooterScan();
// If partition is specified, get pruned partition list
if (partitions.size() > 0) {
columnStatsWork.addInputPartitions(parseContext.getPrunedPartitions(tableScan).getPartitions());
}
return TaskFactory.get(columnStatsWork);
} else {
BasicStatsWork statsWork = new BasicStatsWork(tableScan.getConf().getTableMetadata().getTableSpec());
statsWork.setIsExplicitAnalyze(true);
StatsWork columnStatsWork = new StatsWork(table, statsWork, parseContext.getConf());
columnStatsWork.collectStatsFromAggregator(tableScan.getConf());
columnStatsWork.setSourceTask(currentTask);
return TaskFactory.get(columnStatsWork);
}
}
private void setLoadFileLocation(
final ParseContext pCtx, LoadFileDesc lfd) throws SemanticException {
// CTAS; make the move task's destination directory the table's destination.
DDLDescWithTableProperties ddlDesc = pCtx.getQueryProperties().isCTAS() ?
pCtx.getCreateTable() : pCtx.getCreateViewDesc();
FileSinkDesc dataSink = ddlDesc.getAndUnsetWriter();
Long txnId = ddlDesc.getInitialWriteId();
String loc = ddlDesc.getLocation();
int stmtId = 0; // CTAS or CMV cannot be part of multi-txn stmt
Path location = (loc == null) ? getDefaultCtasOrCMVLocation(pCtx) : new Path(loc);
if (pCtx.getQueryProperties().isCTAS()) {
CreateTableDesc ctd = pCtx.getCreateTable();
if (HiveConf.getBoolVar(conf, HiveConf.ConfVars.CREATE_TABLE_AS_EXTERNAL)) {
ctd.getTblProps().put(hive_metastoreConstants.CTAS_LEGACY_CONFIG, "true"); // create as external table
}
try {
Table table = ctd.toTable(conf);
if (!ctd.isMaterialization()) {
table = db.getTranslateTableDryrun(table.getTTable());
}
org.apache.hadoop.hive.metastore.api.Table tTable = table.getTTable();
if (tTable.getSd() != null && tTable.getSd().getLocation() != null) {
location = new Path(tTable.getSd().getLocation());
}
ctd.getTblProps().remove(hive_metastoreConstants.CTAS_LEGACY_CONFIG);
ctd.fromTable(tTable);
} catch (HiveException ex) {
throw new SemanticException(ex);
}
pCtx.setCreateTable(ctd);
}
if (txnId != null) {
dataSink.setDirName(location);
location = new Path(location, AcidUtils.deltaSubdir(txnId, txnId, stmtId));
lfd.setSourcePath(location);
if (Utilities.FILE_OP_LOGGER.isTraceEnabled()) {
Utilities.FILE_OP_LOGGER.trace("Setting MM CTAS to " + location);
}
}
if (Utilities.FILE_OP_LOGGER.isTraceEnabled()) {
Utilities.FILE_OP_LOGGER.trace("Location for LFD is being set to "
+ location + "; moving from " + lfd.getSourcePath());
}
lfd.setTargetDir(location);
}
private Path getDefaultCtasOrCMVLocation(final ParseContext pCtx) throws SemanticException {
try {
String protoName = null, suffix = "";
boolean isExternal = false;
boolean createTableOrMVUseSuffix = HiveConf.getBoolVar(conf, HiveConf.ConfVars.HIVE_ACID_CREATE_TABLE_USE_SUFFIX)
|| HiveConf.getBoolVar(conf, HiveConf.ConfVars.HIVE_ACID_LOCKLESS_READS_ENABLED);
if (pCtx.getQueryProperties().isCTAS()) {
protoName = pCtx.getCreateTable().getDbTableName();
isExternal = pCtx.getCreateTable().isExternal();
createTableOrMVUseSuffix &= AcidUtils.isTransactionalTable(pCtx.getCreateTable());
suffix = Utilities.getTableOrMVSuffix(pCtx.getContext(), createTableOrMVUseSuffix);
} else if (pCtx.getQueryProperties().isMaterializedView()) {
protoName = pCtx.getCreateViewDesc().getViewName();
createTableOrMVUseSuffix &= AcidUtils.isTransactionalView(pCtx.getCreateViewDesc());
suffix = Utilities.getTableOrMVSuffix(pCtx.getContext(), createTableOrMVUseSuffix);
}
String[] names = Utilities.getDbTableName(protoName);
if (!db.databaseExists(names[0])) {
throw new SemanticException("ERROR: The database " + names[0] + " does not exist.");
}
Warehouse wh = new Warehouse(conf);
return wh.getDefaultTablePath(db.getDatabase(names[0]), names[1] + suffix, isExternal);
} catch (HiveException | MetaException e) {
throw new SemanticException(e);
}
}
private void patchUpAfterCTASorMaterializedView(List<Task<?>> rootTasks,
Set<ReadEntity> inputs, Set<WriteEntity> outputs, Task<?> createTask,
boolean createTaskAfterMoveTask) {
// clear the mapredWork output file from outputs for CTAS
// DDLWork at the tail of the chain will have the output
Iterator<WriteEntity> outIter = outputs.iterator();
while (outIter.hasNext()) {
switch (outIter.next().getType()) {
case DFS_DIR:
case LOCAL_DIR:
outIter.remove();
break;
default:
break;
}
}
// find all leaf tasks and make the DDLTask as a dependent task on all of them
Set<Task<?>> leaves = new LinkedHashSet<>();
getLeafTasks(rootTasks, leaves);
assert (leaves.size() > 0);
// Target task is supposed to be the last task
Task<?> targetTask = createTask;
for (Task<?> task : leaves) {
if (task instanceof StatsTask) {
// StatsTask require table to already exist
for (Task<?> parentOfStatsTask : task.getParentTasks()) {
if (parentOfStatsTask instanceof MoveTask && !createTaskAfterMoveTask) {
// For partitioned CTAS, we need to create the table before the move task
// as we need to create the partitions in metastore and for that we should
// have already registered the table
interleaveTask(parentOfStatsTask, createTask);
} else {
parentOfStatsTask.addDependentTask(createTask);
}
}
for (Task<?> parentOfCrtTblTask : createTask.getParentTasks()) {
parentOfCrtTblTask.removeDependentTask(task);
}
createTask.addDependentTask(task);
targetTask = task;
} else if (task instanceof MoveTask && !createTaskAfterMoveTask) {
// For partitioned CTAS, we need to create the table before the move task
// as we need to create the partitions in metastore and for that we should
// have already registered the table
interleaveTask(task, createTask);
targetTask = task;
} else {
task.addDependentTask(createTask);
}
}
// Add task to insert / delete materialized view from registry if needed
if (createTask instanceof DDLTask) {
DDLTask ddlTask = (DDLTask)createTask;
DDLWork work = ddlTask.getWork();
DDLDesc desc = work.getDDLDesc();
if (desc instanceof CreateMaterializedViewDesc) {
CreateMaterializedViewDesc createViewDesc = (CreateMaterializedViewDesc)desc;
String tableName = createViewDesc.getViewName();
boolean retrieveAndInclude = createViewDesc.isRewriteEnabled();
MaterializedViewUpdateDesc materializedViewUpdateDesc =
new MaterializedViewUpdateDesc(tableName, retrieveAndInclude, false, false);
DDLWork ddlWork = new DDLWork(inputs, outputs, materializedViewUpdateDesc);
targetTask.addDependentTask(TaskFactory.get(ddlWork, conf));
} else if (desc instanceof AlterMaterializedViewRewriteDesc) {
AlterMaterializedViewRewriteDesc alterMVRewriteDesc = (AlterMaterializedViewRewriteDesc)desc;
String tableName = alterMVRewriteDesc.getMaterializedViewName();
boolean retrieveAndInclude = alterMVRewriteDesc.isRewriteEnable();
boolean disableRewrite = !alterMVRewriteDesc.isRewriteEnable();
MaterializedViewUpdateDesc materializedViewUpdateDesc =
new MaterializedViewUpdateDesc(tableName, retrieveAndInclude, disableRewrite, false);
DDLWork ddlWork = new DDLWork(inputs, outputs, materializedViewUpdateDesc);
targetTask.addDependentTask(TaskFactory.get(ddlWork, conf));
}
}
}
/**
* Makes dependentTask dependent of task.
*/
private void interleaveTask(Task<?> dependentTask, Task<?> task) {
for (Task<?> parentOfStatsTask : dependentTask.getParentTasks()) {
parentOfStatsTask.addDependentTask(task);
}
for (Task<?> parentOfCrtTblTask : task.getParentTasks()) {
parentOfCrtTblTask.removeDependentTask(dependentTask);
}
task.addDependentTask(dependentTask);
}
/**
* A helper function to generate a column stats task on top of map-red task. The column stats
* task fetches from the output of the map-red task, constructs the column stats object and
* persists it to the metastore.
*
* This method generates a plan with a column stats task on top of map-red task and sets up the
* appropriate metadata to be used during execution.
*
*/
protected void genColumnStatsTask(AnalyzeRewriteContext analyzeRewrite,
List<LoadFileDesc> loadFileWork, Map<String, StatsTask> map,
int outerQueryLimit, int numBitVector) throws SemanticException {
FetchWork fetch;
String tableName = analyzeRewrite.getTableName();
List<String> colName = analyzeRewrite.getColName();
List<String> colType = analyzeRewrite.getColType();
boolean isTblLevel = analyzeRewrite.isTblLvl();
String cols = loadFileWork.get(0).getColumns();
String colTypes = loadFileWork.get(0).getColumnTypes();
TableDesc resultTab;
if (SessionState.get().isHiveServerQuery() && conf.getBoolVar(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_RESULTSET_SERIALIZE_IN_TASKS)) {
resultTab = PlanUtils.getDefaultQueryOutputTableDesc(cols, colTypes, ResultFileFormat.SEQUENCEFILE.toString(),
ThriftJDBCBinarySerDe.class);
} else {
resultTab = PlanUtils.getDefaultQueryOutputTableDesc(cols, colTypes, conf.getResultFileFormat().toString(),
LazySimpleSerDe.class);
}
fetch = new FetchWork(loadFileWork.get(0).getSourcePath(), resultTab, outerQueryLimit);
ColumnStatsDesc cStatsDesc = new ColumnStatsDesc(tableName,
colName, colType, isTblLevel, numBitVector, fetch);
StatsTask columnStatsTask = map.get(tableName);
if (columnStatsTask == null) {
throw new SemanticException("Can not find " + tableName + " in genColumnStatsTask");
} else {
columnStatsTask.getWork().setColStats(cStatsDesc);
}
}
/**
* Find all leaf tasks of the list of root tasks.
*/
private void getLeafTasks(List<Task<?>> rootTasks,
Set<Task<?>> leaves) {
for (Task<?> root : rootTasks) {
getLeafTasks(root, leaves);
}
}
private void getLeafTasks(Task<?> task,
Set<Task<?>> leaves) {
if (task.getDependentTasks() == null) {
if (!leaves.contains(task)) {
leaves.add(task);
}
} else {
getLeafTasks(task.getDependentTasks(), leaves);
}
}
/*
* Called to transform tasks into local tasks where possible/desirable
*/
protected abstract void decideExecMode(List<Task<?>> rootTasks, Context ctx,
GlobalLimitCtx globalLimitCtx) throws SemanticException;
/*
* Called at the beginning of the compile phase to have another chance to optimize the operator plan
*/
protected void optimizeOperatorPlan(ParseContext pCtxSet) throws SemanticException {
}
/*
* Called after the tasks have been generated to run another round of optimization
*/
protected abstract void optimizeTaskPlan(List<Task<?>> rootTasks,
ParseContext pCtx, Context ctx) throws SemanticException;
/*
* Called to set the appropriate input format for tasks
*/
protected abstract void setInputFormat(Task<?> rootTask);
/*
* Called to generate the tasks tree from the parse context/operator tree
*/
protected abstract void generateTaskTree(List<Task<?>> rootTasks, ParseContext pCtx,
List<Task<MoveWork>> mvTask, Set<ReadEntity> inputs, Set<WriteEntity> outputs) throws SemanticException;
/*
* Called for dynamic partitioning sort optimization.
*/
protected void runDynPartitionSortOptimizations(ParseContext parseContext, HiveConf hConf) throws SemanticException {
// run Sorted dynamic partition optimization
if(HiveConf.getBoolVar(hConf, HiveConf.ConfVars.DYNAMIC_PARTITIONING) &&
HiveConf.getVar(hConf, HiveConf.ConfVars.DYNAMIC_PARTITIONING_MODE).equals("nonstrict") &&
!HiveConf.getBoolVar(hConf, HiveConf.ConfVars.HIVE_OPT_LIST_BUCKETING)) {
new SortedDynPartitionOptimizer().transform(parseContext);
if(HiveConf.getBoolVar(hConf, HiveConf.ConfVars.HIVE_OPT_REDUCE_DEDUPLICATION)) {
// Dynamic sort partition adds an extra RS therefore need to de-dup
new ReduceSinkDeDuplication().transform(parseContext);
// there is an issue with dedup logic wherein SELECT is created with wrong columns
// NonBlockingOpDeDupProc fixes that
new NonBlockingOpDeDupProc().transform(parseContext);
}
}
}
/**
* Create a clone of the parse context
*/
public ParseContext getParseContext(ParseContext pCtx, List<Task<?>> rootTasks) {
ParseContext clone = new ParseContext(queryState,
pCtx.getOpToPartPruner(), pCtx.getOpToPartList(), pCtx.getTopOps(),
pCtx.getJoinOps(), pCtx.getSmbMapJoinOps(),
pCtx.getLoadTableWork(), pCtx.getLoadFileWork(),
pCtx.getColumnStatsAutoGatherContexts(), pCtx.getContext(),
pCtx.getIdToTableNameMap(), pCtx.getDestTableId(), pCtx.getUCtx(),
pCtx.getListMapJoinOpsNoReducer(),
pCtx.getPrunedPartitions(), pCtx.getTabNameToTabObject(), pCtx.getOpToSamplePruner(), pCtx.getGlobalLimitCtx(),
pCtx.getNameToSplitSample(), pCtx.getSemanticInputs(), rootTasks,
pCtx.getOpToPartToSkewedPruner(), pCtx.getViewAliasToInput(),
pCtx.getReduceSinkOperatorsAddedByEnforceBucketingSorting(),
pCtx.getAnalyzeRewrite(), pCtx.getCreateTable(),
pCtx.getCreateViewDesc(), pCtx.getMaterializedViewUpdateDesc(),
pCtx.getQueryProperties(), pCtx.getViewProjectToTableSchema());
clone.setFetchTask(pCtx.getFetchTask());
clone.setLineageInfo(pCtx.getLineageInfo());
clone.setMapJoinOps(pCtx.getMapJoinOps());
clone.setRsToRuntimeValuesInfoMap(pCtx.getRsToRuntimeValuesInfoMap());
clone.setRsToSemiJoinBranchInfo(pCtx.getRsToSemiJoinBranchInfo());
clone.setColExprToGBMap(pCtx.getColExprToGBMap());
clone.setSemiJoinHints(pCtx.getSemiJoinHints());
return clone;
}
}
|
googleapis/google-cloud-java | 36,521 | java-datalabeling/proto-google-cloud-datalabeling-v1beta1/src/main/java/com/google/cloud/datalabeling/v1beta1/Attempt.java | /*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/datalabeling/v1beta1/evaluation_job.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.datalabeling.v1beta1;
/**
*
*
* <pre>
* Records a failed evaluation job run.
* </pre>
*
* Protobuf type {@code google.cloud.datalabeling.v1beta1.Attempt}
*/
public final class Attempt extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.datalabeling.v1beta1.Attempt)
AttemptOrBuilder {
private static final long serialVersionUID = 0L;
// Use Attempt.newBuilder() to construct.
private Attempt(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Attempt() {
partialFailures_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new Attempt();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datalabeling.v1beta1.EvaluationJobOuterClass
.internal_static_google_cloud_datalabeling_v1beta1_Attempt_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datalabeling.v1beta1.EvaluationJobOuterClass
.internal_static_google_cloud_datalabeling_v1beta1_Attempt_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datalabeling.v1beta1.Attempt.class,
com.google.cloud.datalabeling.v1beta1.Attempt.Builder.class);
}
private int bitField0_;
public static final int ATTEMPT_TIME_FIELD_NUMBER = 1;
private com.google.protobuf.Timestamp attemptTime_;
/**
* <code>.google.protobuf.Timestamp attempt_time = 1;</code>
*
* @return Whether the attemptTime field is set.
*/
@java.lang.Override
public boolean hasAttemptTime() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <code>.google.protobuf.Timestamp attempt_time = 1;</code>
*
* @return The attemptTime.
*/
@java.lang.Override
public com.google.protobuf.Timestamp getAttemptTime() {
return attemptTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : attemptTime_;
}
/** <code>.google.protobuf.Timestamp attempt_time = 1;</code> */
@java.lang.Override
public com.google.protobuf.TimestampOrBuilder getAttemptTimeOrBuilder() {
return attemptTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : attemptTime_;
}
public static final int PARTIAL_FAILURES_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private java.util.List<com.google.rpc.Status> partialFailures_;
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
@java.lang.Override
public java.util.List<com.google.rpc.Status> getPartialFailuresList() {
return partialFailures_;
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.rpc.StatusOrBuilder>
getPartialFailuresOrBuilderList() {
return partialFailures_;
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
@java.lang.Override
public int getPartialFailuresCount() {
return partialFailures_.size();
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
@java.lang.Override
public com.google.rpc.Status getPartialFailures(int index) {
return partialFailures_.get(index);
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
@java.lang.Override
public com.google.rpc.StatusOrBuilder getPartialFailuresOrBuilder(int index) {
return partialFailures_.get(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getAttemptTime());
}
for (int i = 0; i < partialFailures_.size(); i++) {
output.writeMessage(2, partialFailures_.get(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.computeMessageSize(1, getAttemptTime());
}
for (int i = 0; i < partialFailures_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, partialFailures_.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.datalabeling.v1beta1.Attempt)) {
return super.equals(obj);
}
com.google.cloud.datalabeling.v1beta1.Attempt other =
(com.google.cloud.datalabeling.v1beta1.Attempt) obj;
if (hasAttemptTime() != other.hasAttemptTime()) return false;
if (hasAttemptTime()) {
if (!getAttemptTime().equals(other.getAttemptTime())) return false;
}
if (!getPartialFailuresList().equals(other.getPartialFailuresList())) 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 (hasAttemptTime()) {
hash = (37 * hash) + ATTEMPT_TIME_FIELD_NUMBER;
hash = (53 * hash) + getAttemptTime().hashCode();
}
if (getPartialFailuresCount() > 0) {
hash = (37 * hash) + PARTIAL_FAILURES_FIELD_NUMBER;
hash = (53 * hash) + getPartialFailuresList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.datalabeling.v1beta1.Attempt parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datalabeling.v1beta1.Attempt parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datalabeling.v1beta1.Attempt parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datalabeling.v1beta1.Attempt parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datalabeling.v1beta1.Attempt parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datalabeling.v1beta1.Attempt parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datalabeling.v1beta1.Attempt parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datalabeling.v1beta1.Attempt parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.datalabeling.v1beta1.Attempt parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.datalabeling.v1beta1.Attempt parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.datalabeling.v1beta1.Attempt parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datalabeling.v1beta1.Attempt parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.datalabeling.v1beta1.Attempt 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>
* Records a failed evaluation job run.
* </pre>
*
* Protobuf type {@code google.cloud.datalabeling.v1beta1.Attempt}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.datalabeling.v1beta1.Attempt)
com.google.cloud.datalabeling.v1beta1.AttemptOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datalabeling.v1beta1.EvaluationJobOuterClass
.internal_static_google_cloud_datalabeling_v1beta1_Attempt_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datalabeling.v1beta1.EvaluationJobOuterClass
.internal_static_google_cloud_datalabeling_v1beta1_Attempt_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datalabeling.v1beta1.Attempt.class,
com.google.cloud.datalabeling.v1beta1.Attempt.Builder.class);
}
// Construct using com.google.cloud.datalabeling.v1beta1.Attempt.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getAttemptTimeFieldBuilder();
getPartialFailuresFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
attemptTime_ = null;
if (attemptTimeBuilder_ != null) {
attemptTimeBuilder_.dispose();
attemptTimeBuilder_ = null;
}
if (partialFailuresBuilder_ == null) {
partialFailures_ = java.util.Collections.emptyList();
} else {
partialFailures_ = null;
partialFailuresBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.datalabeling.v1beta1.EvaluationJobOuterClass
.internal_static_google_cloud_datalabeling_v1beta1_Attempt_descriptor;
}
@java.lang.Override
public com.google.cloud.datalabeling.v1beta1.Attempt getDefaultInstanceForType() {
return com.google.cloud.datalabeling.v1beta1.Attempt.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.datalabeling.v1beta1.Attempt build() {
com.google.cloud.datalabeling.v1beta1.Attempt result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.datalabeling.v1beta1.Attempt buildPartial() {
com.google.cloud.datalabeling.v1beta1.Attempt result =
new com.google.cloud.datalabeling.v1beta1.Attempt(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(com.google.cloud.datalabeling.v1beta1.Attempt result) {
if (partialFailuresBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)) {
partialFailures_ = java.util.Collections.unmodifiableList(partialFailures_);
bitField0_ = (bitField0_ & ~0x00000002);
}
result.partialFailures_ = partialFailures_;
} else {
result.partialFailures_ = partialFailuresBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.datalabeling.v1beta1.Attempt result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.attemptTime_ =
attemptTimeBuilder_ == null ? attemptTime_ : attemptTimeBuilder_.build();
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.datalabeling.v1beta1.Attempt) {
return mergeFrom((com.google.cloud.datalabeling.v1beta1.Attempt) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.datalabeling.v1beta1.Attempt other) {
if (other == com.google.cloud.datalabeling.v1beta1.Attempt.getDefaultInstance()) return this;
if (other.hasAttemptTime()) {
mergeAttemptTime(other.getAttemptTime());
}
if (partialFailuresBuilder_ == null) {
if (!other.partialFailures_.isEmpty()) {
if (partialFailures_.isEmpty()) {
partialFailures_ = other.partialFailures_;
bitField0_ = (bitField0_ & ~0x00000002);
} else {
ensurePartialFailuresIsMutable();
partialFailures_.addAll(other.partialFailures_);
}
onChanged();
}
} else {
if (!other.partialFailures_.isEmpty()) {
if (partialFailuresBuilder_.isEmpty()) {
partialFailuresBuilder_.dispose();
partialFailuresBuilder_ = null;
partialFailures_ = other.partialFailures_;
bitField0_ = (bitField0_ & ~0x00000002);
partialFailuresBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getPartialFailuresFieldBuilder()
: null;
} else {
partialFailuresBuilder_.addAllMessages(other.partialFailures_);
}
}
}
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(getAttemptTimeFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
com.google.rpc.Status m =
input.readMessage(com.google.rpc.Status.parser(), extensionRegistry);
if (partialFailuresBuilder_ == null) {
ensurePartialFailuresIsMutable();
partialFailures_.add(m);
} else {
partialFailuresBuilder_.addMessage(m);
}
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.protobuf.Timestamp attemptTime_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
attemptTimeBuilder_;
/**
* <code>.google.protobuf.Timestamp attempt_time = 1;</code>
*
* @return Whether the attemptTime field is set.
*/
public boolean hasAttemptTime() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <code>.google.protobuf.Timestamp attempt_time = 1;</code>
*
* @return The attemptTime.
*/
public com.google.protobuf.Timestamp getAttemptTime() {
if (attemptTimeBuilder_ == null) {
return attemptTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: attemptTime_;
} else {
return attemptTimeBuilder_.getMessage();
}
}
/** <code>.google.protobuf.Timestamp attempt_time = 1;</code> */
public Builder setAttemptTime(com.google.protobuf.Timestamp value) {
if (attemptTimeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
attemptTime_ = value;
} else {
attemptTimeBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/** <code>.google.protobuf.Timestamp attempt_time = 1;</code> */
public Builder setAttemptTime(com.google.protobuf.Timestamp.Builder builderForValue) {
if (attemptTimeBuilder_ == null) {
attemptTime_ = builderForValue.build();
} else {
attemptTimeBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/** <code>.google.protobuf.Timestamp attempt_time = 1;</code> */
public Builder mergeAttemptTime(com.google.protobuf.Timestamp value) {
if (attemptTimeBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& attemptTime_ != null
&& attemptTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) {
getAttemptTimeBuilder().mergeFrom(value);
} else {
attemptTime_ = value;
}
} else {
attemptTimeBuilder_.mergeFrom(value);
}
if (attemptTime_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/** <code>.google.protobuf.Timestamp attempt_time = 1;</code> */
public Builder clearAttemptTime() {
bitField0_ = (bitField0_ & ~0x00000001);
attemptTime_ = null;
if (attemptTimeBuilder_ != null) {
attemptTimeBuilder_.dispose();
attemptTimeBuilder_ = null;
}
onChanged();
return this;
}
/** <code>.google.protobuf.Timestamp attempt_time = 1;</code> */
public com.google.protobuf.Timestamp.Builder getAttemptTimeBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getAttemptTimeFieldBuilder().getBuilder();
}
/** <code>.google.protobuf.Timestamp attempt_time = 1;</code> */
public com.google.protobuf.TimestampOrBuilder getAttemptTimeOrBuilder() {
if (attemptTimeBuilder_ != null) {
return attemptTimeBuilder_.getMessageOrBuilder();
} else {
return attemptTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: attemptTime_;
}
}
/** <code>.google.protobuf.Timestamp attempt_time = 1;</code> */
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
getAttemptTimeFieldBuilder() {
if (attemptTimeBuilder_ == null) {
attemptTimeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>(
getAttemptTime(), getParentForChildren(), isClean());
attemptTime_ = null;
}
return attemptTimeBuilder_;
}
private java.util.List<com.google.rpc.Status> partialFailures_ =
java.util.Collections.emptyList();
private void ensurePartialFailuresIsMutable() {
if (!((bitField0_ & 0x00000002) != 0)) {
partialFailures_ = new java.util.ArrayList<com.google.rpc.Status>(partialFailures_);
bitField0_ |= 0x00000002;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.rpc.Status, com.google.rpc.Status.Builder, com.google.rpc.StatusOrBuilder>
partialFailuresBuilder_;
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public java.util.List<com.google.rpc.Status> getPartialFailuresList() {
if (partialFailuresBuilder_ == null) {
return java.util.Collections.unmodifiableList(partialFailures_);
} else {
return partialFailuresBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public int getPartialFailuresCount() {
if (partialFailuresBuilder_ == null) {
return partialFailures_.size();
} else {
return partialFailuresBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public com.google.rpc.Status getPartialFailures(int index) {
if (partialFailuresBuilder_ == null) {
return partialFailures_.get(index);
} else {
return partialFailuresBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public Builder setPartialFailures(int index, com.google.rpc.Status value) {
if (partialFailuresBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePartialFailuresIsMutable();
partialFailures_.set(index, value);
onChanged();
} else {
partialFailuresBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public Builder setPartialFailures(int index, com.google.rpc.Status.Builder builderForValue) {
if (partialFailuresBuilder_ == null) {
ensurePartialFailuresIsMutable();
partialFailures_.set(index, builderForValue.build());
onChanged();
} else {
partialFailuresBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public Builder addPartialFailures(com.google.rpc.Status value) {
if (partialFailuresBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePartialFailuresIsMutable();
partialFailures_.add(value);
onChanged();
} else {
partialFailuresBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public Builder addPartialFailures(int index, com.google.rpc.Status value) {
if (partialFailuresBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePartialFailuresIsMutable();
partialFailures_.add(index, value);
onChanged();
} else {
partialFailuresBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public Builder addPartialFailures(com.google.rpc.Status.Builder builderForValue) {
if (partialFailuresBuilder_ == null) {
ensurePartialFailuresIsMutable();
partialFailures_.add(builderForValue.build());
onChanged();
} else {
partialFailuresBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public Builder addPartialFailures(int index, com.google.rpc.Status.Builder builderForValue) {
if (partialFailuresBuilder_ == null) {
ensurePartialFailuresIsMutable();
partialFailures_.add(index, builderForValue.build());
onChanged();
} else {
partialFailuresBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public Builder addAllPartialFailures(
java.lang.Iterable<? extends com.google.rpc.Status> values) {
if (partialFailuresBuilder_ == null) {
ensurePartialFailuresIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, partialFailures_);
onChanged();
} else {
partialFailuresBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public Builder clearPartialFailures() {
if (partialFailuresBuilder_ == null) {
partialFailures_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
} else {
partialFailuresBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public Builder removePartialFailures(int index) {
if (partialFailuresBuilder_ == null) {
ensurePartialFailuresIsMutable();
partialFailures_.remove(index);
onChanged();
} else {
partialFailuresBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public com.google.rpc.Status.Builder getPartialFailuresBuilder(int index) {
return getPartialFailuresFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public com.google.rpc.StatusOrBuilder getPartialFailuresOrBuilder(int index) {
if (partialFailuresBuilder_ == null) {
return partialFailures_.get(index);
} else {
return partialFailuresBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public java.util.List<? extends com.google.rpc.StatusOrBuilder>
getPartialFailuresOrBuilderList() {
if (partialFailuresBuilder_ != null) {
return partialFailuresBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(partialFailures_);
}
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public com.google.rpc.Status.Builder addPartialFailuresBuilder() {
return getPartialFailuresFieldBuilder()
.addBuilder(com.google.rpc.Status.getDefaultInstance());
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public com.google.rpc.Status.Builder addPartialFailuresBuilder(int index) {
return getPartialFailuresFieldBuilder()
.addBuilder(index, com.google.rpc.Status.getDefaultInstance());
}
/**
*
*
* <pre>
* Details of errors that occurred.
* </pre>
*
* <code>repeated .google.rpc.Status partial_failures = 2;</code>
*/
public java.util.List<com.google.rpc.Status.Builder> getPartialFailuresBuilderList() {
return getPartialFailuresFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.rpc.Status, com.google.rpc.Status.Builder, com.google.rpc.StatusOrBuilder>
getPartialFailuresFieldBuilder() {
if (partialFailuresBuilder_ == null) {
partialFailuresBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.rpc.Status,
com.google.rpc.Status.Builder,
com.google.rpc.StatusOrBuilder>(
partialFailures_,
((bitField0_ & 0x00000002) != 0),
getParentForChildren(),
isClean());
partialFailures_ = null;
}
return partialFailuresBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.datalabeling.v1beta1.Attempt)
}
// @@protoc_insertion_point(class_scope:google.cloud.datalabeling.v1beta1.Attempt)
private static final com.google.cloud.datalabeling.v1beta1.Attempt DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.datalabeling.v1beta1.Attempt();
}
public static com.google.cloud.datalabeling.v1beta1.Attempt getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<Attempt> PARSER =
new com.google.protobuf.AbstractParser<Attempt>() {
@java.lang.Override
public Attempt 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<Attempt> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Attempt> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.datalabeling.v1beta1.Attempt getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,587 | java-monitoring-metricsscope/proto-google-cloud-monitoring-metricsscope-v1/src/main/java/com/google/monitoring/metricsscope/v1/CreateMonitoredProjectRequest.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/metricsscope/v1/metrics_scopes.proto
// Protobuf Java Version: 3.25.8
package com.google.monitoring.metricsscope.v1;
/**
*
*
* <pre>
* Request for the `CreateMonitoredProject` method.
* </pre>
*
* Protobuf type {@code google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest}
*/
public final class CreateMonitoredProjectRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest)
CreateMonitoredProjectRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateMonitoredProjectRequest.newBuilder() to construct.
private CreateMonitoredProjectRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateMonitoredProjectRequest() {
parent_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateMonitoredProjectRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.monitoring.metricsscope.v1.MetricsScopesProto
.internal_static_google_monitoring_metricsscope_v1_CreateMonitoredProjectRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.metricsscope.v1.MetricsScopesProto
.internal_static_google_monitoring_metricsscope_v1_CreateMonitoredProjectRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest.class,
com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The resource name of the existing `Metrics Scope` that will monitor this
* project.
* Example:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The resource name of the existing `Metrics Scope` that will monitor this
* project.
* Example:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}`
* </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 MONITORED_PROJECT_FIELD_NUMBER = 2;
private com.google.monitoring.metricsscope.v1.MonitoredProject monitoredProject_;
/**
*
*
* <pre>
* Required. The initial `MonitoredProject` configuration.
* Specify only the `monitored_project.name` field. All other fields are
* ignored. The `monitored_project.name` must be in the format:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}/projects/{MONITORED_PROJECT_ID_OR_NUMBER}`
* </pre>
*
* <code>
* .google.monitoring.metricsscope.v1.MonitoredProject monitored_project = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the monitoredProject field is set.
*/
@java.lang.Override
public boolean hasMonitoredProject() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The initial `MonitoredProject` configuration.
* Specify only the `monitored_project.name` field. All other fields are
* ignored. The `monitored_project.name` must be in the format:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}/projects/{MONITORED_PROJECT_ID_OR_NUMBER}`
* </pre>
*
* <code>
* .google.monitoring.metricsscope.v1.MonitoredProject monitored_project = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The monitoredProject.
*/
@java.lang.Override
public com.google.monitoring.metricsscope.v1.MonitoredProject getMonitoredProject() {
return monitoredProject_ == null
? com.google.monitoring.metricsscope.v1.MonitoredProject.getDefaultInstance()
: monitoredProject_;
}
/**
*
*
* <pre>
* Required. The initial `MonitoredProject` configuration.
* Specify only the `monitored_project.name` field. All other fields are
* ignored. The `monitored_project.name` must be in the format:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}/projects/{MONITORED_PROJECT_ID_OR_NUMBER}`
* </pre>
*
* <code>
* .google.monitoring.metricsscope.v1.MonitoredProject monitored_project = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.monitoring.metricsscope.v1.MonitoredProjectOrBuilder
getMonitoredProjectOrBuilder() {
return monitoredProject_ == null
? com.google.monitoring.metricsscope.v1.MonitoredProject.getDefaultInstance()
: monitoredProject_;
}
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, getMonitoredProject());
}
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, getMonitoredProject());
}
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.metricsscope.v1.CreateMonitoredProjectRequest)) {
return super.equals(obj);
}
com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest other =
(com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (hasMonitoredProject() != other.hasMonitoredProject()) return false;
if (hasMonitoredProject()) {
if (!getMonitoredProject().equals(other.getMonitoredProject())) 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 (hasMonitoredProject()) {
hash = (37 * hash) + MONITORED_PROJECT_FIELD_NUMBER;
hash = (53 * hash) + getMonitoredProject().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest 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.metricsscope.v1.CreateMonitoredProjectRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest 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.metricsscope.v1.CreateMonitoredProjectRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest 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.metricsscope.v1.CreateMonitoredProjectRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest
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.metricsscope.v1.CreateMonitoredProjectRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest 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.metricsscope.v1.CreateMonitoredProjectRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request for the `CreateMonitoredProject` method.
* </pre>
*
* Protobuf type {@code google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest)
com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.monitoring.metricsscope.v1.MetricsScopesProto
.internal_static_google_monitoring_metricsscope_v1_CreateMonitoredProjectRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.metricsscope.v1.MetricsScopesProto
.internal_static_google_monitoring_metricsscope_v1_CreateMonitoredProjectRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest.class,
com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest.Builder.class);
}
// Construct using
// com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getMonitoredProjectFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
monitoredProject_ = null;
if (monitoredProjectBuilder_ != null) {
monitoredProjectBuilder_.dispose();
monitoredProjectBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.monitoring.metricsscope.v1.MetricsScopesProto
.internal_static_google_monitoring_metricsscope_v1_CreateMonitoredProjectRequest_descriptor;
}
@java.lang.Override
public com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest
getDefaultInstanceForType() {
return com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest build() {
com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest buildPartial() {
com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest result =
new com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.monitoredProject_ =
monitoredProjectBuilder_ == null ? monitoredProject_ : monitoredProjectBuilder_.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.monitoring.metricsscope.v1.CreateMonitoredProjectRequest) {
return mergeFrom(
(com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest other) {
if (other
== com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest
.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasMonitoredProject()) {
mergeMonitoredProject(other.getMonitoredProject());
}
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(
getMonitoredProjectFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The resource name of the existing `Metrics Scope` that will monitor this
* project.
* Example:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The resource name of the existing `Metrics Scope` that will monitor this
* project.
* Example:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The resource name of the existing `Metrics Scope` that will monitor this
* project.
* Example:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The resource name of the existing `Metrics Scope` that will monitor this
* project.
* Example:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The resource name of the existing `Metrics Scope` that will monitor this
* project.
* Example:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}`
* </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.monitoring.metricsscope.v1.MonitoredProject monitoredProject_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.metricsscope.v1.MonitoredProject,
com.google.monitoring.metricsscope.v1.MonitoredProject.Builder,
com.google.monitoring.metricsscope.v1.MonitoredProjectOrBuilder>
monitoredProjectBuilder_;
/**
*
*
* <pre>
* Required. The initial `MonitoredProject` configuration.
* Specify only the `monitored_project.name` field. All other fields are
* ignored. The `monitored_project.name` must be in the format:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}/projects/{MONITORED_PROJECT_ID_OR_NUMBER}`
* </pre>
*
* <code>
* .google.monitoring.metricsscope.v1.MonitoredProject monitored_project = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the monitoredProject field is set.
*/
public boolean hasMonitoredProject() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The initial `MonitoredProject` configuration.
* Specify only the `monitored_project.name` field. All other fields are
* ignored. The `monitored_project.name` must be in the format:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}/projects/{MONITORED_PROJECT_ID_OR_NUMBER}`
* </pre>
*
* <code>
* .google.monitoring.metricsscope.v1.MonitoredProject monitored_project = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The monitoredProject.
*/
public com.google.monitoring.metricsscope.v1.MonitoredProject getMonitoredProject() {
if (monitoredProjectBuilder_ == null) {
return monitoredProject_ == null
? com.google.monitoring.metricsscope.v1.MonitoredProject.getDefaultInstance()
: monitoredProject_;
} else {
return monitoredProjectBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The initial `MonitoredProject` configuration.
* Specify only the `monitored_project.name` field. All other fields are
* ignored. The `monitored_project.name` must be in the format:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}/projects/{MONITORED_PROJECT_ID_OR_NUMBER}`
* </pre>
*
* <code>
* .google.monitoring.metricsscope.v1.MonitoredProject monitored_project = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setMonitoredProject(
com.google.monitoring.metricsscope.v1.MonitoredProject value) {
if (monitoredProjectBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
monitoredProject_ = value;
} else {
monitoredProjectBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The initial `MonitoredProject` configuration.
* Specify only the `monitored_project.name` field. All other fields are
* ignored. The `monitored_project.name` must be in the format:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}/projects/{MONITORED_PROJECT_ID_OR_NUMBER}`
* </pre>
*
* <code>
* .google.monitoring.metricsscope.v1.MonitoredProject monitored_project = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setMonitoredProject(
com.google.monitoring.metricsscope.v1.MonitoredProject.Builder builderForValue) {
if (monitoredProjectBuilder_ == null) {
monitoredProject_ = builderForValue.build();
} else {
monitoredProjectBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The initial `MonitoredProject` configuration.
* Specify only the `monitored_project.name` field. All other fields are
* ignored. The `monitored_project.name` must be in the format:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}/projects/{MONITORED_PROJECT_ID_OR_NUMBER}`
* </pre>
*
* <code>
* .google.monitoring.metricsscope.v1.MonitoredProject monitored_project = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeMonitoredProject(
com.google.monitoring.metricsscope.v1.MonitoredProject value) {
if (monitoredProjectBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& monitoredProject_ != null
&& monitoredProject_
!= com.google.monitoring.metricsscope.v1.MonitoredProject.getDefaultInstance()) {
getMonitoredProjectBuilder().mergeFrom(value);
} else {
monitoredProject_ = value;
}
} else {
monitoredProjectBuilder_.mergeFrom(value);
}
if (monitoredProject_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The initial `MonitoredProject` configuration.
* Specify only the `monitored_project.name` field. All other fields are
* ignored. The `monitored_project.name` must be in the format:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}/projects/{MONITORED_PROJECT_ID_OR_NUMBER}`
* </pre>
*
* <code>
* .google.monitoring.metricsscope.v1.MonitoredProject monitored_project = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearMonitoredProject() {
bitField0_ = (bitField0_ & ~0x00000002);
monitoredProject_ = null;
if (monitoredProjectBuilder_ != null) {
monitoredProjectBuilder_.dispose();
monitoredProjectBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The initial `MonitoredProject` configuration.
* Specify only the `monitored_project.name` field. All other fields are
* ignored. The `monitored_project.name` must be in the format:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}/projects/{MONITORED_PROJECT_ID_OR_NUMBER}`
* </pre>
*
* <code>
* .google.monitoring.metricsscope.v1.MonitoredProject monitored_project = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.monitoring.metricsscope.v1.MonitoredProject.Builder
getMonitoredProjectBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getMonitoredProjectFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The initial `MonitoredProject` configuration.
* Specify only the `monitored_project.name` field. All other fields are
* ignored. The `monitored_project.name` must be in the format:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}/projects/{MONITORED_PROJECT_ID_OR_NUMBER}`
* </pre>
*
* <code>
* .google.monitoring.metricsscope.v1.MonitoredProject monitored_project = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.monitoring.metricsscope.v1.MonitoredProjectOrBuilder
getMonitoredProjectOrBuilder() {
if (monitoredProjectBuilder_ != null) {
return monitoredProjectBuilder_.getMessageOrBuilder();
} else {
return monitoredProject_ == null
? com.google.monitoring.metricsscope.v1.MonitoredProject.getDefaultInstance()
: monitoredProject_;
}
}
/**
*
*
* <pre>
* Required. The initial `MonitoredProject` configuration.
* Specify only the `monitored_project.name` field. All other fields are
* ignored. The `monitored_project.name` must be in the format:
* `locations/global/metricsScopes/{SCOPING_PROJECT_ID_OR_NUMBER}/projects/{MONITORED_PROJECT_ID_OR_NUMBER}`
* </pre>
*
* <code>
* .google.monitoring.metricsscope.v1.MonitoredProject monitored_project = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.metricsscope.v1.MonitoredProject,
com.google.monitoring.metricsscope.v1.MonitoredProject.Builder,
com.google.monitoring.metricsscope.v1.MonitoredProjectOrBuilder>
getMonitoredProjectFieldBuilder() {
if (monitoredProjectBuilder_ == null) {
monitoredProjectBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.metricsscope.v1.MonitoredProject,
com.google.monitoring.metricsscope.v1.MonitoredProject.Builder,
com.google.monitoring.metricsscope.v1.MonitoredProjectOrBuilder>(
getMonitoredProject(), getParentForChildren(), isClean());
monitoredProject_ = null;
}
return monitoredProjectBuilder_;
}
@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.metricsscope.v1.CreateMonitoredProjectRequest)
}
// @@protoc_insertion_point(class_scope:google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest)
private static final com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest();
}
public static com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateMonitoredProjectRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateMonitoredProjectRequest>() {
@java.lang.Override
public CreateMonitoredProjectRequest 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<CreateMonitoredProjectRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateMonitoredProjectRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.monitoring.metricsscope.v1.CreateMonitoredProjectRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.